@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
@@ -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
  'use strict';
8
8
 
@@ -90,6 +90,14 @@ function canonicalJson(value) {
90
90
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
91
91
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
92
92
  }
93
+ /**
94
+ * `storage`: the buyer turns on the cloud copy of the extension's settings. The
95
+ * hosted page shows the storage disclosure; the claim records consent. Additive:
96
+ * a session without a purpose is a plain restore.
97
+ */
98
+ const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
99
+ /** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
100
+ const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
93
101
 
94
102
  const ERROR_CODES = {
95
103
  INVALID_CONFIG: 'INVALID_CONFIG',
@@ -161,7 +169,7 @@ async function getOrCreateEndUserRef(storage) {
161
169
  * developed with no backend: offers and entitlements come from `mockData`, a
162
170
  * mock checkout completes after `claimAfterPolls` polls and grants the SKU.
163
171
  */
164
- const DAY_MS = 24 * 60 * 60 * 1000;
172
+ const DAY_MS$1 = 24 * 60 * 60 * 1000;
165
173
  /** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
166
174
  function mockConsent(value) {
167
175
  const consent = value;
@@ -179,6 +187,10 @@ class MockTransport {
179
187
  this.claimAfterPolls = data.claimAfterPolls ?? 1;
180
188
  this.withdrawalWaiver =
181
189
  data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
190
+ this.seller = data.seller;
191
+ this.trial = null;
192
+ if (data.trial)
193
+ this.setTrial(data.trial.days, data.trial.startedAt);
182
194
  }
183
195
  async call(procedure, _kind, input) {
184
196
  switch (procedure) {
@@ -200,6 +212,14 @@ class MockTransport {
200
212
  setEntitlements(items) {
201
213
  this.entitlements = [...items];
202
214
  }
215
+ /** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
216
+ setTrial(days, startedAt = new Date().toISOString()) {
217
+ const start = Date.parse(startedAt);
218
+ this.trial =
219
+ days === null || !Number.isFinite(start)
220
+ ? null
221
+ : { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
222
+ }
203
223
  cancelSession(sessionId) {
204
224
  const session = this.sessions.get(sessionId);
205
225
  if (session)
@@ -219,6 +239,7 @@ class MockTransport {
219
239
  offers: [...this.offers],
220
240
  entitlementPublicKey: null,
221
241
  withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
242
+ ...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
222
243
  };
223
244
  }
224
245
  createCheckout(sku, withdrawalWaiver) {
@@ -256,7 +277,7 @@ class MockTransport {
256
277
  grant(sku) {
257
278
  const offer = this.offers.find((o) => o.sku === sku);
258
279
  const expiresAt = offer?.kind === 'subscription'
259
- ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
280
+ ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
260
281
  : null;
261
282
  this.entitlements = [
262
283
  ...this.entitlements.filter((item) => item.sku !== sku),
@@ -278,6 +299,7 @@ class MockTransport {
278
299
  endUserRef,
279
300
  entitlements: [...this.entitlements],
280
301
  issuedAt: new Date().toISOString(),
302
+ ...(this.trial ? { trial: { ...this.trial } } : {}),
281
303
  },
282
304
  signature: null,
283
305
  alg: null,
@@ -291,12 +313,17 @@ class PayApi {
291
313
  this.transport = transport;
292
314
  this.publishableKey = publishableKey;
293
315
  }
294
- /** `locale` opens the hosted recovery page (and its email) in the user's language. */
295
- createRestoreSession(claimChallenge, locale) {
316
+ /**
317
+ * `locale` opens the hosted recovery page (and its email) in the user's language.
318
+ * `purpose` is sent only for `storage`: a plain restore keeps the request older
319
+ * BFFs know, and their non-strict zod input strips the key anyway.
320
+ */
321
+ createRestoreSession(claimChallenge, locale, purpose) {
296
322
  return this.transport.call('pay.createRestoreSession', 'mutation', {
297
323
  publishableKey: this.publishableKey,
298
324
  claimChallenge,
299
325
  ...(locale ? { locale } : {}),
326
+ ...(purpose === 'storage' ? { purpose } : {}),
300
327
  });
301
328
  }
302
329
  claimRestoreSession(sessionId, claimSecret) {
@@ -335,10 +362,12 @@ class PayApi {
335
362
  endUserRef,
336
363
  });
337
364
  }
338
- getEntitlement(endUserRef) {
365
+ /** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
366
+ getEntitlement(endUserRef, trialStartedHint) {
339
367
  return this.transport.call('pay.getEntitlement', 'query', {
340
368
  publishableKey: this.publishableKey,
341
369
  endUserRef,
370
+ ...(trialStartedHint ? { trialStartedHint } : {}),
342
371
  });
343
372
  }
344
373
  getPortalUrl(endUserRef, customerId, locale) {
@@ -736,6 +765,118 @@ var checkout = /*#__PURE__*/Object.freeze({
736
765
  openInNewTab: openInNewTab
737
766
  });
738
767
 
768
+ /**
769
+ * Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
770
+ * token: only a verified restore claim issues it; this module keeps it in the
771
+ * SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
772
+ * through `cloudBackupToken()`. The token is never logged and never answered to
773
+ * a content script: route those calls to the background.
774
+ */
775
+ const REQUEST_TIMEOUT_MS = 10000;
776
+ /** True in a content script, where the token must not be handed out. */
777
+ function inContentScript() {
778
+ const g = globalThis;
779
+ return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
780
+ }
781
+ class CloudBackup {
782
+ constructor(options) {
783
+ this.options = options;
784
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
785
+ }
786
+ get storageKey() {
787
+ return `extenshi-pay:${this.options.publishableKey}:storageToken`;
788
+ }
789
+ /** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
790
+ async accept(grant) {
791
+ if (!grant || typeof grant !== 'object')
792
+ return undefined;
793
+ try {
794
+ if (grant.state === 'granted') {
795
+ if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
796
+ return undefined;
797
+ await this.options.storage.set(this.storageKey, grant.token);
798
+ return 'on';
799
+ }
800
+ if (grant.state === 'unavailable') {
801
+ await this.options.storage.remove(this.storageKey);
802
+ return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
803
+ }
804
+ }
805
+ catch {
806
+ logger.warn('cloud backup state could not be saved');
807
+ }
808
+ return undefined;
809
+ }
810
+ async token() {
811
+ this.assertTrustedContext();
812
+ const value = await this.options.storage.get(this.storageKey);
813
+ return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
814
+ }
815
+ /** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
816
+ async disable() {
817
+ const token = await this.token();
818
+ if (!token)
819
+ return;
820
+ if (!this.options.mock) {
821
+ const status = await this.request('/v1/storage/grant', token);
822
+ if (status !== 401)
823
+ this.throwUnlessOk(status);
824
+ }
825
+ await this.options.storage.remove(this.storageKey);
826
+ }
827
+ /** Deletes the buyer's cloud copy and turns the backup off on every device. */
828
+ async delete() {
829
+ const token = await this.token();
830
+ if (!token)
831
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
832
+ if (!this.options.mock) {
833
+ const status = await this.request('/v1/storage/data', token);
834
+ if (status === 401) {
835
+ // The server no longer accepts this token, so it is useless here; the copy was not deleted.
836
+ await this.options.storage.remove(this.storageKey);
837
+ 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 });
838
+ }
839
+ this.throwUnlessOk(status);
840
+ }
841
+ await this.options.storage.remove(this.storageKey);
842
+ }
843
+ assertTrustedContext() {
844
+ if (inContentScript())
845
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
846
+ }
847
+ throwUnlessOk(status) {
848
+ if (status >= 200 && status < 300)
849
+ return;
850
+ if (status === 429)
851
+ throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
852
+ if (status >= 500)
853
+ throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
854
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
855
+ }
856
+ async request(path, token) {
857
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
858
+ const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
859
+ try {
860
+ const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
861
+ method: 'DELETE',
862
+ headers: { Authorization: `Bearer ${token}` },
863
+ credentials: 'omit',
864
+ signal: controller?.signal,
865
+ });
866
+ return response.status;
867
+ }
868
+ catch (error) {
869
+ if (controller?.signal.aborted)
870
+ throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
871
+ throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
872
+ }
873
+ finally {
874
+ if (timer !== null)
875
+ clearTimeout(timer);
876
+ }
877
+ }
878
+ }
879
+
739
880
  /** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
740
881
  const LIVE_STATUSES = new Set(['active', 'grace']);
741
882
  function isLive(item) {
@@ -790,9 +931,17 @@ Object.freeze(EMPTY_ENTITLEMENT.features);
790
931
  /**
791
932
  * Ed25519 verification of the entitlement projection.
792
933
  *
793
- * Tamper resistance, not DRM. Trust comes from the developer's bundled key or
794
- * a key fetched over HTTPS, never from editable extension storage. Callers must
795
- * deny access for both invalid and unverified envelopes outside explicit mocks.
934
+ * Tamper resistance, not DRM. Callers must deny access for both invalid and
935
+ * unverified envelopes outside explicit mocks.
936
+ *
937
+ * Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
938
+ * 1. the key the server returned over HTTPS in this session;
939
+ * 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
940
+ * verification without a round-trip: a key read from extension storage is then never used;
941
+ * 3. without a bundled key, the server key saved in `storage.local` next to the
942
+ * license cache, so a restart with no network can still verify the cache.
943
+ * When none of them verifies an envelope the server is asked for its current key once
944
+ * (a rotated key), and that answer decides.
796
945
  */
