@extenshi/pay 0.8.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.
- package/README.md +134 -19
- package/dist/api/mock.d.ts +4 -0
- package/dist/api/mock.d.ts.map +1 -1
- package/dist/api/pay-api.d.ts +9 -4
- package/dist/api/pay-api.d.ts.map +1 -1
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/extenshi-pay.d.ts +60 -5
- package/dist/core/extenshi-pay.d.ts.map +1 -1
- package/dist/core/index.d.ts +3 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/storage.d.ts +6 -0
- package/dist/core/storage.d.ts.map +1 -1
- package/dist/core.d.mts +280 -27
- package/dist/core.d.ts +280 -27
- package/dist/core.js +566 -44
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +562 -45
- package/dist/core.mjs.map +1 -1
- package/dist/extenshi-pay-lite.js +555 -44
- package/dist/extenshi-pay-lite.js.map +1 -1
- package/dist/extenshi-pay-lite.min.js +3 -3
- package/dist/extenshi-pay-lite.min.js.map +1 -1
- package/dist/extenshi-pay-lite.mjs +555 -44
- package/dist/extenshi-pay-lite.mjs.map +1 -1
- package/dist/extenshi-pay.cjs.js +823 -69
- package/dist/extenshi-pay.cjs.js.map +1 -1
- package/dist/extenshi-pay.d.ts +11 -1
- package/dist/extenshi-pay.d.ts.map +1 -1
- package/dist/extenshi-pay.js +823 -69
- package/dist/extenshi-pay.js.map +1 -1
- package/dist/extenshi-pay.min.js +3 -3
- package/dist/extenshi-pay.min.js.map +1 -1
- package/dist/extenshi-pay.min.mjs +3 -3
- package/dist/extenshi-pay.min.mjs.map +1 -1
- package/dist/extenshi-pay.mjs +819 -70
- package/dist/extenshi-pay.mjs.map +1 -1
- package/dist/index.d.mts +305 -27
- package/dist/index.d.ts +305 -27
- package/dist/lite.d.mts +224 -14
- package/dist/lite.d.ts +224 -14
- package/dist/lite.d.ts.map +1 -1
- package/dist/payment/cloud-backup.d.ts +35 -0
- package/dist/payment/cloud-backup.d.ts.map +1 -0
- package/dist/payment/entitlement.d.ts +21 -5
- package/dist/payment/entitlement.d.ts.map +1 -1
- package/dist/payment/recovery.d.ts +4 -2
- package/dist/payment/recovery.d.ts.map +1 -1
- package/dist/payment/signature.d.ts +29 -3
- package/dist/payment/signature.d.ts.map +1 -1
- package/dist/payment/trial.d.ts +55 -0
- package/dist/payment/trial.d.ts.map +1 -0
- package/dist/paywall/i18n.d.ts +3 -0
- package/dist/paywall/i18n.d.ts.map +1 -1
- package/dist/paywall/icon.d.ts +18 -0
- package/dist/paywall/icon.d.ts.map +1 -0
- package/dist/paywall/renderer.d.ts +15 -0
- package/dist/paywall/renderer.d.ts.map +1 -1
- package/dist/paywall.d.mts +27 -1
- package/dist/paywall.d.ts +27 -1
- package/dist/paywall.js +131 -25
- package/dist/paywall.js.map +1 -1
- package/dist/paywall.mjs +131 -25
- package/dist/paywall.mjs.map +1 -1
- package/dist/types/config.d.ts +27 -1
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/contract.d.ts +35 -0
- package/dist/types/contract.d.ts.map +1 -1
- package/dist/types/entitlement.d.ts +37 -1
- package/dist/types/entitlement.d.ts.map +1 -1
- package/dist/types/events.d.ts +5 -1
- package/dist/types/events.d.ts.map +1 -1
- package/dist/types/paywall.d.ts +22 -1
- package/dist/types/paywall.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/package.json +3 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* ExtenshiPay SDK v0.
|
|
2
|
+
* ExtenshiPay SDK v0.11.0
|
|
3
3
|
* (c) 2026 Extenshi.io
|
|
4
4
|
* Released under the MIT License.
|
|
5
|
-
* commit
|
|
5
|
+
* commit ed0f776ae9ab7ce6b2c614dbdfe696e9007b0d05 · built by `rollup -c`
|
|
6
6
|
*/
|
|
7
7
|
(function (global, factory) {
|
|
8
8
|
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
|
@@ -73,6 +73,8 @@
|
|
|
73
73
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
74
74
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
|
|
75
75
|
}
|
|
76
|
+
/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
|
|
77
|
+
const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
|
|
76
78
|
|
|
77
79
|
const ERROR_CODES = {
|
|
78
80
|
INVALID_CONFIG: 'INVALID_CONFIG',
|
|
@@ -144,7 +146,7 @@
|
|
|
144
146
|
* developed with no backend: offers and entitlements come from `mockData`, a
|
|
145
147
|
* mock checkout completes after `claimAfterPolls` polls and grants the SKU.
|
|
146
148
|
*/
|
|
147
|
-
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
149
|
+
const DAY_MS$1 = 24 * 60 * 60 * 1000;
|
|
148
150
|
/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
|
|
149
151
|
function mockConsent(value) {
|
|
150
152
|
const consent = value;
|
|
@@ -162,6 +164,10 @@
|
|
|
162
164
|
this.claimAfterPolls = data.claimAfterPolls ?? 1;
|
|
163
165
|
this.withdrawalWaiver =
|
|
164
166
|
data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
|
|
167
|
+
this.seller = data.seller;
|
|
168
|
+
this.trial = null;
|
|
169
|
+
if (data.trial)
|
|
170
|
+
this.setTrial(data.trial.days, data.trial.startedAt);
|
|
165
171
|
}
|
|
166
172
|
async call(procedure, _kind, input) {
|
|
167
173
|
switch (procedure) {
|
|
@@ -183,6 +189,14 @@
|
|
|
183
189
|
setEntitlements(items) {
|
|
184
190
|
this.entitlements = [...items];
|
|
185
191
|
}
|
|
192
|
+
/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
|
|
193
|
+
setTrial(days, startedAt = new Date().toISOString()) {
|
|
194
|
+
const start = Date.parse(startedAt);
|
|
195
|
+
this.trial =
|
|
196
|
+
days === null || !Number.isFinite(start)
|
|
197
|
+
? null
|
|
198
|
+
: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
|
|
199
|
+
}
|
|
186
200
|
cancelSession(sessionId) {
|
|
187
201
|
const session = this.sessions.get(sessionId);
|
|
188
202
|
if (session)
|
|
@@ -202,6 +216,7 @@
|
|
|
202
216
|
offers: [...this.offers],
|
|
203
217
|
entitlementPublicKey: null,
|
|
204
218
|
withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
|
|
219
|
+
...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
|
|
205
220
|
};
|
|
206
221
|
}
|
|
207
222
|
createCheckout(sku, withdrawalWaiver) {
|
|
@@ -239,7 +254,7 @@
|
|
|
239
254
|
grant(sku) {
|
|
240
255
|
const offer = this.offers.find((o) => o.sku === sku);
|
|
241
256
|
const expiresAt = offer?.kind === 'subscription'
|
|
242
|
-
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
|
|
257
|
+
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
|
|
243
258
|
: null;
|
|
244
259
|
this.entitlements = [
|
|
245
260
|
...this.entitlements.filter((item) => item.sku !== sku),
|
|
@@ -261,6 +276,7 @@
|
|
|
261
276
|
endUserRef,
|
|
262
277
|
entitlements: [...this.entitlements],
|
|
263
278
|
issuedAt: new Date().toISOString(),
|
|
279
|
+
...(this.trial ? { trial: { ...this.trial } } : {}),
|
|
264
280
|
},
|
|
265
281
|
signature: null,
|
|
266
282
|
alg: null,
|
|
@@ -274,12 +290,17 @@
|
|
|
274
290
|
this.transport = transport;
|
|
275
291
|
this.publishableKey = publishableKey;
|
|
276
292
|
}
|
|
277
|
-
/**
|
|
278
|
-
|
|
293
|
+
/**
|
|
294
|
+
* `locale` opens the hosted recovery page (and its email) in the user's language.
|
|
295
|
+
* `purpose` is sent only for `storage`: a plain restore keeps the request older
|
|
296
|
+
* BFFs know, and their non-strict zod input strips the key anyway.
|
|
297
|
+
*/
|
|
298
|
+
createRestoreSession(claimChallenge, locale, purpose) {
|
|
279
299
|
return this.transport.call('pay.createRestoreSession', 'mutation', {
|
|
280
300
|
publishableKey: this.publishableKey,
|
|
281
301
|
claimChallenge,
|
|
282
302
|
...(locale ? { locale } : {}),
|
|
303
|
+
...(purpose === 'storage' ? { purpose } : {}),
|
|
283
304
|
});
|
|
284
305
|
}
|
|
285
306
|
claimRestoreSession(sessionId, claimSecret) {
|
|
@@ -318,10 +339,12 @@
|
|
|
318
339
|
endUserRef,
|
|
319
340
|
});
|
|
320
341
|
}
|
|
321
|
-
|
|
342
|
+
/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
|
|
343
|
+
getEntitlement(endUserRef, trialStartedHint) {
|
|
322
344
|
return this.transport.call('pay.getEntitlement', 'query', {
|
|
323
345
|
publishableKey: this.publishableKey,
|
|
324
346
|
endUserRef,
|
|
347
|
+
...(trialStartedHint ? { trialStartedHint } : {}),
|
|
325
348
|
});
|
|
326
349
|
}
|
|
327
350
|
getPortalUrl(endUserRef, customerId, locale) {
|
|
@@ -719,6 +742,118 @@
|
|
|
719
742
|
openInNewTab: openInNewTab
|
|
720
743
|
});
|
|
721
744
|
|
|
745
|
+
/**
|
|
746
|
+
* Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
|
|
747
|
+
* token: only a verified restore claim issues it; this module keeps it in the
|
|
748
|
+
* SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
|
|
749
|
+
* through `cloudBackupToken()`. The token is never logged and never answered to
|
|
750
|
+
* a content script: route those calls to the background.
|
|
751
|
+
*/
|
|
752
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
753
|
+
/** True in a content script, where the token must not be handed out. */
|
|
754
|
+
function inContentScript() {
|
|
755
|
+
const g = globalThis;
|
|
756
|
+
return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
|
|
757
|
+
}
|
|
758
|
+
class CloudBackup {
|
|
759
|
+
constructor(options) {
|
|
760
|
+
this.options = options;
|
|
761
|
+
this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
762
|
+
}
|
|
763
|
+
get storageKey() {
|
|
764
|
+
return `extenshi-pay:${this.options.publishableKey}:storageToken`;
|
|
765
|
+
}
|
|
766
|
+
/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
|
|
767
|
+
async accept(grant) {
|
|
768
|
+
if (!grant || typeof grant !== 'object')
|
|
769
|
+
return undefined;
|
|
770
|
+
try {
|
|
771
|
+
if (grant.state === 'granted') {
|
|
772
|
+
if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
|
|
773
|
+
return undefined;
|
|
774
|
+
await this.options.storage.set(this.storageKey, grant.token);
|
|
775
|
+
return 'on';
|
|
776
|
+
}
|
|
777
|
+
if (grant.state === 'unavailable') {
|
|
778
|
+
await this.options.storage.remove(this.storageKey);
|
|
779
|
+
return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
catch {
|
|
783
|
+
logger.warn('cloud backup state could not be saved');
|
|
784
|
+
}
|
|
785
|
+
return undefined;
|
|
786
|
+
}
|
|
787
|
+
async token() {
|
|
788
|
+
this.assertTrustedContext();
|
|
789
|
+
const value = await this.options.storage.get(this.storageKey);
|
|
790
|
+
return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
|
|
791
|
+
}
|
|
792
|
+
/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
|
|
793
|
+
async disable() {
|
|
794
|
+
const token = await this.token();
|
|
795
|
+
if (!token)
|
|
796
|
+
return;
|
|
797
|
+
if (!this.options.mock) {
|
|
798
|
+
const status = await this.request('/v1/storage/grant', token);
|
|
799
|
+
if (status !== 401)
|
|
800
|
+
this.throwUnlessOk(status);
|
|
801
|
+
}
|
|
802
|
+
await this.options.storage.remove(this.storageKey);
|
|
803
|
+
}
|
|
804
|
+
/** Deletes the buyer's cloud copy and turns the backup off on every device. */
|
|
805
|
+
async delete() {
|
|
806
|
+
const token = await this.token();
|
|
807
|
+
if (!token)
|
|
808
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
|
|
809
|
+
if (!this.options.mock) {
|
|
810
|
+
const status = await this.request('/v1/storage/data', token);
|
|
811
|
+
if (status === 401) {
|
|
812
|
+
// The server no longer accepts this token, so it is useless here; the copy was not deleted.
|
|
813
|
+
await this.options.storage.remove(this.storageKey);
|
|
814
|
+
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 });
|
|
815
|
+
}
|
|
816
|
+
this.throwUnlessOk(status);
|
|
817
|
+
}
|
|
818
|
+
await this.options.storage.remove(this.storageKey);
|
|
819
|
+
}
|
|
820
|
+
assertTrustedContext() {
|
|
821
|
+
if (inContentScript())
|
|
822
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
|
|
823
|
+
}
|
|
824
|
+
throwUnlessOk(status) {
|
|
825
|
+
if (status >= 200 && status < 300)
|
|
826
|
+
return;
|
|
827
|
+
if (status === 429)
|
|
828
|
+
throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
|
|
829
|
+
if (status >= 500)
|
|
830
|
+
throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
|
|
831
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
|
|
832
|
+
}
|
|
833
|
+
async request(path, token) {
|
|
834
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
835
|
+
const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
|
|
836
|
+
try {
|
|
837
|
+
const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
|
|
838
|
+
method: 'DELETE',
|
|
839
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
840
|
+
credentials: 'omit',
|
|
841
|
+
signal: controller?.signal,
|
|
842
|
+
});
|
|
843
|
+
return response.status;
|
|
844
|
+
}
|
|
845
|
+
catch (error) {
|
|
846
|
+
if (controller?.signal.aborted)
|
|
847
|
+
throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
|
|
848
|
+
throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
|
|
849
|
+
}
|
|
850
|
+
finally {
|
|
851
|
+
if (timer !== null)
|
|
852
|
+
clearTimeout(timer);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
722
857
|
/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
|
|
723
858
|
const LIVE_STATUSES = new Set(['active', 'grace']);
|
|
724
859
|
function isLive(item) {
|
|
@@ -773,9 +908,17 @@
|
|
|
773
908
|
/**
|
|
774
909
|
* Ed25519 verification of the entitlement projection.
|
|
775
910
|
*
|
|
776
|
-
* Tamper resistance, not DRM.
|
|
777
|
-
*
|
|
778
|
-
*
|
|
911
|
+
* Tamper resistance, not DRM. Callers must deny access for both invalid and
|
|
912
|
+
* unverified envelopes outside explicit mocks.
|
|
913
|
+
*
|
|
914
|
+
* Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
|
|
915
|
+
* 1. the key the server returned over HTTPS in this session;
|
|
916
|
+
* 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
|
|
917
|
+
* verification without a round-trip: a key read from extension storage is then never used;
|
|
918
|
+
* 3. without a bundled key, the server key saved in `storage.local` next to the
|
|
919
|
+
* license cache, so a restart with no network can still verify the cache.
|
|
920
|
+
* When none of them verifies an envelope the server is asked for its current key once
|
|
921
|
+
* (a rotated key), and that answer decides.
|
|
779
922
|
*/
|
|
780
923
|
function base64ToBytes(base64) {
|
|
781
924
|
const binary = atob(base64);
|
|
@@ -810,6 +953,140 @@
|
|
|
810
953
|
return 'invalid';
|
|
811
954
|
}
|
|
812
955
|
}
|
|
956
|
+
const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
957
|
+
/**
|
|
958
|
+
* `invalid` only when the server's current key was checked too (or the envelope carries no
|
|
959
|
+
* signature at all). A mismatch against known keys while the server is unreachable is
|
|
960
|
+
* `unverified`: it may be a rotated key, and no paid access is granted either way.
|
|
961
|
+
*/
|
|
962
|
+
async function verifyWithKeys(envelope, source) {
|
|
963
|
+
if (!envelope.signature || envelope.alg !== 'ed25519')
|
|
964
|
+
return { verdict: 'invalid', key: null };
|
|
965
|
+
let known = [];
|
|
966
|
+
try {
|
|
967
|
+
known = await source.known();
|
|
968
|
+
}
|
|
969
|
+
catch {
|
|
970
|
+
known = [];
|
|
971
|
+
}
|
|
972
|
+
let mismatch = false;
|
|
973
|
+
for (const key of known) {
|
|
974
|
+
const verdict = await verifyEntitlementSignature(envelope, key);
|
|
975
|
+
if (verdict === 'valid')
|
|
976
|
+
return { verdict, key };
|
|
977
|
+
if (verdict === 'invalid')
|
|
978
|
+
mismatch = true;
|
|
979
|
+
}
|
|
980
|
+
let current;
|
|
981
|
+
try {
|
|
982
|
+
current = await source.fetchCurrent();
|
|
983
|
+
}
|
|
984
|
+
catch {
|
|
985
|
+
return { verdict: 'unverified', key: null };
|
|
986
|
+
}
|
|
987
|
+
if (current && !known.includes(current)) {
|
|
988
|
+
const verdict = await verifyEntitlementSignature(envelope, current);
|
|
989
|
+
return { verdict, key: verdict === 'valid' ? current : null };
|
|
990
|
+
}
|
|
991
|
+
return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
/**
|
|
995
|
+
* The free trial an application configures on the server (`trialDays`).
|
|
996
|
+
*
|
|
997
|
+
* The server starts one clock per installation at its first license read and
|
|
998
|
+
* signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
|
|
999
|
+
* the verified license like paid access does: no start date in extension
|
|
1000
|
+
* storage, nothing a device clock or a storage edit can move. Offline, the
|
|
1001
|
+
* cached license answers for up to 48 hours.
|
|
1002
|
+
*
|
|
1003
|
+
* `trial:ending` / `trial:ended` fire once per installation and trial (the
|
|
1004
|
+
* marker is kept in the SDK's storage), and not while the user has paid
|
|
1005
|
+
* access. Render state from `getTrial()`; the events are one-time notices.
|
|
1006
|
+
*/
|
|
1007
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1008
|
+
/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
|
|
1009
|
+
const MAX_TIMER_MS$1 = DAY_MS;
|
|
1010
|
+
/** The trial as of `clock`, or null when the license carries none (or a malformed one). */
|
|
1011
|
+
function trialState(trial, clock) {
|
|
1012
|
+
if (!trial)
|
|
1013
|
+
return null;
|
|
1014
|
+
const startedAt = Date.parse(trial.startedAt);
|
|
1015
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1016
|
+
if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
|
|
1017
|
+
return null;
|
|
1018
|
+
// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
|
|
1019
|
+
const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
|
|
1020
|
+
const left = endsAt - now;
|
|
1021
|
+
return {
|
|
1022
|
+
active: left > 0 && clock.checked,
|
|
1023
|
+
startedAt: trial.startedAt,
|
|
1024
|
+
endsAt: trial.endsAt,
|
|
1025
|
+
daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
|
|
1026
|
+
requiresOnlineCheck: left > 0 && !clock.checked,
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
class TrialNotifier {
|
|
1030
|
+
constructor(options) {
|
|
1031
|
+
this.options = options;
|
|
1032
|
+
this.timer = null;
|
|
1033
|
+
this.running = false;
|
|
1034
|
+
this.pending = Promise.resolve();
|
|
1035
|
+
}
|
|
1036
|
+
start() {
|
|
1037
|
+
this.running = true;
|
|
1038
|
+
void this.evaluate();
|
|
1039
|
+
}
|
|
1040
|
+
stop() {
|
|
1041
|
+
this.running = false;
|
|
1042
|
+
this.clearTimer();
|
|
1043
|
+
}
|
|
1044
|
+
/** Checks the held license; serialized, so two refreshes never send one event twice. */
|
|
1045
|
+
evaluate() {
|
|
1046
|
+
this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
|
|
1047
|
+
return this.pending;
|
|
1048
|
+
}
|
|
1049
|
+
async check() {
|
|
1050
|
+
if (!this.running)
|
|
1051
|
+
return;
|
|
1052
|
+
this.clearTimer();
|
|
1053
|
+
const trial = this.options.getTrial();
|
|
1054
|
+
if (!trial)
|
|
1055
|
+
return;
|
|
1056
|
+
const now = this.options.now();
|
|
1057
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1058
|
+
const endingAt = endsAt - this.options.endingDays * DAY_MS;
|
|
1059
|
+
const event = trial.daysLeft === 0
|
|
1060
|
+
? 'trial:ended'
|
|
1061
|
+
: trial.active && this.options.endingDays > 0 && now >= endingAt
|
|
1062
|
+
? 'trial:ending'
|
|
1063
|
+
: null;
|
|
1064
|
+
if (event && !this.options.hasPaidAccess())
|
|
1065
|
+
await this.send(event, trial);
|
|
1066
|
+
if (!this.running || trial.daysLeft === 0)
|
|
1067
|
+
return;
|
|
1068
|
+
const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
|
|
1069
|
+
this.timer = setTimeout(() => {
|
|
1070
|
+
this.timer = null;
|
|
1071
|
+
void this.evaluate();
|
|
1072
|
+
}, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
|
|
1073
|
+
}
|
|
1074
|
+
async send(event, trial) {
|
|
1075
|
+
const id = `${trial.startedAt}|${trial.endsAt}`;
|
|
1076
|
+
const field = event === 'trial:ended' ? 'ended' : 'ending';
|
|
1077
|
+
const stored = (await this.options.storage.get(this.options.storageKey));
|
|
1078
|
+
const sent = stored && typeof stored === 'object' ? stored : {};
|
|
1079
|
+
if (sent[field] === id || !this.running)
|
|
1080
|
+
return;
|
|
1081
|
+
await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
|
|
1082
|
+
this.options.emit(event, trial);
|
|
1083
|
+
}
|
|
1084
|
+
clearTimer() {
|
|
1085
|
+
if (this.timer !== null)
|
|
1086
|
+
clearTimeout(this.timer);
|
|
1087
|
+
this.timer = null;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
813
1090
|
|
|
814
1091
|
/**
|
|
815
1092
|
* Entitlement cache + refresh.
|
|
@@ -817,13 +1094,18 @@
|
|
|
817
1094
|
* The cached envelope is a cache OF the server projection, never a second
|
|
818
1095
|
* source of truth: it is verified when stored and re-verified on load (once
|
|
819
1096
|
* the project's public key is known), served without a round-trip while the
|
|
820
|
-
* TTL holds, served for
|
|
1097
|
+
* TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
|
|
821
1098
|
* locally by `expiresAt`. Background refresh polls at most every 15 minutes
|
|
822
1099
|
* and backs off exponentially on errors.
|
|
823
1100
|
*/
|
|
824
1101
|
const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
|
|
825
1102
|
const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
|
1103
|
+
/** Offline allowance when the signed license names none (older servers and caches). */
|
|
826
1104
|
const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
|
|
1105
|
+
/** Ceiling for a signed `offlineSeconds`. */
|
|
1106
|
+
const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
|
|
1107
|
+
/** `setTimeout` fires at once past this delay. */
|
|
1108
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
827
1109
|
// Allow small server/client clock skew without granting more than the signed age limit.
|
|
828
1110
|
const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
829
1111
|
const CACHE_VERSION = 1;
|
|
@@ -842,6 +1124,8 @@
|
|
|
842
1124
|
this.options = options;
|
|
843
1125
|
this.held = null;
|
|
844
1126
|
this.inflight = null;
|
|
1127
|
+
/** Device clock against the server's at the last license check; null within 5 minutes. */
|
|
1128
|
+
this.clockSkew = null;
|
|
845
1129
|
this.timer = null;
|
|
846
1130
|
this.refreshGeneration = 0;
|
|
847
1131
|
this.deadlineTimer = null;
|
|
@@ -883,8 +1167,10 @@
|
|
|
883
1167
|
envelope: JSON.parse(JSON.stringify(record.envelope)),
|
|
884
1168
|
fetchedAt: record.fetchedAt,
|
|
885
1169
|
verified: false,
|
|
1170
|
+
key: null,
|
|
886
1171
|
source: this.source === 'mock' ? 'mock' : 'cache',
|
|
887
1172
|
};
|
|
1173
|
+
this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
|
|
888
1174
|
this.lastFingerprint = this.fingerprint();
|
|
889
1175
|
return this.snapshot();
|
|
890
1176
|
}
|
|
@@ -895,8 +1181,7 @@
|
|
|
895
1181
|
if (this.source === 'mock')
|
|
896
1182
|
return;
|
|
897
1183
|
const held = this.held;
|
|
898
|
-
const key = await this.
|
|
899
|
-
const verdict = await verifyEntitlementSignature(held.envelope, key);
|
|
1184
|
+
const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
|
|
900
1185
|
if (held !== this.held)
|
|
901
1186
|
return;
|
|
902
1187
|
if (verdict === 'invalid') {
|
|
@@ -905,19 +1190,39 @@
|
|
|
905
1190
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
|
|
906
1191
|
}
|
|
907
1192
|
held.verified = verdict === 'valid';
|
|
1193
|
+
held.key = key;
|
|
908
1194
|
if (!held.verified) {
|
|
909
1195
|
throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
|
|
910
1196
|
}
|
|
911
1197
|
this.scheduleDeadline();
|
|
912
1198
|
}
|
|
1199
|
+
/** The key the held license was verified with; null when there is none or it is unverified. */
|
|
1200
|
+
get verifiedKey() {
|
|
1201
|
+
return this.held?.verified ? this.held.key : null;
|
|
1202
|
+
}
|
|
913
1203
|
getCached() {
|
|
914
1204
|
return this.held ? this.snapshot() : null;
|
|
915
1205
|
}
|
|
1206
|
+
/** The server trial in the held license; null without one, or while the license is unverified. */
|
|
1207
|
+
getTrial() {
|
|
1208
|
+
const held = this.held;
|
|
1209
|
+
if (!held || (this.source !== 'mock' && !held.verified))
|
|
1210
|
+
return null;
|
|
1211
|
+
const now = this.now();
|
|
1212
|
+
const issuedAt = Date.parse(held.envelope.payload.issuedAt);
|
|
1213
|
+
return trialState(held.envelope.payload.trial, {
|
|
1214
|
+
now,
|
|
1215
|
+
issuedAt,
|
|
1216
|
+
// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
|
|
1217
|
+
checked: this.source === 'mock' ||
|
|
1218
|
+
(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
916
1221
|
isFresh() {
|
|
917
1222
|
return (this.held !== null &&
|
|
918
1223
|
(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
|
|
919
1224
|
this.now() >= this.held.fetchedAt &&
|
|
920
|
-
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs,
|
|
1225
|
+
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
|
|
921
1226
|
}
|
|
922
1227
|
async get(options = {}) {
|
|
923
1228
|
if (!options.force && this.isFresh())
|
|
@@ -932,7 +1237,7 @@
|
|
|
932
1237
|
logger.debug('serving cached entitlement after refresh failure', err.code);
|
|
933
1238
|
return this.snapshot();
|
|
934
1239
|
}
|
|
935
|
-
return
|
|
1240
|
+
return this.snapshot();
|
|
936
1241
|
}
|
|
937
1242
|
}
|
|
938
1243
|
/** Fetches the projection from the backend, verifies and stores it. */
|
|
@@ -940,7 +1245,8 @@
|
|
|
940
1245
|
if (!this.inflight) {
|
|
941
1246
|
this.inflight = (async () => {
|
|
942
1247
|
const endUserRef = await this.options.getEndUserRef();
|
|
943
|
-
const
|
|
1248
|
+
const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
|
|
1249
|
+
const envelope = await this.options.api.getEntitlement(endUserRef, hint);
|
|
944
1250
|
return this.accept(envelope, this.source);
|
|
945
1251
|
})().finally(() => {
|
|
946
1252
|
this.inflight = null;
|
|
@@ -962,9 +1268,9 @@
|
|
|
962
1268
|
if (envelope.payload.endUserRef !== endUserRef) {
|
|
963
1269
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
|
|
964
1270
|
}
|
|
965
|
-
const verdict = this.source === 'mock'
|
|
966
|
-
? 'unverified'
|
|
967
|
-
: await
|
|
1271
|
+
const { verdict, key } = this.source === 'mock'
|
|
1272
|
+
? { verdict: 'unverified', key: null }
|
|
1273
|
+
: await verifyWithKeys(envelope, this.options.keys);
|
|
968
1274
|
if (verdict === 'invalid') {
|
|
969
1275
|
await this.discard();
|
|
970
1276
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
|
|
@@ -974,15 +1280,19 @@
|
|
|
974
1280
|
}
|
|
975
1281
|
const fetchedAt = this.now();
|
|
976
1282
|
const issuedAt = Date.parse(envelope.payload.issuedAt);
|
|
1283
|
+
// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
|
|
1284
|
+
if (this.source !== 'mock')
|
|
1285
|
+
this.measureClockSkew(fetchedAt, issuedAt);
|
|
977
1286
|
if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
|
|
978
1287
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
|
|
979
1288
|
}
|
|
980
|
-
this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
|
|
1289
|
+
this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
|
|
981
1290
|
const record = { v: CACHE_VERSION, envelope, fetchedAt };
|
|
982
1291
|
await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
|
|
983
1292
|
this.backoffMs = 0;
|
|
984
1293
|
this.scheduleDeadline();
|
|
985
1294
|
this.notifyIfChanged();
|
|
1295
|
+
this.options.onAccepted?.();
|
|
986
1296
|
return this.snapshot();
|
|
987
1297
|
}
|
|
988
1298
|
/** Drain an older installation refresh before changing identity. */
|
|
@@ -1036,7 +1346,7 @@
|
|
|
1036
1346
|
this.deadlineTimer = null;
|
|
1037
1347
|
this.notifyIfChanged();
|
|
1038
1348
|
this.scheduleDeadline();
|
|
1039
|
-
}, remaining);
|
|
1349
|
+
}, Math.min(remaining, MAX_TIMER_MS));
|
|
1040
1350
|
}
|
|
1041
1351
|
schedule(delayMs) {
|
|
1042
1352
|
const generation = this.refreshGeneration;
|
|
@@ -1057,14 +1367,12 @@
|
|
|
1057
1367
|
}
|
|
1058
1368
|
}, delayMs);
|
|
1059
1369
|
}
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
return null;
|
|
1067
|
-
}
|
|
1370
|
+
measureClockSkew(local, server) {
|
|
1371
|
+
const ms = local - server;
|
|
1372
|
+
this.clockSkew =
|
|
1373
|
+
Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
|
|
1374
|
+
? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
|
|
1375
|
+
: null;
|
|
1068
1376
|
}
|
|
1069
1377
|
async discard() {
|
|
1070
1378
|
this.held = null;
|
|
@@ -1087,13 +1395,25 @@
|
|
|
1087
1395
|
if (!this.held)
|
|
1088
1396
|
return NaN;
|
|
1089
1397
|
// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
|
|
1090
|
-
return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) +
|
|
1398
|
+
return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
|
|
1399
|
+
}
|
|
1400
|
+
/** The signed allowance of the held license, or 48 hours when it names none. */
|
|
1401
|
+
offlineAgeMs() {
|
|
1402
|
+
const seconds = this.held?.envelope.payload.offlineSeconds;
|
|
1403
|
+
if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
|
|
1404
|
+
return MAX_OFFLINE_AGE_MS;
|
|
1405
|
+
return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
|
|
1091
1406
|
}
|
|
1092
1407
|
snapshot() {
|
|
1093
1408
|
if (!this.held)
|
|
1094
|
-
return EMPTY_ENTITLEMENT;
|
|
1409
|
+
return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
|
|
1095
1410
|
if (this.source !== 'mock' && !this.held.verified) {
|
|
1096
|
-
return {
|
|
1411
|
+
return {
|
|
1412
|
+
...EMPTY_ENTITLEMENT,
|
|
1413
|
+
requiresOnlineCheck: true,
|
|
1414
|
+
clockSkew: this.clockSkew,
|
|
1415
|
+
source: this.held.source,
|
|
1416
|
+
};
|
|
1097
1417
|
}
|
|
1098
1418
|
const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
|
|
1099
1419
|
const hasPaidAccess = collectFeatures(items).length > 0 ||
|
|
@@ -1109,6 +1429,7 @@
|
|
|
1109
1429
|
features: requiresOnlineCheck ? [] : collectFeatures(items),
|
|
1110
1430
|
requiresOnlineCheck,
|
|
1111
1431
|
offlineUntil,
|
|
1432
|
+
clockSkew: this.clockSkew,
|
|
1112
1433
|
verified: this.held.verified,
|
|
1113
1434
|
issuedAt: this.held.envelope.payload.issuedAt,
|
|
1114
1435
|
fetchedAt: this.held.fetchedAt,
|
|
@@ -1197,6 +1518,16 @@
|
|
|
1197
1518
|
this.map.delete(key);
|
|
1198
1519
|
}
|
|
1199
1520
|
}
|
|
1521
|
+
/**
|
|
1522
|
+
* The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
|
|
1523
|
+
* only the trial start there (never `endUserRef`), so devices on one synced account share the
|
|
1524
|
+
* trial. Uninstalling clears it from the account, so it does not survive a reinstall.
|
|
1525
|
+
*/
|
|
1526
|
+
function createSyncStorage() {
|
|
1527
|
+
const g = extensionGlobals();
|
|
1528
|
+
const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
|
|
1529
|
+
return area ? new ExtensionStorage(area) : null;
|
|
1530
|
+
}
|
|
1200
1531
|
function createStorage() {
|
|
1201
1532
|
const g = extensionGlobals();
|
|
1202
1533
|
const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
|
|
@@ -1253,7 +1584,7 @@
|
|
|
1253
1584
|
const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1254
1585
|
const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
|
|
1255
1586
|
const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1256
|
-
const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
|
|
1587
|
+
const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
|
|
1257
1588
|
if (!Number.isFinite(Date.parse(created.expiresAt)))
|
|
1258
1589
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
|
|
1259
1590
|
const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
|
|
@@ -1313,8 +1644,9 @@
|
|
|
1313
1644
|
break;
|
|
1314
1645
|
if (claim.state === 'complete') {
|
|
1315
1646
|
const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
|
|
1647
|
+
const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
|
|
1316
1648
|
await this.options.storage.remove(this.pendingKey);
|
|
1317
|
-
return { state: 'complete', entitlement };
|
|
1649
|
+
return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
|
|
1318
1650
|
}
|
|
1319
1651
|
if (claim.state !== 'pending')
|
|
1320
1652
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
|
|
@@ -1460,11 +1792,12 @@
|
|
|
1460
1792
|
}
|
|
1461
1793
|
|
|
1462
1794
|
/** Kept in sync with package.json by tests/unit/version.test.ts. */
|
|
1463
|
-
const VERSION = '0.
|
|
1795
|
+
const VERSION = '0.11.0';
|
|
1464
1796
|
|
|
1465
1797
|
const DEFAULT_API_URL = 'https://bff.extenshi.io';
|
|
1466
1798
|
const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
1467
1799
|
const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1800
|
+
const DEFAULT_TRIAL_ENDING_DAYS = 2;
|
|
1468
1801
|
|
|
1469
1802
|
const ENVIRONMENTS = new Set(['production', 'sandbox', 'development']);
|
|
1470
1803
|
const LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug']);
|
|
@@ -1492,7 +1825,7 @@
|
|
|
1492
1825
|
if (!isHttpUrl(apiUrl))
|
|
1493
1826
|
errors.push('apiUrl must be an http(s) URL');
|
|
1494
1827
|
const entitlementPublicKey = input.entitlementPublicKey ?? null;
|
|
1495
|
-
if (entitlementPublicKey !== null &&
|
|
1828
|
+
if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
|
|
1496
1829
|
errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
|
|
1497
1830
|
}
|
|
1498
1831
|
const environment = input.environment ?? 'production';
|
|
@@ -1514,6 +1847,9 @@
|
|
|
1514
1847
|
const theme = input.theme ?? {};
|
|
1515
1848
|
if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
|
|
1516
1849
|
errors.push('theme.mode must be light, dark or auto');
|
|
1850
|
+
const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
|
|
1851
|
+
if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
|
|
1852
|
+
errors.push('trialEndingDays must be a whole number of days between 0 and 365');
|
|
1517
1853
|
if (input.mock &&
|
|
1518
1854
|
input.mockData !== undefined &&
|
|
1519
1855
|
(typeof input.mockData !== 'object' || input.mockData === null)) {
|
|
@@ -1534,6 +1870,8 @@
|
|
|
1534
1870
|
mock: input.mock === true,
|
|
1535
1871
|
mockData: input.mock ? (input.mockData ?? {}) : null,
|
|
1536
1872
|
theme,
|
|
1873
|
+
trialEndingDays,
|
|
1874
|
+
syncTrialStart: input.syncTrialStart !== false,
|
|
1537
1875
|
};
|
|
1538
1876
|
}
|
|
1539
1877
|
|
|
@@ -1585,8 +1923,10 @@
|
|
|
1585
1923
|
* extends it with `getOffer()` / `showPaywall()`.
|
|
1586
1924
|
*
|
|
1587
1925
|
* Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
|
|
1588
|
-
* `locale
|
|
1589
|
-
*
|
|
1926
|
+
* `locale`, checkout session IDs and, with a server trial, the trial start date
|
|
1927
|
+
* the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
|
|
1928
|
+
* challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
|
|
1929
|
+
* storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
|
|
1590
1930
|
*/
|
|
1591
1931
|
/** Server-side offer cache is 5 min; mirror it in memory. */
|
|
1592
1932
|
const OFFER_TTL_MS = 5 * 60 * 1000;
|
|
@@ -1597,12 +1937,30 @@
|
|
|
1597
1937
|
this.endUserRefPromise = null;
|
|
1598
1938
|
this.offer = null;
|
|
1599
1939
|
this.offerInflight = null;
|
|
1940
|
+
/** The signing key the server returned in this session; never one read from storage. */
|
|
1941
|
+
this.serverKey = null;
|
|
1942
|
+
/** Trust order for license signatures; see payment/signature.ts. */
|
|
1943
|
+
this.keys = {
|
|
1944
|
+
known: async () => {
|
|
1945
|
+
const pinned = this.config.entitlementPublicKey;
|
|
1946
|
+
const offline = pinned ?? (await this.readSavedServerKey());
|
|
1947
|
+
return [...new Set([this.serverKey, offline].filter((key) => !!key))];
|
|
1948
|
+
},
|
|
1949
|
+
fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
|
|
1950
|
+
};
|
|
1600
1951
|
this.readyPromise = null;
|
|
1601
1952
|
this.destroyed = false;
|
|
1602
1953
|
this.config = resolveConfig(config);
|
|
1603
1954
|
logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
|
|
1604
1955
|
this.now = deps.now ?? (() => Date.now());
|
|
1605
1956
|
this.storage = deps.storage ?? createStorage();
|
|
1957
|
+
this.openUrl = deps.openUrl;
|
|
1958
|
+
this.syncStorage =
|
|
1959
|
+
!this.config.syncTrialStart || this.config.mock
|
|
1960
|
+
? null
|
|
1961
|
+
: deps.syncStorage === undefined
|
|
1962
|
+
? createSyncStorage()
|
|
1963
|
+
: deps.syncStorage;
|
|
1606
1964
|
const transport = deps.transport ??
|
|
1607
1965
|
(this.config.mock
|
|
1608
1966
|
? new MockTransport(this.config.mockData ?? {})
|
|
@@ -1615,11 +1973,26 @@
|
|
|
1615
1973
|
cacheTtlMs: this.config.cacheTtlMs,
|
|
1616
1974
|
source: this.config.mock ? 'mock' : 'network',
|
|
1617
1975
|
getEndUserRef: () => this.getEndUserRef(),
|
|
1618
|
-
|
|
1976
|
+
keys: this.keys,
|
|
1619
1977
|
onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
|
|
1978
|
+
onAccepted: () => {
|
|
1979
|
+
void this.trial.evaluate();
|
|
1980
|
+
void this.rememberTrialStart();
|
|
1981
|
+
},
|
|
1982
|
+
getTrialStartHint: () => this.readTrialStartHint(),
|
|
1620
1983
|
onError: (error) => this.reportError(error),
|
|
1621
1984
|
now: this.now,
|
|
1622
1985
|
});
|
|
1986
|
+
this.trial = new TrialNotifier({
|
|
1987
|
+
storage: this.storage,
|
|
1988
|
+
storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
|
|
1989
|
+
endingDays: this.config.trialEndingDays,
|
|
1990
|
+
getTrial: () => this.entitlements.getTrial(),
|
|
1991
|
+
// A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
|
|
1992
|
+
hasPaidAccess: () => (this.entitlements.getCached()?.items ?? []).some(isLive),
|
|
1993
|
+
emit: (event, trial) => this.emitter.emit(event, trial),
|
|
1994
|
+
now: this.now,
|
|
1995
|
+
});
|
|
1623
1996
|
this.checkout = new CheckoutManager({
|
|
1624
1997
|
api: this.api,
|
|
1625
1998
|
storage: this.storage,
|
|
@@ -1633,6 +2006,13 @@
|
|
|
1633
2006
|
(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
|
|
1634
2007
|
now: this.now,
|
|
1635
2008
|
});
|
|
2009
|
+
this.backup = new CloudBackup({
|
|
2010
|
+
storage: this.storage,
|
|
2011
|
+
publishableKey: this.config.publishableKey,
|
|
2012
|
+
apiUrl: this.config.apiUrl,
|
|
2013
|
+
fetch: deps.fetch,
|
|
2014
|
+
mock: this.config.mock,
|
|
2015
|
+
});
|
|
1636
2016
|
this.recovery = new RecoveryManager({
|
|
1637
2017
|
api: this.api,
|
|
1638
2018
|
locale: this.config.locale,
|
|
@@ -1646,7 +2026,7 @@
|
|
|
1646
2026
|
envelope.payload.publishableKey !== this.config.publishableKey ||
|
|
1647
2027
|
!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
|
|
1648
2028
|
Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
|
|
1649
|
-
(await
|
|
2029
|
+
(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
|
|
1650
2030
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
|
|
1651
2031
|
this.entitlements.stopAutoRefresh();
|
|
1652
2032
|
try {
|
|
@@ -1664,6 +2044,7 @@
|
|
|
1664
2044
|
this.entitlements.startAutoRefresh();
|
|
1665
2045
|
}
|
|
1666
2046
|
},
|
|
2047
|
+
onStorageGrant: (grant) => this.backup.accept(grant),
|
|
1667
2048
|
});
|
|
1668
2049
|
if (config.onError)
|
|
1669
2050
|
this.emitter.on('error', config.onError);
|
|
@@ -1709,8 +2090,11 @@
|
|
|
1709
2090
|
catch (error) {
|
|
1710
2091
|
this.reportError(error);
|
|
1711
2092
|
}
|
|
1712
|
-
|
|
2093
|
+
void this.confirmSavedServerKey();
|
|
2094
|
+
if (!this.destroyed) {
|
|
1713
2095
|
this.entitlements.startAutoRefresh();
|
|
2096
|
+
this.trial.start();
|
|
2097
|
+
}
|
|
1714
2098
|
}
|
|
1715
2099
|
/** The anonymous, random id this install is known by. */
|
|
1716
2100
|
getEndUserRef() {
|
|
@@ -1731,6 +2115,16 @@
|
|
|
1731
2115
|
await this.initialize();
|
|
1732
2116
|
return this.entitlements.get(options);
|
|
1733
2117
|
}
|
|
2118
|
+
/**
|
|
2119
|
+
* The free trial the application set on the server, from the verified license, or null when
|
|
2120
|
+
* there is none (or the license could not be verified yet). Answers offline from the cached
|
|
2121
|
+
* license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
|
|
2122
|
+
* `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
|
|
2123
|
+
*/
|
|
2124
|
+
async getTrial(options = {}) {
|
|
2125
|
+
await this.getEntitlement(options);
|
|
2126
|
+
return this.entitlements.getTrial();
|
|
2127
|
+
}
|
|
1734
2128
|
/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
|
|
1735
2129
|
async isPaid(sku) {
|
|
1736
2130
|
return isEntitled(await this.getEntitlement(), sku);
|
|
@@ -1814,6 +2208,41 @@
|
|
|
1814
2208
|
throw this.reportError(error);
|
|
1815
2209
|
}
|
|
1816
2210
|
}
|
|
2211
|
+
/**
|
|
2212
|
+
* Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
|
|
2213
|
+
* hosted restore page shows the storage disclosure and the buyer confirms with
|
|
2214
|
+
* the code from the purchase email. `cloudBackup` in the result says whether it is
|
|
2215
|
+
* on. Buyers only; consent is recorded by the server.
|
|
2216
|
+
*/
|
|
2217
|
+
enableCloudBackup(options = {}) {
|
|
2218
|
+
return this.restorePurchase({ ...options, purpose: 'storage' });
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2221
|
+
* The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
|
|
2222
|
+
* while cloud backup is off on this installation. Extension pages and background
|
|
2223
|
+
* only: it rejects in a content script, and must never be sent to one.
|
|
2224
|
+
*/
|
|
2225
|
+
async cloudBackupToken() {
|
|
2226
|
+
return this.backup.token();
|
|
2227
|
+
}
|
|
2228
|
+
/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
|
|
2229
|
+
async disableCloudBackup() {
|
|
2230
|
+
try {
|
|
2231
|
+
await this.backup.disable();
|
|
2232
|
+
}
|
|
2233
|
+
catch (error) {
|
|
2234
|
+
throw this.reportError(error);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
|
|
2238
|
+
async deleteCloudBackup() {
|
|
2239
|
+
try {
|
|
2240
|
+
await this.backup.delete();
|
|
2241
|
+
}
|
|
2242
|
+
catch (error) {
|
|
2243
|
+
throw this.reportError(error);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
1817
2246
|
/** Read-only license view. Entitlements retain cache/signature/offline semantics. */
|
|
1818
2247
|
async getLicenseSummary(options = {}) {
|
|
1819
2248
|
await this.initialize();
|
|
@@ -1883,6 +2312,7 @@
|
|
|
1883
2312
|
destroy() {
|
|
1884
2313
|
this.destroyed = true;
|
|
1885
2314
|
this.recovery.stop();
|
|
2315
|
+
this.trial.stop();
|
|
1886
2316
|
this.entitlements.stopAutoRefresh();
|
|
1887
2317
|
this.emitter.removeAll();
|
|
1888
2318
|
}
|
|
@@ -1894,8 +2324,9 @@
|
|
|
1894
2324
|
if (!this.offerInflight) {
|
|
1895
2325
|
this.offerInflight = this.api
|
|
1896
2326
|
.getOffer(this.config.locale)
|
|
1897
|
-
.then((value) => {
|
|
2327
|
+
.then(async (value) => {
|
|
1898
2328
|
this.offer = { value, fetchedAt: this.now() };
|
|
2329
|
+
await this.rememberServerKey(value.entitlementPublicKey);
|
|
1899
2330
|
return value;
|
|
1900
2331
|
})
|
|
1901
2332
|
.finally(() => {
|
|
@@ -1904,8 +2335,88 @@
|
|
|
1904
2335
|
}
|
|
1905
2336
|
return this.offerInflight;
|
|
1906
2337
|
}
|
|
1907
|
-
|
|
1908
|
-
return this.config.entitlementPublicKey
|
|
2338
|
+
get serverKeyStorageKey() {
|
|
2339
|
+
return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
|
|
2340
|
+
}
|
|
2341
|
+
async readSavedServerKey() {
|
|
2342
|
+
try {
|
|
2343
|
+
const value = await this.storage.get(this.serverKeyStorageKey);
|
|
2344
|
+
return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
|
|
2345
|
+
}
|
|
2346
|
+
catch {
|
|
2347
|
+
return null;
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
/**
|
|
2351
|
+
* Keeps the server's key next to the license cache so a restart with no network can verify it.
|
|
2352
|
+
* Not with a bundled key: that one already covers the restart, and storage stays untrusted.
|
|
2353
|
+
*/
|
|
2354
|
+
async rememberServerKey(key) {
|
|
2355
|
+
if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
|
|
2356
|
+
return;
|
|
2357
|
+
this.serverKey = key;
|
|
2358
|
+
if (this.config.entitlementPublicKey || this.config.mock)
|
|
2359
|
+
return;
|
|
2360
|
+
try {
|
|
2361
|
+
if ((await this.readSavedServerKey()) !== key)
|
|
2362
|
+
await this.storage.set(this.serverKeyStorageKey, key);
|
|
2363
|
+
}
|
|
2364
|
+
catch (error) {
|
|
2365
|
+
logger.debug('signing key not saved', error);
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
/**
|
|
2369
|
+
* A license verified with the saved key alone is checked against the server once per start:
|
|
2370
|
+
* when the server's key differs (rotation, or an edited storage) the license is fetched again,
|
|
2371
|
+
* and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
|
|
2372
|
+
*/
|
|
2373
|
+
async confirmSavedServerKey() {
|
|
2374
|
+
const used = this.entitlements.verifiedKey;
|
|
2375
|
+
if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
|
|
2376
|
+
return;
|
|
2377
|
+
try {
|
|
2378
|
+
if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
|
|
2379
|
+
return;
|
|
2380
|
+
}
|
|
2381
|
+
catch {
|
|
2382
|
+
return;
|
|
2383
|
+
}
|
|
2384
|
+
try {
|
|
2385
|
+
await this.entitlements.refresh();
|
|
2386
|
+
}
|
|
2387
|
+
catch {
|
|
2388
|
+
await this.entitlements.reverify().catch((error) => this.reportError(error));
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
get trialStartKey() {
|
|
2392
|
+
return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
|
|
2393
|
+
}
|
|
2394
|
+
/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
|
|
2395
|
+
async readTrialStartHint() {
|
|
2396
|
+
if (!this.syncStorage)
|
|
2397
|
+
return null;
|
|
2398
|
+
try {
|
|
2399
|
+
const value = await this.syncStorage.get(this.trialStartKey);
|
|
2400
|
+
return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
|
|
2401
|
+
}
|
|
2402
|
+
catch {
|
|
2403
|
+
return null;
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
|
|
2407
|
+
async rememberTrialStart() {
|
|
2408
|
+
const trial = this.entitlements.getTrial();
|
|
2409
|
+
if (!this.syncStorage || !trial)
|
|
2410
|
+
return;
|
|
2411
|
+
try {
|
|
2412
|
+
const synced = await this.readTrialStartHint();
|
|
2413
|
+
if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
|
|
2414
|
+
return;
|
|
2415
|
+
await this.syncStorage.set(this.trialStartKey, trial.startedAt);
|
|
2416
|
+
}
|
|
2417
|
+
catch (error) {
|
|
2418
|
+
logger.debug('trial start not synced', error);
|
|
2419
|
+
}
|
|
1909
2420
|
}
|
|
1910
2421
|
reportError(error) {
|
|
1911
2422
|
const err = ExtenshiPayError.from(error);
|