797
946
  function base64ToBytes(base64) {
798
947
  const binary = atob(base64);
@@ -827,6 +976,156 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
827
976
  return 'invalid';
828
977
  }
829
978
  }
979
+ const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
980
+ /**
981
+ * `invalid` only when the server's current key was checked too (or the envelope carries no
982
+ * signature at all). A mismatch against known keys while the server is unreachable is
983
+ * `unverified`: it may be a rotated key, and no paid access is granted either way.
984
+ */
985
+ async function verifyWithKeys(envelope, source) {
986
+ if (!envelope.signature || envelope.alg !== 'ed25519')
987
+ return { verdict: 'invalid', key: null };
988
+ let known = [];
989
+ try {
990
+ known = await source.known();
991
+ }
992
+ catch {
993
+ known = [];
994
+ }
995
+ let mismatch = false;
996
+ for (const key of known) {
997
+ const verdict = await verifyEntitlementSignature(envelope, key);
998
+ if (verdict === 'valid')
999
+ return { verdict, key };
1000
+ if (verdict === 'invalid')
1001
+ mismatch = true;
1002
+ }
1003
+ let current;
1004
+ try {
1005
+ current = await source.fetchCurrent();
1006
+ }
1007
+ catch {
1008
+ return { verdict: 'unverified', key: null };
1009
+ }
1010
+ if (current && !known.includes(current)) {
1011
+ const verdict = await verifyEntitlementSignature(envelope, current);
1012
+ return { verdict, key: verdict === 'valid' ? current : null };
1013
+ }
1014
+ return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
1015
+ }
1016
+
1017
+ /**
1018
+ * The free trial an application configures on the server (`trialDays`).
1019
+ *
1020
+ * The server starts one clock per installation at its first license read and
1021
+ * signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
1022
+ * the verified license like paid access does: no start date in extension
1023
+ * storage, nothing a device clock or a storage edit can move. Offline, the
1024
+ * cached license answers for up to 48 hours.
1025
+ *
1026
+ * `trial:ending` / `trial:ended` fire once per installation and trial (the
1027
+ * marker is kept in the SDK's storage), and not while the user has paid
1028
+ * access. Render state from `getTrial()`; the events are one-time notices.
1029
+ */
1030
+ const DAY_MS = 24 * 60 * 60 * 1000;
1031
+ /** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
1032
+ const MAX_TIMER_MS$1 = DAY_MS;
1033
+ /** The trial as of `clock`, or null when the license carries none (or a malformed one). */
1034
+ function trialState(trial, clock) {
1035
+ if (!trial)
1036
+ return null;
1037
+ const startedAt = Date.parse(trial.startedAt);
1038
+ const endsAt = Date.parse(trial.endsAt);
1039
+ if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
1040
+ return null;
1041
+ // The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
1042
+ const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
1043
+ const left = endsAt - now;
1044
+ return {
1045
+ active: left > 0 && clock.checked,
1046
+ startedAt: trial.startedAt,
1047
+ endsAt: trial.endsAt,
1048
+ daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
1049
+ requiresOnlineCheck: left > 0 && !clock.checked,
1050
+ };
1051
+ }
1052
+ /** The feedback form address with `src=trial_end`; null unless it is a plain HTTPS URL. No installation id is added. */
1053
+ function trialFeedbackUrl(raw) {
1054
+ if (!raw)
1055
+ return null;
1056
+ let url;
1057
+ try {
1058
+ url = new URL(raw);
1059
+ }
1060
+ catch {
1061
+ return null;
1062
+ }
1063
+ if (url.protocol !== 'https:' || url.username || url.password)
1064
+ return null;
1065
+ url.searchParams.set('src', 'trial_end');
1066
+ return url.toString();
1067
+ }
1068
+ class TrialNotifier {
1069
+ constructor(options) {
1070
+ this.options = options;
1071
+ this.timer = null;
1072
+ this.running = false;
1073
+ this.pending = Promise.resolve();
1074
+ }
1075
+ start() {
1076
+ this.running = true;
1077
+ void this.evaluate();
1078
+ }
1079
+ stop() {
1080
+ this.running = false;
1081
+ this.clearTimer();
1082
+ }
1083
+ /** Checks the held license; serialized, so two refreshes never send one event twice. */
1084
+ evaluate() {
1085
+ this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
1086
+ return this.pending;
1087
+ }
1088
+ async check() {
1089
+ if (!this.running)
1090
+ return;
1091
+ this.clearTimer();
1092
+ const trial = this.options.getTrial();
1093
+ if (!trial)
1094
+ return;
1095
+ const now = this.options.now();
1096
+ const endsAt = Date.parse(trial.endsAt);
1097
+ const endingAt = endsAt - this.options.endingDays * DAY_MS;
1098
+ const event = trial.daysLeft === 0
1099
+ ? 'trial:ended'
1100
+ : trial.active && this.options.endingDays > 0 && now >= endingAt
1101
+ ? 'trial:ending'
1102
+ : null;
1103
+ if (event && !this.options.hasPaidAccess())
1104
+ await this.send(event, trial);
1105
+ if (!this.running || trial.daysLeft === 0)
1106
+ return;
1107
+ const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
1108
+ this.timer = setTimeout(() => {
1109
+ this.timer = null;
1110
+ void this.evaluate();
1111
+ }, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
1112
+ }
1113
+ async send(event, trial) {
1114
+ const id = `${trial.startedAt}|${trial.endsAt}`;
1115
+ const field = event === 'trial:ended' ? 'ended' : 'ending';
1116
+ const stored = (await this.options.storage.get(this.options.storageKey));
1117
+ const sent = stored && typeof stored === 'object' ? stored : {};
1118
+ if (sent[field] === id || !this.running)
1119
+ return;
1120
+ await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
1121
+ this.options.emit(event, trial);
1122
+ }
1123
+ clearTimer() {
1124
+ if (this.timer !== null)
1125
+ clearTimeout(this.timer);
1126
+ this.timer = null;
1127
+ }
1128
+ }
830
1129
 
831
1130
  /**
832
1131
  * Entitlement cache + refresh.
@@ -834,13 +1133,18 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
834
1133
  * The cached envelope is a cache OF the server projection, never a second
835
1134
  * source of truth: it is verified when stored and re-verified on load (once
836
1135
  * the project's public key is known), served without a round-trip while the
837
- * TTL holds, served for up to 48 hours after signed issuance when the network is down, and expired
1136
+ * TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
838
1137
  * locally by `expiresAt`. Background refresh polls at most every 15 minutes
839
1138
  * and backs off exponentially on errors.
840
1139
  */
841
1140
  const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
842
1141
  const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
1142
+ /** Offline allowance when the signed license names none (older servers and caches). */
843
1143
  const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
1144
+ /** Ceiling for a signed `offlineSeconds`. */
1145
+ const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
1146
+ /** `setTimeout` fires at once past this delay. */
1147
+ const MAX_TIMER_MS = 2 ** 31 - 1;
844
1148
  // Allow small server/client clock skew without granting more than the signed age limit.
845
1149
  const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
846
1150
  const CACHE_VERSION = 1;
@@ -859,6 +1163,8 @@ class EntitlementManager {
859
1163
  this.options = options;
860
1164
  this.held = null;
861
1165
  this.inflight = null;
1166
+ /** Device clock against the server's at the last license check; null within 5 minutes. */
1167
+ this.clockSkew = null;
862
1168
  this.timer = null;
863
1169
  this.refreshGeneration = 0;
864
1170
  this.deadlineTimer = null;
@@ -900,8 +1206,10 @@ class EntitlementManager {
900
1206
  envelope: JSON.parse(JSON.stringify(record.envelope)),
901
1207
  fetchedAt: record.fetchedAt,
902
1208
  verified: false,
1209
+ key: null,
903
1210
  source: this.source === 'mock' ? 'mock' : 'cache',
904
1211
  };
1212
+ this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
905
1213
  this.lastFingerprint = this.fingerprint();
906
1214
  return this.snapshot();
907
1215
  }
@@ -912,8 +1220,7 @@ class EntitlementManager {
912
1220
  if (this.source === 'mock')
913
1221
  return;
914
1222
  const held = this.held;
915
- const key = await this.safePublicKey();
916
- const verdict = await verifyEntitlementSignature(held.envelope, key);
1223
+ const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
917
1224
  if (held !== this.held)
918
1225
  return;
919
1226
  if (verdict === 'invalid') {
@@ -922,19 +1229,39 @@ class EntitlementManager {
922
1229
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
923
1230
  }
924
1231
  held.verified = verdict === 'valid';
1232
+ held.key = key;
925
1233
  if (!held.verified) {
926
1234
  throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
927
1235
  }
928
1236
  this.scheduleDeadline();
929
1237
  }
1238
+ /** The key the held license was verified with; null when there is none or it is unverified. */
1239
+ get verifiedKey() {
1240
+ return this.held?.verified ? this.held.key : null;
1241
+ }
930
1242
  getCached() {
931
1243
  return this.held ? this.snapshot() : null;
932
1244
  }
1245
+ /** The server trial in the held license; null without one, or while the license is unverified. */
1246
+ getTrial() {
1247
+ const held = this.held;
1248
+ if (!held || (this.source !== 'mock' && !held.verified))
1249
+ return null;
1250
+ const now = this.now();
1251
+ const issuedAt = Date.parse(held.envelope.payload.issuedAt);
1252
+ return trialState(held.envelope.payload.trial, {
1253
+ now,
1254
+ issuedAt,
1255
+ // The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
1256
+ checked: this.source === 'mock' ||
1257
+ (now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
1258
+ });
1259
+ }
933
1260
  isFresh() {
934
1261
  return (this.held !== null &&
935
1262
  (this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
936
1263
  this.now() >= this.held.fetchedAt &&
937
- this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS));
1264
+ this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
938
1265
  }
939
1266
  async get(options = {}) {
940
1267
  if (!options.force && this.isFresh())
@@ -949,7 +1276,7 @@ class EntitlementManager {
949
1276
  logger.debug('serving cached entitlement after refresh failure', err.code);
950
1277
  return this.snapshot();
951
1278
  }
952
- return EMPTY_ENTITLEMENT;
1279
+ return this.snapshot();
953
1280
  }
954
1281
  }
955
1282
  /** Fetches the projection from the backend, verifies and stores it. */
@@ -957,7 +1284,8 @@ class EntitlementManager {
957
1284
  if (!this.inflight) {
958
1285
  this.inflight = (async () => {
959
1286
  const endUserRef = await this.options.getEndUserRef();
960
- const envelope = await this.options.api.getEntitlement(endUserRef);
1287
+ const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
1288
+ const envelope = await this.options.api.getEntitlement(endUserRef, hint);
961
1289
  return this.accept(envelope, this.source);
962
1290
  })().finally(() => {
963
1291
  this.inflight = null;
@@ -979,9 +1307,9 @@ class EntitlementManager {
979
1307
  if (envelope.payload.endUserRef !== endUserRef) {
980
1308
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
981
1309
  }
982
- const verdict = this.source === 'mock'
983
- ? 'unverified'
984
- : await verifyEntitlementSignature(envelope, await this.safePublicKey());
1310
+ const { verdict, key } = this.source === 'mock'
1311
+ ? { verdict: 'unverified', key: null }
1312
+ : await verifyWithKeys(envelope, this.options.keys);
985
1313
  if (verdict === 'invalid') {
986
1314
  await this.discard();
987
1315
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
@@ -991,15 +1319,19 @@ class EntitlementManager {
991
1319
  }
992
1320
  const fetchedAt = this.now();
993
1321
  const issuedAt = Date.parse(envelope.payload.issuedAt);
1322
+ // A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
1323
+ if (this.source !== 'mock')
1324
+ this.measureClockSkew(fetchedAt, issuedAt);
994
1325
  if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
995
1326
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
996
1327
  }
997
- this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
1328
+ this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
998
1329
  const record = { v: CACHE_VERSION, envelope, fetchedAt };
999
1330
  await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
1000
1331
  this.backoffMs = 0;
1001
1332
  this.scheduleDeadline();
1002
1333
  this.notifyIfChanged();
1334
+ this.options.onAccepted?.();
1003
1335
  return this.snapshot();
1004
1336
  }
1005
1337
  /** Drain an older installation refresh before changing identity. */
@@ -1053,7 +1385,7 @@ class EntitlementManager {
1053
1385
  this.deadlineTimer = null;
1054
1386
  this.notifyIfChanged();
1055
1387
  this.scheduleDeadline();
1056
- }, remaining);
1388
+ }, Math.min(remaining, MAX_TIMER_MS));
1057
1389
  }
1058
1390
  schedule(delayMs) {
1059
1391
  const generation = this.refreshGeneration;
@@ -1074,14 +1406,12 @@ class EntitlementManager {
1074
1406
  }
1075
1407
  }, delayMs);
1076
1408
  }
1077
- async safePublicKey() {
1078
- try {
1079
- return await this.options.getPublicKey();
1080
- }
1081
- catch (error) {
1082
- logger.debug('public key unavailable; entitlement stays unverified', error);
1083
- return null;
1084
- }
1409
+ measureClockSkew(local, server) {
1410
+ const ms = local - server;
1411
+ this.clockSkew =
1412
+ Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
1413
+ ? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
1414
+ : null;
1085
1415
  }
1086
1416
  async discard() {
1087
1417
  this.held = null;
@@ -1104,13 +1434,25 @@ class EntitlementManager {
1104
1434
  if (!this.held)
1105
1435
  return NaN;
1106
1436
  // fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
1107
- return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + MAX_OFFLINE_AGE_MS;
1437
+ return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
1438
+ }
1439
+ /** The signed allowance of the held license, or 48 hours when it names none. */
1440
+ offlineAgeMs() {
1441
+ const seconds = this.held?.envelope.payload.offlineSeconds;
1442
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
1443
+ return MAX_OFFLINE_AGE_MS;
1444
+ return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
1108
1445
  }
1109
1446
  snapshot() {
1110
1447
  if (!this.held)
1111
- return EMPTY_ENTITLEMENT;
1448
+ return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
1112
1449
  if (this.source !== 'mock' && !this.held.verified) {
1113
- return { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source };
1450
+ return {
1451
+ ...EMPTY_ENTITLEMENT,
1452
+ requiresOnlineCheck: true,
1453
+ clockSkew: this.clockSkew,
1454
+ source: this.held.source,
1455
+ };
1114
1456
  }
1115
1457
  const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1116
1458
  const hasPaidAccess = collectFeatures(items).length > 0 ||
@@ -1126,6 +1468,7 @@ class EntitlementManager {
1126
1468
  features: requiresOnlineCheck ? [] : collectFeatures(items),
1127
1469
  requiresOnlineCheck,
1128
1470
  offlineUntil,
1471
+ clockSkew: this.clockSkew,
1129
1472
  verified: this.held.verified,
1130
1473
  issuedAt: this.held.envelope.payload.issuedAt,
1131
1474
  fetchedAt: this.held.fetchedAt,
@@ -1214,6 +1557,16 @@ class MemoryStorage {
1214
1557
  this.map.delete(key);
1215
1558
  }
1216
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
+ }
1217
1570
  function createStorage() {
1218
1571
  const g = extensionGlobals();
1219
1572
  const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
@@ -1270,7 +1623,7 @@ class RecoveryManager {
1270
1623
  const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
1271
1624
  const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
1272
1625
  const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
1273
- 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);
1274
1627
  if (!Number.isFinite(Date.parse(created.expiresAt)))
1275
1628
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
1276
1629
  const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
@@ -1330,8 +1683,9 @@ class RecoveryManager {
1330
1683
  break;
1331
1684
  if (claim.state === 'complete') {
1332
1685
  const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
1686
+ const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
1333
1687
  await this.options.storage.remove(this.pendingKey);
1334
- return { state: 'complete', entitlement };
1688
+ return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
1335
1689
  }
1336
1690
  if (claim.state !== 'pending')
1337
1691
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
@@ -1360,9 +1714,10 @@ class RecoveryManager {
1360
1714
  const DEFAULT_API_URL = 'https://bff.extenshi.io';
1361
1715
  const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
1362
1716
  const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
1717
+ const DEFAULT_TRIAL_ENDING_DAYS = 2;
1363
1718
 
1364
1719
  /** Kept in sync with package.json by tests/unit/version.test.ts. */
1365
- const VERSION = '0.9.0';
1720
+ const VERSION = '0.11.0';
1366
1721
 
1367
1722
  /**
1368
1723
  * The user's language as the SDK sends it. Kept apart from the paywall
@@ -1432,7 +1787,7 @@ function resolveConfig(input) {
1432
1787
  if (!isHttpUrl(apiUrl))
1433
1788
  errors.push('apiUrl must be an http(s) URL');
1434
1789
  const entitlementPublicKey = input.entitlementPublicKey ?? null;
1435
- if (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {
1790
+ if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
1436
1791
  errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
1437
1792
  }
1438
1793
  const environment = input.environment ?? 'production';
@@ -1454,6 +1809,9 @@ function resolveConfig(input) {
1454
1809
  const theme = input.theme ?? {};
1455
1810
  if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
1456
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');
1457
1815
  if (input.mock &&
1458
1816
  input.mockData !== undefined &&
1459
1817
  (typeof input.mockData !== 'object' || input.mockData === null)) {
@@ -1474,6 +1832,8 @@ function resolveConfig(input) {
1474
1832
  mock: input.mock === true,
1475
1833
  mockData: input.mock ? (input.mockData ?? {}) : null,
1476
1834
  theme,
1835
+ trialEndingDays,
1836
+ syncTrialStart: input.syncTrialStart !== false,
1477
1837
  };
1478
1838
  }
1479
1839
 
@@ -1598,6 +1958,9 @@ const SDK_STRINGS_EN = {
1598
1958
  pickerDescription: 'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.',
1599
1959
  pickerFirstRecorded: 'First recorded {date}',
1600
1960
  pickerCancel: 'Cancel',
1961
+ trialEndedTitle: 'Your free trial has ended',
1962
+ trialEndedDescription: 'The extension’s tools are paused. Your settings are kept and will be there when you upgrade.',
1963
+ trialEndedFeedback: 'Share feedback',
1601
1964
  };
1602
1965
  // BEGIN GENERATED TRANSLATIONS
1603
1966
  const TRANSLATIONS = {
@@ -1666,6 +2029,9 @@ const TRANSLATIONS = {
1666
2029
  pickerDescription: 'Las compras independientes pueden tener perfiles de facturación distintos. Elige uno para gestionar sus suscripciones y datos de pago.',
1667
2030
  pickerFirstRecorded: 'Registrado por primera vez el {date}',
1668
2031
  pickerCancel: 'Cancelar',
2032
+ trialEndedTitle: 'Tu prueba gratuita ha terminado',
2033
+ trialEndedDescription: 'Las herramientas de la extensión están en pausa. Tu configuración se conserva y la encontrarás igual cuando mejores tu plan.',
2034
+ trialEndedFeedback: 'Enviar comentarios',
1669
2035
  },
1670
2036
  'pt-BR': {
1671
2037
  title: 'Desbloqueie os recursos premium',
@@ -1732,6 +2098,9 @@ const TRANSLATIONS = {
1732
2098
  pickerDescription: 'Compras diferentes podem ter perfis de cobrança diferentes. Escolha um perfil para gerenciar as assinaturas e os dados de pagamento vinculados a ele.',
1733
2099
  pickerFirstRecorded: 'Registrado pela primeira vez em {date}',
1734
2100
  pickerCancel: 'Cancelar',
2101
+ trialEndedTitle: 'Seu teste gratuito terminou',
2102
+ trialEndedDescription: 'As ferramentas da extensão estão pausadas. Suas configurações foram mantidas e estarão lá quando você fizer o upgrade.',
2103
+ trialEndedFeedback: 'Enviar feedback',
1735
2104
  },
1736
2105
  fr: {
1737
2106
  title: 'Débloquez les fonctionnalités premium',
@@ -1798,6 +2167,9 @@ const TRANSLATIONS = {
1798
2167
  pickerDescription: 'Des achats distincts peuvent avoir des profils de facturation distincts. Choisissez-en un pour gérer ses abonnements et ses informations de paiement.',
1799
2168
  pickerFirstRecorded: 'Enregistré pour la première fois le {date}',
1800
2169
  pickerCancel: 'Annuler',
2170
+ trialEndedTitle: 'Votre essai gratuit est terminé',
2171
+ trialEndedDescription: 'Les outils de l’extension sont en pause. Vos paramètres sont conservés et vous les retrouverez après la mise à niveau.',
2172
+ trialEndedFeedback: 'Donner votre avis',
1801
2173
  },
1802
2174
  de: {
1803
2175
  title: 'Premium-Funktionen freischalten',
@@ -1864,6 +2236,9 @@ const TRANSLATIONS = {
1864
2236
  pickerDescription: 'Verschiedene Käufe können eigene Abrechnungsprofile haben. Wähle eines aus, um seine Abonnements und Zahlungsdaten zu verwalten.',
1865
2237
  pickerFirstRecorded: 'Erstmals erfasst am {date}',
1866
2238
  pickerCancel: 'Abbrechen',
2239
+ trialEndedTitle: 'Dein kostenloser Testzeitraum ist abgelaufen',
2240
+ trialEndedDescription: 'Die Funktionen der Erweiterung sind pausiert. Deine Einstellungen bleiben erhalten und sind nach dem Upgrade wieder da.',
2241
+ trialEndedFeedback: 'Feedback geben',
1867
2242
  },
1868
2243
  it: {
1869
2244
  title: 'Sblocca le funzionalità premium',
@@ -1930,6 +2305,9 @@ const TRANSLATIONS = {
1930
2305
  pickerDescription: 'Acquisti diversi possono avere profili di fatturazione diversi. Scegline uno per gestirne gli abbonamenti e i dati di pagamento.',
1931
2306
  pickerFirstRecorded: 'Registrato per la prima volta il {date}',
1932
2307
  pickerCancel: 'Annulla',
2308
+ trialEndedTitle: 'La tua prova gratuita è terminata',
2309
+ trialEndedDescription: 'Gli strumenti dell’estensione sono in pausa. Le tue impostazioni sono conservate e le ritroverai dopo l’upgrade.',
2310
+ trialEndedFeedback: 'Invia un feedback',
1933
2311
  },
1934
2312
  ru: {
1935
2313
  title: 'Откройте доступ к премиум-функциям',
@@ -1996,6 +2374,9 @@ const TRANSLATIONS = {
1996
2374
  pickerDescription: 'У разных покупок могут быть разные платёжные профили. Выберите профиль, чтобы управлять его подписками и платёжными данными.',
1997
2375
  pickerFirstRecorded: 'Впервые зафиксирован: {date}',
1998
2376
  pickerCancel: 'Отмена',
2377
+ trialEndedTitle: 'Бесплатный пробный период закончился',
2378
+ trialEndedDescription: 'Инструменты расширения приостановлены. Ваши настройки сохранены и будут на месте после перехода на премиум.',
2379
+ trialEndedFeedback: 'Оставить отзыв',
1999
2380
  },
2000
2381
  ja: {
2001
2382
  title: 'プレミアム機能をアンロック',
@@ -2062,6 +2443,9 @@ const TRANSLATIONS = {
2062
2443
  pickerDescription: '購入ごとに別々の請求プロファイルがある場合があります。サブスクリプションと支払い情報を管理するプロファイルを1つ選択してください。',
2063
2444
  pickerFirstRecorded: '初回記録日:{date}',
2064
2445
  pickerCancel: 'キャンセル',
2446
+ trialEndedTitle: '無料トライアルが終了しました',
2447
+ trialEndedDescription: '拡張機能のツールは一時停止しています。設定は保存されており、アップグレード後もそのままご利用いただけます。',
2448
+ trialEndedFeedback: 'フィードバックを送信',
2065
2449
  },
2066
2450
  ko: {
2067
2451
  title: '프리미엄 기능 잠금 해제',
@@ -2128,6 +2512,9 @@ const TRANSLATIONS = {
2128
2512
  pickerDescription: '구매마다 결제 프로필이 다를 수 있습니다. 구독과 결제 정보를 관리할 프로필을 하나 선택해 주세요.',
2129
2513
  pickerFirstRecorded: '최초 기록일: {date}',
2130
2514
  pickerCancel: '취소',
2515
+ trialEndedTitle: '무료 체험 기간이 종료되었습니다',
2516
+ trialEndedDescription: '확장 프로그램의 도구가 일시 중지되었습니다. 설정은 그대로 저장되어 있으며 업그레이드하면 다시 사용할 수 있습니다.',
2517
+ trialEndedFeedback: '의견 보내기',
2131
2518
  },
2132
2519
  'zh-CN': {
2133
2520
  title: '解锁高级功能',
@@ -2194,6 +2581,9 @@ const TRANSLATIONS = {
2194
2581
  pickerDescription: '不同的购买可以有各自的账单资料。请选择一个,以管理其订阅和付款信息。',
2195
2582
  pickerFirstRecorded: '首次记录于 {date}',
2196
2583
  pickerCancel: '取消',
2584
+ trialEndedTitle: '免费试用已结束',
2585
+ trialEndedDescription: '扩展程序的工具已暂停。您的设置已保留,升级后即可继续使用。',
2586
+ trialEndedFeedback: '提交反馈',
2197
2587
  },
2198
2588
  ar: {
2199
2589
  title: 'احصل على الميزات المميزة',
@@ -2260,6 +2650,9 @@ const TRANSLATIONS = {
2260
2650
  pickerDescription: 'يمكن أن تكون لعمليات الشراء المنفصلة ملفات فوترة منفصلة. اختر ملفًا منها لإدارة اشتراكاته وتفاصيل الدفع الخاصة به.',
2261
2651
  pickerFirstRecorded: 'سُجِّل لأول مرة في {date}',
2262
2652
  pickerCancel: 'إلغاء',
2653
+ trialEndedTitle: 'انتهت فترتك التجريبية المجانية',
2654
+ trialEndedDescription: 'أدوات الإضافة متوقفة مؤقتًا. إعداداتك محفوظة وستجدها كما هي بعد الترقية.',
2655
+ trialEndedFeedback: 'إرسال ملاحظات',
2263
2656
  },
2264
2657
  };
2265
2658
  // END GENERATED TRANSLATIONS
@@ -2340,8 +2733,10 @@ function withdrawalWaiverText(serverVersion, locale, seller) {
2340
2733
  * extends it with `getOffer()` / `showPaywall()`.
2341
2734
  *
2342
2735
  * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
2343
- * `locale` and checkout session IDs. Explicit recovery also sends its session ID,
2344
- * challenge and claim secret (POST body). Email stays on the hosted page.
2736
+ * `locale`, checkout session IDs and, with a server trial, the trial start date
2737
+ * the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
2738
+ * challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
2739
+ * storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
2345
2740
  */
2346
2741
  /** Server-side offer cache is 5 min; mirror it in memory. */
2347
2742
  const OFFER_TTL_MS = 5 * 60 * 1000;
@@ -2352,12 +2747,30 @@ class ExtenshiPayLite {
2352
2747
  this.endUserRefPromise = null;
2353
2748
  this.offer = null;
2354
2749
  this.offerInflight = null;
2750
+ /** The signing key the server returned in this session; never one read from storage. */
2751
+ this.serverKey = null;
2752
+ /** Trust order for license signatures; see payment/signature.ts. */
2753
+ this.keys = {
2754
+ known: async () => {
2755
+ const pinned = this.config.entitlementPublicKey;
2756
+ const offline = pinned ?? (await this.readSavedServerKey());
2757
+ return [...new Set([this.serverKey, offline].filter((key) => !!key))];
2758
+ },
2759
+ fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
2760
+ };
2355
2761
  this.readyPromise = null;
2356
2762
  this.destroyed = false;
2357
2763
  this.config = resolveConfig(config);
2358
2764
  logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
2359
2765
  this.now = deps.now ?? (() => Date.now());
2360
2766
  this.storage = deps.storage ?? createStorage();
2767
+ this.openUrl = deps.openUrl;
2768
+ this.syncStorage =
2769
+ !this.config.syncTrialStart || this.config.mock
2770
+ ? null
2771
+ : deps.syncStorage === undefined
2772
+ ? createSyncStorage()
2773
+ : deps.syncStorage;
2361
2774
  const transport = deps.transport ??
2362
2775
  (this.config.mock
2363
2776
  ? new MockTransport(this.config.mockData ?? {})
@@ -2370,11 +2783,26 @@ class ExtenshiPayLite {
2370
2783
  cacheTtlMs: this.config.cacheTtlMs,
2371
2784
  source: this.config.mock ? 'mock' : 'network',
2372
2785
  getEndUserRef: () => this.getEndUserRef(),
2373
- getPublicKey: () => this.getPublicKey(),
2786
+ keys: this.keys,
2374
2787
  onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
2788
+ onAccepted: () => {
2789
+ void this.trial.evaluate();
2790
+ void this.rememberTrialStart();
2791
+ },
2792
+ getTrialStartHint: () => this.readTrialStartHint(),
2375
2793
  onError: (error) => this.reportError(error),
2376
2794
  now: this.now,
2377
2795
  });
2796
+ this.trial = new TrialNotifier({
2797
+ storage: this.storage,
2798
+ storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
2799
+ endingDays: this.config.trialEndingDays,
2800
+ getTrial: () => this.entitlements.getTrial(),
2801
+ // A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
2802
+ hasPaidAccess: () => (this.entitlements.getCached()?.items ?? []).some(isLive),
2803
+ emit: (event, trial) => this.emitter.emit(event, trial),
2804
+ now: this.now,
2805
+ });
2378
2806
  this.checkout = new CheckoutManager({
2379
2807
  api: this.api,
2380
2808
  storage: this.storage,
@@ -2388,6 +2816,13 @@ class ExtenshiPayLite {
2388
2816
  (this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
2389
2817
  now: this.now,
2390
2818
  });
2819
+ this.backup = new CloudBackup({
2820
+ storage: this.storage,
2821
+ publishableKey: this.config.publishableKey,
2822
+ apiUrl: this.config.apiUrl,
2823
+ fetch: deps.fetch,
2824
+ mock: this.config.mock,
2825
+ });
2391
2826
  this.recovery = new RecoveryManager({
2392
2827
  api: this.api,
2393
2828
  locale: this.config.locale,
@@ -2401,7 +2836,7 @@ class ExtenshiPayLite {
2401
2836
  envelope.payload.publishableKey !== this.config.publishableKey ||
2402
2837
  !Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
2403
2838
  Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
2404
- (await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid')
2839
+ (await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
2405
2840
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
2406
2841
  this.entitlements.stopAutoRefresh();
2407
2842
  try {
@@ -2419,6 +2854,7 @@ class ExtenshiPayLite {
2419
2854
  this.entitlements.startAutoRefresh();
2420
2855
  }
2421
2856
  },
2857
+ onStorageGrant: (grant) => this.backup.accept(grant),
2422
2858
  });
2423
2859
  if (config.onError)
2424
2860
  this.emitter.on('error', config.onError);
@@ -2464,8 +2900,11 @@ class ExtenshiPayLite {
2464
2900
  catch (error) {
2465
2901
  this.reportError(error);
2466
2902
  }
2467
- if (!this.destroyed)
2903
+ void this.confirmSavedServerKey();
2904
+ if (!this.destroyed) {
2468
2905
  this.entitlements.startAutoRefresh();
2906
+ this.trial.start();
2907
+ }
2469
2908
  }
2470
2909
  /** The anonymous, random id this install is known by. */
2471
2910
  getEndUserRef() {
@@ -2486,6 +2925,16 @@ class ExtenshiPayLite {
2486
2925
  await this.initialize();
2487
2926
  return this.entitlements.get(options);
2488
2927
  }
2928
+ /**
2929
+ * The free trial the application set on the server, from the verified license, or null when
2930
+ * there is none (or the license could not be verified yet). Answers offline from the cached
2931
+ * license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
2932
+ * `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
2933
+ */
2934
+ async getTrial(options = {}) {
2935
+ await this.getEntitlement(options);
2936
+ return this.entitlements.getTrial();
2937
+ }
2489
2938
  /** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
2490
2939
  async isPaid(sku) {
2491
2940
  return isEntitled(await this.getEntitlement(), sku);
@@ -2569,6 +3018,41 @@ class ExtenshiPayLite {
2569
3018
  throw this.reportError(error);
2570
3019
  }
2571
3020
  }
3021
+ /**
3022
+ * Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
3023
+ * hosted restore page shows the storage disclosure and the buyer confirms with
3024
+ * the code from the purchase email. `cloudBackup` in the result says whether it is
3025
+ * on. Buyers only; consent is recorded by the server.
3026
+ */
3027
+ enableCloudBackup(options = {}) {
3028
+ return this.restorePurchase({ ...options, purpose: 'storage' });
3029
+ }
3030
+ /**
3031
+ * The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
3032
+ * while cloud backup is off on this installation. Extension pages and background
3033
+ * only: it rejects in a content script, and must never be sent to one.
3034
+ */
3035
+ async cloudBackupToken() {
3036
+ return this.backup.token();
3037
+ }
3038
+ /** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
3039
+ async disableCloudBackup() {
3040
+ try {
3041
+ await this.backup.disable();
3042
+ }
3043
+ catch (error) {
3044
+ throw this.reportError(error);
3045
+ }
3046
+ }
3047
+ /** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
3048
+ async deleteCloudBackup() {
3049
+ try {
3050
+ await this.backup.delete();
3051
+ }
3052
+ catch (error) {
3053
+ throw this.reportError(error);
3054
+ }
3055
+ }
2572
3056
  /** Read-only license view. Entitlements retain cache/signature/offline semantics. */
2573
3057
  async getLicenseSummary(options = {}) {
2574
3058
  await this.initialize();
@@ -2638,6 +3122,7 @@ class ExtenshiPayLite {
2638
3122
  destroy() {
2639
3123
  this.destroyed = true;
2640
3124
  this.recovery.stop();
3125
+ this.trial.stop();
2641
3126
  this.entitlements.stopAutoRefresh();
2642
3127
  this.emitter.removeAll();
2643
3128
  }
@@ -2649,8 +3134,9 @@ class ExtenshiPayLite {
2649
3134
  if (!this.offerInflight) {
2650
3135
  this.offerInflight = this.api
2651
3136
  .getOffer(this.config.locale)
2652
- .then((value) => {
3137
+ .then(async (value) => {
2653
3138
  this.offer = { value, fetchedAt: this.now() };
3139
+ await this.rememberServerKey(value.entitlementPublicKey);
2654
3140
  return value;
2655
3141
  })
2656
3142
  .finally(() => {
@@ -2659,8 +3145,88 @@ class ExtenshiPayLite {
2659
3145
  }
2660
3146
  return this.offerInflight;
2661
3147
  }
2662
- async getPublicKey() {
2663
- return this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey;
3148
+ get serverKeyStorageKey() {
3149
+ return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
3150
+ }
3151
+ async readSavedServerKey() {
3152
+ try {
3153
+ const value = await this.storage.get(this.serverKeyStorageKey);
3154
+ return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
3155
+ }
3156
+ catch {
3157
+ return null;
3158
+ }
3159
+ }
3160
+ /**
3161
+ * Keeps the server's key next to the license cache so a restart with no network can verify it.
3162
+ * Not with a bundled key: that one already covers the restart, and storage stays untrusted.
3163
+ */
3164
+ async rememberServerKey(key) {
3165
+ if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
3166
+ return;
3167
+ this.serverKey = key;
3168
+ if (this.config.entitlementPublicKey || this.config.mock)
3169
+ return;
3170
+ try {
3171
+ if ((await this.readSavedServerKey()) !== key)
3172
+ await this.storage.set(this.serverKeyStorageKey, key);
3173
+ }
3174
+ catch (error) {
3175
+ logger.debug('signing key not saved', error);
3176
+ }
3177
+ }
3178
+ /**
3179
+ * A license verified with the saved key alone is checked against the server once per start:
3180
+ * when the server's key differs (rotation, or an edited storage) the license is fetched again,
3181
+ * and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
3182
+ */
3183
+ async confirmSavedServerKey() {
3184
+ const used = this.entitlements.verifiedKey;
3185
+ if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
3186
+ return;
3187
+ try {
3188
+ if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
3189
+ return;
3190
+ }
3191
+ catch {
3192
+ return;
3193
+ }
3194
+ try {
3195
+ await this.entitlements.refresh();
3196
+ }
3197
+ catch {
3198
+ await this.entitlements.reverify().catch((error) => this.reportError(error));
3199
+ }
3200
+ }
3201
+ get trialStartKey() {
3202
+ return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
3203
+ }
3204
+ /** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
3205
+ async readTrialStartHint() {
3206
+ if (!this.syncStorage)
3207
+ return null;
3208
+ try {
3209
+ const value = await this.syncStorage.get(this.trialStartKey);
3210
+ return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
3211
+ }
3212
+ catch {
3213
+ return null;
3214
+ }
3215
+ }
3216
+ /** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
3217
+ async rememberTrialStart() {
3218
+ const trial = this.entitlements.getTrial();
3219
+ if (!this.syncStorage || !trial)
3220
+ return;
3221
+ try {
3222
+ const synced = await this.readTrialStartHint();
3223
+ if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
3224
+ return;
3225
+ await this.syncStorage.set(this.trialStartKey, trial.startedAt);
3226
+ }
3227
+ catch (error) {
3228
+ logger.debug('trial start not synced', error);
3229
+ }
2664
3230
  }
2665
3231
  reportError(error) {
2666
3232
  const err = ExtenshiPayError.from(error);
@@ -3405,18 +3971,12 @@ class PaywallRenderer {
3405
3971
  }
3406
3972
  if (waiver && waiverBox)
3407
3973
  this.mountWaiver(root, doc, waiver.text, waiverBox);
3408
- if (view.recoveryEnabled && this.callbacks.onRestore) {
3409
- const footer = root.querySelector('[class*="-footer"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content');
3410
- if (footer) {
3411
- const button = doc.createElement('button');
3412
- button.type = 'button';
3413
- button.textContent = strings.restorePurchase;
3414
- button.style.cssText =
3415
- 'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer';
3416
- button.addEventListener('click', () => this.callbacks.onRestore?.());
3417
- footer.appendChild(button);
3418
- }
3419
- }
3974
+ const onRestore = this.callbacks.onRestore;
3975
+ if (view.recoveryEnabled && onRestore)
3976
+ this.footerLink(root, doc, strings.restorePurchase, onRestore);
3977
+ const onFeedback = this.callbacks.onFeedback;
3978
+ if (view.feedback && onFeedback)
3979
+ this.footerLink(root, doc, view.feedback.label, onFeedback);
3420
3980
  const mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body;
3421
3981
  mount.appendChild(host);
3422
3982
  this.host = host;
@@ -3433,6 +3993,19 @@ class PaywallRenderer {
3433
3993
  this.host.remove();
3434
3994
  this.host = null;
3435
3995
  }
3996
+ /** A text button at the end of the footer (no `href`: the SDK opens URLs itself). */
3997
+ footerLink(root, doc, label, onClick) {
3998
+ const footer = root.querySelector('[class*="-footer"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content');
3999
+ if (!footer)
4000
+ return;
4001
+ const button = doc.createElement('button');
4002
+ button.type = 'button';
4003
+ button.textContent = label;
4004
+ button.style.cssText =
4005
+ 'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer';
4006
+ button.addEventListener('click', () => onClick());
4007
+ footer.appendChild(button);
4008
+ }
3436
4009
  prune(root) {
3437
4010
  for (const element of root.querySelectorAll(PRUNE_SELECTOR))
3438
4011
  element.remove();
@@ -3639,6 +4212,28 @@ class ExtenshiPay extends ExtenshiPayLite {
3639
4212
  * `getOffer()`; if that fails the paywall still renders with checkout disabled.
3640
4213
  */
3641
4214
  async showPaywall(options = {}) {
4215
+ return this.present(options, null);
4216
+ }
4217
+ /**
4218
+ * The paywall for a user whose free trial ended, e.g. on `trial:ended`. In the user's
4219
+ * language it says the trial has ended, the tools are paused and the settings are kept,
4220
+ * then shows the plans, "Restore purchase" when recovery is on, and with `feedbackFormUrl`
4221
+ * a feedback button. Resolves like `showPaywall()`. The default text promises the settings
4222
+ * are kept: pass `description` if your extension does not keep them.
4223
+ */
4224
+ async showTrialEnded(options = {}) {
4225
+ const t = sdkStrings(this.config.locale);
4226
+ const feedbackUrl = trialFeedbackUrl(options.feedbackFormUrl);
4227
+ if (options.feedbackFormUrl !== undefined && !feedbackUrl)
4228
+ this.reportError(new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'feedbackFormUrl must be an https URL without credentials; the feedback button is left out'));
4229
+ const { feedbackFormUrl: _url, feedbackLabel, ...paywall } = options;
4230
+ return this.present({
4231
+ ...paywall,
4232
+ title: options.title ?? t.trialEndedTitle,
4233
+ description: options.description ?? t.trialEndedDescription,
4234
+ }, feedbackUrl ? { label: feedbackLabel ?? t.trialEndedFeedback, url: feedbackUrl } : null);
4235
+ }
4236
+ async present(options, feedback) {
3642
4237
  await this.initialize();
3643
4238
  let offer = null;
3644
4239
  try {
@@ -3665,6 +4260,7 @@ class ExtenshiPay extends ExtenshiPayLite {
3665
4260
  recoveryEnabled: offer?.recoveryEnabled === true,
3666
4261
  seller: offer?.seller ?? null,
3667
4262
  withdrawalWaiver: offer?.withdrawalWaiver ?? null,
4263
+ feedback: feedback ? { label: feedback.label } : null,
3668
4264
  locale: this.config.locale,
3669
4265
  theme: { ...this.config.theme, ...options.theme },
3670
4266
  strings: options.strings ?? {},
@@ -3672,7 +4268,7 @@ class ExtenshiPay extends ExtenshiPayLite {
3672
4268
  };
3673
4269
  this.hidePaywall();
3674
4270
  return new Promise((resolve) => {
3675
- this.paywallSession = { options, resolve };
4271
+ this.paywallSession = { options, resolve, feedbackUrl: feedback?.url ?? null };
3676
4272
  try {
3677
4273
  this.renderer().show(view);
3678
4274
  }
@@ -3705,6 +4301,7 @@ class ExtenshiPay extends ExtenshiPayLite {
3705
4301
  onUpgrade: (sku, consent) => void this.handleUpgrade(sku, consent),
3706
4302
  onClose: () => this.settlePaywall(false),
3707
4303
  onRestore: () => void this.handleRestore(),
4304
+ onFeedback: () => void this.handleFeedback(),
3708
4305
  });
3709
4306
  }
3710
4307
  return this.paywall;
@@ -3721,6 +4318,17 @@ class ExtenshiPay extends ExtenshiPayLite {
3721
4318
  /* Reported through the error event; leave the paywall open for retry. */
3722
4319
  }
3723
4320
  }
4321
+ async handleFeedback() {
4322
+ const url = this.paywallSession?.feedbackUrl;
4323
+ if (!url)
4324
+ return;
4325
+ try {
4326
+ await (this.openUrl ?? openInNewTab)(url);
4327
+ }
4328
+ catch (error) {
4329
+ this.reportError(error);
4330
+ }
4331
+ }
3724
4332
  async handleUpgrade(sku, consent) {
3725
4333
  if (consent)
3726
4334
  this.paywallSession?.options.onUpgrade?.(sku, consent);
@@ -3753,9 +4361,11 @@ class ExtenshiPay extends ExtenshiPayLite {
3753
4361
  exports.CHECKOUT_POLL_INTERVAL_MS = CHECKOUT_POLL_INTERVAL_MS;
3754
4362
  exports.CHECKOUT_TIMEOUT_MS = CHECKOUT_TIMEOUT_MS;
3755
4363
  exports.CheckoutManager = CheckoutManager;
4364
+ exports.CloudBackup = CloudBackup;
3756
4365
  exports.DEFAULT_API_URL = DEFAULT_API_URL;
3757
4366
  exports.DEFAULT_CACHE_TTL_MS = DEFAULT_CACHE_TTL_MS;
3758
4367
  exports.DEFAULT_STRINGS = DEFAULT_STRINGS;
4368
+ exports.DEFAULT_TRIAL_ENDING_DAYS = DEFAULT_TRIAL_ENDING_DAYS;
3759
4369
  exports.EMPTY_ENTITLEMENT = EMPTY_ENTITLEMENT;
3760
4370
  exports.END_USER_REF_STORAGE_KEY = END_USER_REF_STORAGE_KEY;
3761
4371
  exports.ERROR_CODES = ERROR_CODES;
@@ -3788,11 +4398,13 @@ exports.PAY_OFFER_INTERVALS = PAY_OFFER_INTERVALS;
3788
4398
  exports.PAY_OFFER_KINDS = PAY_OFFER_KINDS;
3789
4399
  exports.PAY_PUBLISHABLE_KEY_HEX_LENGTH = PAY_PUBLISHABLE_KEY_HEX_LENGTH;
3790
4400
  exports.PAY_PUBLISHABLE_KEY_PREFIX = PAY_PUBLISHABLE_KEY_PREFIX;
4401
+ exports.PAY_RESTORE_PURPOSES = PAY_RESTORE_PURPOSES;
3791
4402
  exports.PAY_SKU_RE = PAY_SKU_RE;
3792
4403
  exports.PAY_WITHDRAWAL_WAIVER_VERSION = PAY_WITHDRAWAL_WAIVER_VERSION;
3793
4404
  exports.PayApi = PayApi;
3794
4405
  exports.PaywallRenderer = PaywallRenderer;
3795
4406
  exports.RecoveryManager = RecoveryManager;
4407
+ exports.STORAGE_TOKEN_RE = STORAGE_TOKEN_RE;
3796
4408
  exports.TRPC_PATH = TRPC_PATH;
3797
4409
  exports.VERSION = VERSION;
3798
4410
  exports.WITHDRAWAL_WAIVER_CLASS = WITHDRAWAL_WAIVER_CLASS;
@@ -3805,6 +4417,7 @@ exports.checkFeatures = checkFeatures;
3805
4417
  exports.collectFeatures = collectFeatures;
3806
4418
  exports.createRecoveryStorage = createRecoveryStorage;
3807
4419
  exports.createStorage = createStorage;
4420
+ exports.createSyncStorage = createSyncStorage;
3808
4421
  exports.default = ExtenshiPay;
3809
4422
  exports.escapeHtml = escapeHtml;
3810
4423
  exports.formatPrice = formatPrice;