@extenshi/pay 0.9.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +138 -17
- 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 +271 -26
- package/dist/core.d.ts +271 -26
- package/dist/core.js +589 -49
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +584 -50
- package/dist/core.mjs.map +1 -1
- package/dist/extenshi-pay-lite.js +577 -49
- 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 +577 -49
- package/dist/extenshi-pay-lite.mjs.map +1 -1
- package/dist/extenshi-pay.cjs.js +694 -61
- 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 +694 -61
- 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 +689 -62
- package/dist/extenshi-pay.mjs.map +1 -1
- package/dist/index.d.mts +288 -26
- package/dist/index.d.ts +288 -26
- package/dist/lite.d.mts +214 -13
- package/dist/lite.d.ts +214 -13
- 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/renderer.d.ts +7 -0
- package/dist/paywall/renderer.d.ts.map +1 -1
- package/dist/paywall.d.mts +7 -0
- package/dist/paywall.d.ts +7 -0
- package/dist/paywall.js +54 -14
- package/dist/paywall.js.map +1 -1
- package/dist/paywall.mjs +54 -14
- 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 +36 -0
- package/dist/types/contract.d.ts.map +1 -1
- package/dist/types/entitlement.d.ts +39 -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 +10 -0
- 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.12.0
|
|
3
3
|
* (c) 2026 Extenshi.io
|
|
4
4
|
* Released under the MIT License.
|
|
5
|
-
* commit
|
|
5
|
+
* commit 7f4b4e98165b3c8eb11e100b3855fee1ade7aaab · built by `rollup -c`
|
|
6
6
|
*/
|
|
7
7
|
/**
|
|
8
8
|
* Wire contract between the SDK and catalog-bff `pay.*`.
|
|
@@ -29,6 +29,8 @@ const PUBLISHABLE_KEY_RE = new RegExp(`^${PAY_PUBLISHABLE_KEY_PREFIX}[0-9a-f]{${
|
|
|
29
29
|
function isPayPublishableKey(value) {
|
|
30
30
|
return typeof value === 'string' && PUBLISHABLE_KEY_RE.test(value);
|
|
31
31
|
}
|
|
32
|
+
// Outside the seller SKU grammar. Issued only in a signed projection, never in the sales ledger.
|
|
33
|
+
const PAY_REGIONAL_ACCESS_SKU = '@regional-free';
|
|
32
34
|
/**
|
|
33
35
|
* Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA
|
|
34
36
|
* digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The
|
|
@@ -67,6 +69,8 @@ function canonicalJson(value) {
|
|
|
67
69
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
68
70
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
|
|
69
71
|
}
|
|
72
|
+
/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
|
|
73
|
+
const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
|
|
70
74
|
|
|
71
75
|
const ERROR_CODES = {
|
|
72
76
|
INVALID_CONFIG: 'INVALID_CONFIG',
|
|
@@ -138,7 +142,7 @@ async function getOrCreateEndUserRef(storage) {
|
|
|
138
142
|
* developed with no backend: offers and entitlements come from `mockData`, a
|
|
139
143
|
* mock checkout completes after `claimAfterPolls` polls and grants the SKU.
|
|
140
144
|
*/
|
|
141
|
-
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
145
|
+
const DAY_MS$1 = 24 * 60 * 60 * 1000;
|
|
142
146
|
/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
|
|
143
147
|
function mockConsent(value) {
|
|
144
148
|
const consent = value;
|
|
@@ -156,6 +160,10 @@ class MockTransport {
|
|
|
156
160
|
this.claimAfterPolls = data.claimAfterPolls ?? 1;
|
|
157
161
|
this.withdrawalWaiver =
|
|
158
162
|
data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
|
|
163
|
+
this.seller = data.seller;
|
|
164
|
+
this.trial = null;
|
|
165
|
+
if (data.trial)
|
|
166
|
+
this.setTrial(data.trial.days, data.trial.startedAt);
|
|
159
167
|
}
|
|
160
168
|
async call(procedure, _kind, input) {
|
|
161
169
|
switch (procedure) {
|
|
@@ -177,6 +185,14 @@ class MockTransport {
|
|
|
177
185
|
setEntitlements(items) {
|
|
178
186
|
this.entitlements = [...items];
|
|
179
187
|
}
|
|
188
|
+
/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
|
|
189
|
+
setTrial(days, startedAt = new Date().toISOString()) {
|
|
190
|
+
const start = Date.parse(startedAt);
|
|
191
|
+
this.trial =
|
|
192
|
+
days === null || !Number.isFinite(start)
|
|
193
|
+
? null
|
|
194
|
+
: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
|
|
195
|
+
}
|
|
180
196
|
cancelSession(sessionId) {
|
|
181
197
|
const session = this.sessions.get(sessionId);
|
|
182
198
|
if (session)
|
|
@@ -196,6 +212,7 @@ class MockTransport {
|
|
|
196
212
|
offers: [...this.offers],
|
|
197
213
|
entitlementPublicKey: null,
|
|
198
214
|
withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
|
|
215
|
+
...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
|
|
199
216
|
};
|
|
200
217
|
}
|
|
201
218
|
createCheckout(sku, withdrawalWaiver) {
|
|
@@ -233,7 +250,7 @@ class MockTransport {
|
|
|
233
250
|
grant(sku) {
|
|
234
251
|
const offer = this.offers.find((o) => o.sku === sku);
|
|
235
252
|
const expiresAt = offer?.kind === 'subscription'
|
|
236
|
-
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
|
|
253
|
+
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
|
|
237
254
|
: null;
|
|
238
255
|
this.entitlements = [
|
|
239
256
|
...this.entitlements.filter((item) => item.sku !== sku),
|
|
@@ -255,6 +272,7 @@ class MockTransport {
|
|
|
255
272
|
endUserRef,
|
|
256
273
|
entitlements: [...this.entitlements],
|
|
257
274
|
issuedAt: new Date().toISOString(),
|
|
275
|
+
...(this.trial ? { trial: { ...this.trial } } : {}),
|
|
258
276
|
},
|
|
259
277
|
signature: null,
|
|
260
278
|
alg: null,
|
|
@@ -268,12 +286,17 @@ class PayApi {
|
|
|
268
286
|
this.transport = transport;
|
|
269
287
|
this.publishableKey = publishableKey;
|
|
270
288
|
}
|
|
271
|
-
/**
|
|
272
|
-
|
|
289
|
+
/**
|
|
290
|
+
* `locale` opens the hosted recovery page (and its email) in the user's language.
|
|
291
|
+
* `purpose` is sent only for `storage`: a plain restore keeps the request older
|
|
292
|
+
* BFFs know, and their non-strict zod input strips the key anyway.
|
|
293
|
+
*/
|
|
294
|
+
createRestoreSession(claimChallenge, locale, purpose) {
|
|
273
295
|
return this.transport.call('pay.createRestoreSession', 'mutation', {
|
|
274
296
|
publishableKey: this.publishableKey,
|
|
275
297
|
claimChallenge,
|
|
276
298
|
...(locale ? { locale } : {}),
|
|
299
|
+
...(purpose === 'storage' ? { purpose } : {}),
|
|
277
300
|
});
|
|
278
301
|
}
|
|
279
302
|
claimRestoreSession(sessionId, claimSecret) {
|
|
@@ -312,10 +335,12 @@ class PayApi {
|
|
|
312
335
|
endUserRef,
|
|
313
336
|
});
|
|
314
337
|
}
|
|
315
|
-
|
|
338
|
+
/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
|
|
339
|
+
getEntitlement(endUserRef, trialStartedHint) {
|
|
316
340
|
return this.transport.call('pay.getEntitlement', 'query', {
|
|
317
341
|
publishableKey: this.publishableKey,
|
|
318
342
|
endUserRef,
|
|
343
|
+
...(trialStartedHint ? { trialStartedHint } : {}),
|
|
319
344
|
});
|
|
320
345
|
}
|
|
321
346
|
getPortalUrl(endUserRef, customerId, locale) {
|
|
@@ -713,6 +738,118 @@ var checkout = /*#__PURE__*/Object.freeze({
|
|
|
713
738
|
openInNewTab: openInNewTab
|
|
714
739
|
});
|
|
715
740
|
|
|
741
|
+
/**
|
|
742
|
+
* Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
|
|
743
|
+
* token: only a verified restore claim issues it; this module keeps it in the
|
|
744
|
+
* SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
|
|
745
|
+
* through `cloudBackupToken()`. The token is never logged and never answered to
|
|
746
|
+
* a content script: route those calls to the background.
|
|
747
|
+
*/
|
|
748
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
749
|
+
/** True in a content script, where the token must not be handed out. */
|
|
750
|
+
function inContentScript() {
|
|
751
|
+
const g = globalThis;
|
|
752
|
+
return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
|
|
753
|
+
}
|
|
754
|
+
class CloudBackup {
|
|
755
|
+
constructor(options) {
|
|
756
|
+
this.options = options;
|
|
757
|
+
this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
758
|
+
}
|
|
759
|
+
get storageKey() {
|
|
760
|
+
return `extenshi-pay:${this.options.publishableKey}:storageToken`;
|
|
761
|
+
}
|
|
762
|
+
/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
|
|
763
|
+
async accept(grant) {
|
|
764
|
+
if (!grant || typeof grant !== 'object')
|
|
765
|
+
return undefined;
|
|
766
|
+
try {
|
|
767
|
+
if (grant.state === 'granted') {
|
|
768
|
+
if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
|
|
769
|
+
return undefined;
|
|
770
|
+
await this.options.storage.set(this.storageKey, grant.token);
|
|
771
|
+
return 'on';
|
|
772
|
+
}
|
|
773
|
+
if (grant.state === 'unavailable') {
|
|
774
|
+
await this.options.storage.remove(this.storageKey);
|
|
775
|
+
return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
catch {
|
|
779
|
+
logger.warn('cloud backup state could not be saved');
|
|
780
|
+
}
|
|
781
|
+
return undefined;
|
|
782
|
+
}
|
|
783
|
+
async token() {
|
|
784
|
+
this.assertTrustedContext();
|
|
785
|
+
const value = await this.options.storage.get(this.storageKey);
|
|
786
|
+
return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
|
|
787
|
+
}
|
|
788
|
+
/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
|
|
789
|
+
async disable() {
|
|
790
|
+
const token = await this.token();
|
|
791
|
+
if (!token)
|
|
792
|
+
return;
|
|
793
|
+
if (!this.options.mock) {
|
|
794
|
+
const status = await this.request('/v1/storage/grant', token);
|
|
795
|
+
if (status !== 401)
|
|
796
|
+
this.throwUnlessOk(status);
|
|
797
|
+
}
|
|
798
|
+
await this.options.storage.remove(this.storageKey);
|
|
799
|
+
}
|
|
800
|
+
/** Deletes the buyer's cloud copy and turns the backup off on every device. */
|
|
801
|
+
async delete() {
|
|
802
|
+
const token = await this.token();
|
|
803
|
+
if (!token)
|
|
804
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
|
|
805
|
+
if (!this.options.mock) {
|
|
806
|
+
const status = await this.request('/v1/storage/data', token);
|
|
807
|
+
if (status === 401) {
|
|
808
|
+
// The server no longer accepts this token, so it is useless here; the copy was not deleted.
|
|
809
|
+
await this.options.storage.remove(this.storageKey);
|
|
810
|
+
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 });
|
|
811
|
+
}
|
|
812
|
+
this.throwUnlessOk(status);
|
|
813
|
+
}
|
|
814
|
+
await this.options.storage.remove(this.storageKey);
|
|
815
|
+
}
|
|
816
|
+
assertTrustedContext() {
|
|
817
|
+
if (inContentScript())
|
|
818
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
|
|
819
|
+
}
|
|
820
|
+
throwUnlessOk(status) {
|
|
821
|
+
if (status >= 200 && status < 300)
|
|
822
|
+
return;
|
|
823
|
+
if (status === 429)
|
|
824
|
+
throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
|
|
825
|
+
if (status >= 500)
|
|
826
|
+
throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
|
|
827
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
|
|
828
|
+
}
|
|
829
|
+
async request(path, token) {
|
|
830
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
831
|
+
const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
|
|
832
|
+
try {
|
|
833
|
+
const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
|
|
834
|
+
method: 'DELETE',
|
|
835
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
836
|
+
credentials: 'omit',
|
|
837
|
+
signal: controller?.signal,
|
|
838
|
+
});
|
|
839
|
+
return response.status;
|
|
840
|
+
}
|
|
841
|
+
catch (error) {
|
|
842
|
+
if (controller?.signal.aborted)
|
|
843
|
+
throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
|
|
844
|
+
throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
|
|
845
|
+
}
|
|
846
|
+
finally {
|
|
847
|
+
if (timer !== null)
|
|
848
|
+
clearTimeout(timer);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
716
853
|
/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
|
|
717
854
|
const LIVE_STATUSES = new Set(['active', 'grace']);
|
|
718
855
|
function isLive(item) {
|
|
@@ -767,9 +904,17 @@ Object.freeze(EMPTY_ENTITLEMENT.features);
|
|
|
767
904
|
/**
|
|
768
905
|
* Ed25519 verification of the entitlement projection.
|
|
769
906
|
*
|
|
770
|
-
* Tamper resistance, not DRM.
|
|
771
|
-
*
|
|
772
|
-
*
|
|
907
|
+
* Tamper resistance, not DRM. Callers must deny access for both invalid and
|
|
908
|
+
* unverified envelopes outside explicit mocks.
|
|
909
|
+
*
|
|
910
|
+
* Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
|
|
911
|
+
* 1. the key the server returned over HTTPS in this session;
|
|
912
|
+
* 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
|
|
913
|
+
* verification without a round-trip: a key read from extension storage is then never used;
|
|
914
|
+
* 3. without a bundled key, the server key saved in `storage.local` next to the
|
|
915
|
+
* license cache, so a restart with no network can still verify the cache.
|
|
916
|
+
* When none of them verifies an envelope the server is asked for its current key once
|
|
917
|
+
* (a rotated key), and that answer decides.
|
|
773
918
|
*/
|
|
774
919
|
function base64ToBytes(base64) {
|
|
775
920
|
const binary = atob(base64);
|
|
@@ -804,6 +949,140 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
804
949
|
return 'invalid';
|
|
805
950
|
}
|
|
806
951
|
}
|
|
952
|
+
const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
953
|
+
/**
|
|
954
|
+
* `invalid` only when the server's current key was checked too (or the envelope carries no
|
|
955
|
+
* signature at all). A mismatch against known keys while the server is unreachable is
|
|
956
|
+
* `unverified`: it may be a rotated key, and no paid access is granted either way.
|
|
957
|
+
*/
|
|
958
|
+
async function verifyWithKeys(envelope, source) {
|
|
959
|
+
if (!envelope.signature || envelope.alg !== 'ed25519')
|
|
960
|
+
return { verdict: 'invalid', key: null };
|
|
961
|
+
let known = [];
|
|
962
|
+
try {
|
|
963
|
+
known = await source.known();
|
|
964
|
+
}
|
|
965
|
+
catch {
|
|
966
|
+
known = [];
|
|
967
|
+
}
|
|
968
|
+
let mismatch = false;
|
|
969
|
+
for (const key of known) {
|
|
970
|
+
const verdict = await verifyEntitlementSignature(envelope, key);
|
|
971
|
+
if (verdict === 'valid')
|
|
972
|
+
return { verdict, key };
|
|
973
|
+
if (verdict === 'invalid')
|
|
974
|
+
mismatch = true;
|
|
975
|
+
}
|
|
976
|
+
let current;
|
|
977
|
+
try {
|
|
978
|
+
current = await source.fetchCurrent();
|
|
979
|
+
}
|
|
980
|
+
catch {
|
|
981
|
+
return { verdict: 'unverified', key: null };
|
|
982
|
+
}
|
|
983
|
+
if (current && !known.includes(current)) {
|
|
984
|
+
const verdict = await verifyEntitlementSignature(envelope, current);
|
|
985
|
+
return { verdict, key: verdict === 'valid' ? current : null };
|
|
986
|
+
}
|
|
987
|
+
return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/**
|
|
991
|
+
* The free trial an application configures on the server (`trialDays`).
|
|
992
|
+
*
|
|
993
|
+
* The server starts one clock per installation at its first license read and
|
|
994
|
+
* signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
|
|
995
|
+
* the verified license like paid access does: no start date in extension
|
|
996
|
+
* storage, nothing a device clock or a storage edit can move. Offline, the
|
|
997
|
+
* cached license answers for up to 48 hours.
|
|
998
|
+
*
|
|
999
|
+
* `trial:ending` / `trial:ended` fire once per installation and trial (the
|
|
1000
|
+
* marker is kept in the SDK's storage), and not while the user has paid
|
|
1001
|
+
* access. Render state from `getTrial()`; the events are one-time notices.
|
|
1002
|
+
*/
|
|
1003
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1004
|
+
/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
|
|
1005
|
+
const MAX_TIMER_MS$1 = DAY_MS;
|
|
1006
|
+
/** The trial as of `clock`, or null when the license carries none (or a malformed one). */
|
|
1007
|
+
function trialState(trial, clock) {
|
|
1008
|
+
if (!trial)
|
|
1009
|
+
return null;
|
|
1010
|
+
const startedAt = Date.parse(trial.startedAt);
|
|
1011
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1012
|
+
if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
|
|
1013
|
+
return null;
|
|
1014
|
+
// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
|
|
1015
|
+
const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
|
|
1016
|
+
const left = endsAt - now;
|
|
1017
|
+
return {
|
|
1018
|
+
active: left > 0 && clock.checked,
|
|
1019
|
+
startedAt: trial.startedAt,
|
|
1020
|
+
endsAt: trial.endsAt,
|
|
1021
|
+
daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
|
|
1022
|
+
requiresOnlineCheck: left > 0 && !clock.checked,
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
class TrialNotifier {
|
|
1026
|
+
constructor(options) {
|
|
1027
|
+
this.options = options;
|
|
1028
|
+
this.timer = null;
|
|
1029
|
+
this.running = false;
|
|
1030
|
+
this.pending = Promise.resolve();
|
|
1031
|
+
}
|
|
1032
|
+
start() {
|
|
1033
|
+
this.running = true;
|
|
1034
|
+
void this.evaluate();
|
|
1035
|
+
}
|
|
1036
|
+
stop() {
|
|
1037
|
+
this.running = false;
|
|
1038
|
+
this.clearTimer();
|
|
1039
|
+
}
|
|
1040
|
+
/** Checks the held license; serialized, so two refreshes never send one event twice. */
|
|
1041
|
+
evaluate() {
|
|
1042
|
+
this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
|
|
1043
|
+
return this.pending;
|
|
1044
|
+
}
|
|
1045
|
+
async check() {
|
|
1046
|
+
if (!this.running)
|
|
1047
|
+
return;
|
|
1048
|
+
this.clearTimer();
|
|
1049
|
+
const trial = this.options.getTrial();
|
|
1050
|
+
if (!trial)
|
|
1051
|
+
return;
|
|
1052
|
+
const now = this.options.now();
|
|
1053
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1054
|
+
const endingAt = endsAt - this.options.endingDays * DAY_MS;
|
|
1055
|
+
const event = trial.daysLeft === 0
|
|
1056
|
+
? 'trial:ended'
|
|
1057
|
+
: trial.active && this.options.endingDays > 0 && now >= endingAt
|
|
1058
|
+
? 'trial:ending'
|
|
1059
|
+
: null;
|
|
1060
|
+
if (event && !this.options.hasPaidAccess())
|
|
1061
|
+
await this.send(event, trial);
|
|
1062
|
+
if (!this.running || trial.daysLeft === 0)
|
|
1063
|
+
return;
|
|
1064
|
+
const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
|
|
1065
|
+
this.timer = setTimeout(() => {
|
|
1066
|
+
this.timer = null;
|
|
1067
|
+
void this.evaluate();
|
|
1068
|
+
}, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
|
|
1069
|
+
}
|
|
1070
|
+
async send(event, trial) {
|
|
1071
|
+
const id = `${trial.startedAt}|${trial.endsAt}`;
|
|
1072
|
+
const field = event === 'trial:ended' ? 'ended' : 'ending';
|
|
1073
|
+
const stored = (await this.options.storage.get(this.options.storageKey));
|
|
1074
|
+
const sent = stored && typeof stored === 'object' ? stored : {};
|
|
1075
|
+
if (sent[field] === id || !this.running)
|
|
1076
|
+
return;
|
|
1077
|
+
await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
|
|
1078
|
+
this.options.emit(event, trial);
|
|
1079
|
+
}
|
|
1080
|
+
clearTimer() {
|
|
1081
|
+
if (this.timer !== null)
|
|
1082
|
+
clearTimeout(this.timer);
|
|
1083
|
+
this.timer = null;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
807
1086
|
|
|
808
1087
|
/**
|
|
809
1088
|
* Entitlement cache + refresh.
|
|
@@ -811,13 +1090,18 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
|
|
|
811
1090
|
* The cached envelope is a cache OF the server projection, never a second
|
|
812
1091
|
* source of truth: it is verified when stored and re-verified on load (once
|
|
813
1092
|
* the project's public key is known), served without a round-trip while the
|
|
814
|
-
* TTL holds, served for
|
|
1093
|
+
* TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
|
|
815
1094
|
* locally by `expiresAt`. Background refresh polls at most every 15 minutes
|
|
816
1095
|
* and backs off exponentially on errors.
|
|
817
1096
|
*/
|
|
818
1097
|
const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
|
|
819
1098
|
const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
|
1099
|
+
/** Offline allowance when the signed license names none (older servers and caches). */
|
|
820
1100
|
const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
|
|
1101
|
+
/** Ceiling for a signed `offlineSeconds`. */
|
|
1102
|
+
const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
|
|
1103
|
+
/** `setTimeout` fires at once past this delay. */
|
|
1104
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
821
1105
|
// Allow small server/client clock skew without granting more than the signed age limit.
|
|
822
1106
|
const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
823
1107
|
const CACHE_VERSION = 1;
|
|
@@ -836,6 +1120,8 @@ class EntitlementManager {
|
|
|
836
1120
|
this.options = options;
|
|
837
1121
|
this.held = null;
|
|
838
1122
|
this.inflight = null;
|
|
1123
|
+
/** Device clock against the server's at the last license check; null within 5 minutes. */
|
|
1124
|
+
this.clockSkew = null;
|
|
839
1125
|
this.timer = null;
|
|
840
1126
|
this.refreshGeneration = 0;
|
|
841
1127
|
this.deadlineTimer = null;
|
|
@@ -877,8 +1163,10 @@ class EntitlementManager {
|
|
|
877
1163
|
envelope: JSON.parse(JSON.stringify(record.envelope)),
|
|
878
1164
|
fetchedAt: record.fetchedAt,
|
|
879
1165
|
verified: false,
|
|
1166
|
+
key: null,
|
|
880
1167
|
source: this.source === 'mock' ? 'mock' : 'cache',
|
|
881
1168
|
};
|
|
1169
|
+
this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
|
|
882
1170
|
this.lastFingerprint = this.fingerprint();
|
|
883
1171
|
return this.snapshot();
|
|
884
1172
|
}
|
|
@@ -889,8 +1177,7 @@ class EntitlementManager {
|
|
|
889
1177
|
if (this.source === 'mock')
|
|
890
1178
|
return;
|
|
891
1179
|
const held = this.held;
|
|
892
|
-
const key = await this.
|
|
893
|
-
const verdict = await verifyEntitlementSignature(held.envelope, key);
|
|
1180
|
+
const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
|
|
894
1181
|
if (held !== this.held)
|
|
895
1182
|
return;
|
|
896
1183
|
if (verdict === 'invalid') {
|
|
@@ -899,19 +1186,39 @@ class EntitlementManager {
|
|
|
899
1186
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
|
|
900
1187
|
}
|
|
901
1188
|
held.verified = verdict === 'valid';
|
|
1189
|
+
held.key = key;
|
|
902
1190
|
if (!held.verified) {
|
|
903
1191
|
throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
|
|
904
1192
|
}
|
|
905
1193
|
this.scheduleDeadline();
|
|
906
1194
|
}
|
|
1195
|
+
/** The key the held license was verified with; null when there is none or it is unverified. */
|
|
1196
|
+
get verifiedKey() {
|
|
1197
|
+
return this.held?.verified ? this.held.key : null;
|
|
1198
|
+
}
|
|
907
1199
|
getCached() {
|
|
908
1200
|
return this.held ? this.snapshot() : null;
|
|
909
1201
|
}
|
|
1202
|
+
/** The server trial in the held license; null without one, or while the license is unverified. */
|
|
1203
|
+
getTrial() {
|
|
1204
|
+
const held = this.held;
|
|
1205
|
+
if (!held || (this.source !== 'mock' && !held.verified))
|
|
1206
|
+
return null;
|
|
1207
|
+
const now = this.now();
|
|
1208
|
+
const issuedAt = Date.parse(held.envelope.payload.issuedAt);
|
|
1209
|
+
return trialState(held.envelope.payload.trial, {
|
|
1210
|
+
now,
|
|
1211
|
+
issuedAt,
|
|
1212
|
+
// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
|
|
1213
|
+
checked: this.source === 'mock' ||
|
|
1214
|
+
(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
910
1217
|
isFresh() {
|
|
911
1218
|
return (this.held !== null &&
|
|
912
1219
|
(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
|
|
913
1220
|
this.now() >= this.held.fetchedAt &&
|
|
914
|
-
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs,
|
|
1221
|
+
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
|
|
915
1222
|
}
|
|
916
1223
|
async get(options = {}) {
|
|
917
1224
|
if (!options.force && this.isFresh())
|
|
@@ -926,7 +1233,7 @@ class EntitlementManager {
|
|
|
926
1233
|
logger.debug('serving cached entitlement after refresh failure', err.code);
|
|
927
1234
|
return this.snapshot();
|
|
928
1235
|
}
|
|
929
|
-
return
|
|
1236
|
+
return this.snapshot();
|
|
930
1237
|
}
|
|
931
1238
|
}
|
|
932
1239
|
/** Fetches the projection from the backend, verifies and stores it. */
|
|
@@ -934,7 +1241,8 @@ class EntitlementManager {
|
|
|
934
1241
|
if (!this.inflight) {
|
|
935
1242
|
this.inflight = (async () => {
|
|
936
1243
|
const endUserRef = await this.options.getEndUserRef();
|
|
937
|
-
const
|
|
1244
|
+
const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
|
|
1245
|
+
const envelope = await this.options.api.getEntitlement(endUserRef, hint);
|
|
938
1246
|
return this.accept(envelope, this.source);
|
|
939
1247
|
})().finally(() => {
|
|
940
1248
|
this.inflight = null;
|
|
@@ -956,9 +1264,9 @@ class EntitlementManager {
|
|
|
956
1264
|
if (envelope.payload.endUserRef !== endUserRef) {
|
|
957
1265
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
|
|
958
1266
|
}
|
|
959
|
-
const verdict = this.source === 'mock'
|
|
960
|
-
? 'unverified'
|
|
961
|
-
: await
|
|
1267
|
+
const { verdict, key } = this.source === 'mock'
|
|
1268
|
+
? { verdict: 'unverified', key: null }
|
|
1269
|
+
: await verifyWithKeys(envelope, this.options.keys);
|
|
962
1270
|
if (verdict === 'invalid') {
|
|
963
1271
|
await this.discard();
|
|
964
1272
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
|
|
@@ -968,15 +1276,19 @@ class EntitlementManager {
|
|
|
968
1276
|
}
|
|
969
1277
|
const fetchedAt = this.now();
|
|
970
1278
|
const issuedAt = Date.parse(envelope.payload.issuedAt);
|
|
1279
|
+
// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
|
|
1280
|
+
if (this.source !== 'mock')
|
|
1281
|
+
this.measureClockSkew(fetchedAt, issuedAt);
|
|
971
1282
|
if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
|
|
972
1283
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
|
|
973
1284
|
}
|
|
974
|
-
this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
|
|
1285
|
+
this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
|
|
975
1286
|
const record = { v: CACHE_VERSION, envelope, fetchedAt };
|
|
976
1287
|
await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
|
|
977
1288
|
this.backoffMs = 0;
|
|
978
1289
|
this.scheduleDeadline();
|
|
979
1290
|
this.notifyIfChanged();
|
|
1291
|
+
this.options.onAccepted?.();
|
|
980
1292
|
return this.snapshot();
|
|
981
1293
|
}
|
|
982
1294
|
/** Drain an older installation refresh before changing identity. */
|
|
@@ -1030,7 +1342,7 @@ class EntitlementManager {
|
|
|
1030
1342
|
this.deadlineTimer = null;
|
|
1031
1343
|
this.notifyIfChanged();
|
|
1032
1344
|
this.scheduleDeadline();
|
|
1033
|
-
}, remaining);
|
|
1345
|
+
}, Math.min(remaining, MAX_TIMER_MS));
|
|
1034
1346
|
}
|
|
1035
1347
|
schedule(delayMs) {
|
|
1036
1348
|
const generation = this.refreshGeneration;
|
|
@@ -1051,14 +1363,12 @@ class EntitlementManager {
|
|
|
1051
1363
|
}
|
|
1052
1364
|
}, delayMs);
|
|
1053
1365
|
}
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
return null;
|
|
1061
|
-
}
|
|
1366
|
+
measureClockSkew(local, server) {
|
|
1367
|
+
const ms = local - server;
|
|
1368
|
+
this.clockSkew =
|
|
1369
|
+
Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
|
|
1370
|
+
? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
|
|
1371
|
+
: null;
|
|
1062
1372
|
}
|
|
1063
1373
|
async discard() {
|
|
1064
1374
|
this.held = null;
|
|
@@ -1068,7 +1378,13 @@ class EntitlementManager {
|
|
|
1068
1378
|
}
|
|
1069
1379
|
fingerprint() {
|
|
1070
1380
|
const state = this.snapshot();
|
|
1071
|
-
return canonicalJson({
|
|
1381
|
+
return canonicalJson({
|
|
1382
|
+
items: state.items,
|
|
1383
|
+
requiresOnlineCheck: state.requiresOnlineCheck,
|
|
1384
|
+
...(state.regionalFreeUntil
|
|
1385
|
+
? { regionalFreeUntil: state.regionalFreeUntil, features: state.features }
|
|
1386
|
+
: {}),
|
|
1387
|
+
});
|
|
1072
1388
|
}
|
|
1073
1389
|
notifyIfChanged() {
|
|
1074
1390
|
const fingerprint = this.fingerprint();
|
|
@@ -1081,16 +1397,31 @@ class EntitlementManager {
|
|
|
1081
1397
|
if (!this.held)
|
|
1082
1398
|
return NaN;
|
|
1083
1399
|
// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
|
|
1084
|
-
return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) +
|
|
1400
|
+
return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
|
|
1401
|
+
}
|
|
1402
|
+
/** The signed allowance of the held license, or 48 hours when it names none. */
|
|
1403
|
+
offlineAgeMs() {
|
|
1404
|
+
const seconds = this.held?.envelope.payload.offlineSeconds;
|
|
1405
|
+
if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
|
|
1406
|
+
return MAX_OFFLINE_AGE_MS;
|
|
1407
|
+
return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
|
|
1085
1408
|
}
|
|
1086
1409
|
snapshot() {
|
|
1087
1410
|
if (!this.held)
|
|
1088
|
-
return EMPTY_ENTITLEMENT;
|
|
1411
|
+
return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
|
|
1089
1412
|
if (this.source !== 'mock' && !this.held.verified) {
|
|
1090
|
-
return {
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1413
|
+
return {
|
|
1414
|
+
...EMPTY_ENTITLEMENT,
|
|
1415
|
+
requiresOnlineCheck: true,
|
|
1416
|
+
clockSkew: this.clockSkew,
|
|
1417
|
+
source: this.held.source,
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
const grants = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
|
|
1421
|
+
const regional = grants.find((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU && grant.status === 'active');
|
|
1422
|
+
const items = grants.filter((grant) => grant.sku !== PAY_REGIONAL_ACCESS_SKU);
|
|
1423
|
+
const hasPaidAccess = grants.some((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU) ||
|
|
1424
|
+
collectFeatures(items).length > 0 ||
|
|
1094
1425
|
items.some((item) => item.status === 'active' || item.status === 'grace');
|
|
1095
1426
|
const offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline();
|
|
1096
1427
|
const requiresOnlineCheck = offlineUntil !== null &&
|
|
@@ -1100,9 +1431,13 @@ class EntitlementManager {
|
|
|
1100
1431
|
this.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt));
|
|
1101
1432
|
return {
|
|
1102
1433
|
items,
|
|
1103
|
-
features: requiresOnlineCheck ? [] : collectFeatures(
|
|
1434
|
+
features: requiresOnlineCheck ? [] : collectFeatures(grants),
|
|
1435
|
+
...(regional?.expiresAt && !requiresOnlineCheck
|
|
1436
|
+
? { regionalFreeUntil: Date.parse(regional.expiresAt) }
|
|
1437
|
+
: {}),
|
|
1104
1438
|
requiresOnlineCheck,
|
|
1105
1439
|
offlineUntil,
|
|
1440
|
+
clockSkew: this.clockSkew,
|
|
1106
1441
|
verified: this.held.verified,
|
|
1107
1442
|
issuedAt: this.held.envelope.payload.issuedAt,
|
|
1108
1443
|
fetchedAt: this.held.fetchedAt,
|
|
@@ -1191,6 +1526,16 @@ class MemoryStorage {
|
|
|
1191
1526
|
this.map.delete(key);
|
|
1192
1527
|
}
|
|
1193
1528
|
}
|
|
1529
|
+
/**
|
|
1530
|
+
* The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
|
|
1531
|
+
* only the trial start there (never `endUserRef`), so devices on one synced account share the
|
|
1532
|
+
* trial. Uninstalling clears it from the account, so it does not survive a reinstall.
|
|
1533
|
+
*/
|
|
1534
|
+
function createSyncStorage() {
|
|
1535
|
+
const g = extensionGlobals();
|
|
1536
|
+
const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
|
|
1537
|
+
return area ? new ExtensionStorage(area) : null;
|
|
1538
|
+
}
|
|
1194
1539
|
function createStorage() {
|
|
1195
1540
|
const g = extensionGlobals();
|
|
1196
1541
|
const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
|
|
@@ -1247,7 +1592,7 @@ class RecoveryManager {
|
|
|
1247
1592
|
const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1248
1593
|
const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
|
|
1249
1594
|
const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1250
|
-
const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
|
|
1595
|
+
const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
|
|
1251
1596
|
if (!Number.isFinite(Date.parse(created.expiresAt)))
|
|
1252
1597
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
|
|
1253
1598
|
const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
|
|
@@ -1307,8 +1652,9 @@ class RecoveryManager {
|
|
|
1307
1652
|
break;
|
|
1308
1653
|
if (claim.state === 'complete') {
|
|
1309
1654
|
const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
|
|
1655
|
+
const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
|
|
1310
1656
|
await this.options.storage.remove(this.pendingKey);
|
|
1311
|
-
return { state: 'complete', entitlement };
|
|
1657
|
+
return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
|
|
1312
1658
|
}
|
|
1313
1659
|
if (claim.state !== 'pending')
|
|
1314
1660
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
|
|
@@ -1454,11 +1800,12 @@ function withdrawalWaiverText(serverVersion, locale, seller) {
|
|
|
1454
1800
|
}
|
|
1455
1801
|
|
|
1456
1802
|
/** Kept in sync with package.json by tests/unit/version.test.ts. */
|
|
1457
|
-
const VERSION = '0.
|
|
1803
|
+
const VERSION = '0.12.0';
|
|
1458
1804
|
|
|
1459
1805
|
const DEFAULT_API_URL = 'https://bff.extenshi.io';
|
|
1460
1806
|
const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
1461
1807
|
const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1808
|
+
const DEFAULT_TRIAL_ENDING_DAYS = 2;
|
|
1462
1809
|
|
|
1463
1810
|
const ENVIRONMENTS = new Set(['production', 'sandbox', 'development']);
|
|
1464
1811
|
const LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug']);
|
|
@@ -1486,7 +1833,7 @@ function resolveConfig(input) {
|
|
|
1486
1833
|
if (!isHttpUrl(apiUrl))
|
|
1487
1834
|
errors.push('apiUrl must be an http(s) URL');
|
|
1488
1835
|
const entitlementPublicKey = input.entitlementPublicKey ?? null;
|
|
1489
|
-
if (entitlementPublicKey !== null &&
|
|
1836
|
+
if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
|
|
1490
1837
|
errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
|
|
1491
1838
|
}
|
|
1492
1839
|
const environment = input.environment ?? 'production';
|
|
@@ -1508,6 +1855,9 @@ function resolveConfig(input) {
|
|
|
1508
1855
|
const theme = input.theme ?? {};
|
|
1509
1856
|
if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
|
|
1510
1857
|
errors.push('theme.mode must be light, dark or auto');
|
|
1858
|
+
const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
|
|
1859
|
+
if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
|
|
1860
|
+
errors.push('trialEndingDays must be a whole number of days between 0 and 365');
|
|
1511
1861
|
if (input.mock &&
|
|
1512
1862
|
input.mockData !== undefined &&
|
|
1513
1863
|
(typeof input.mockData !== 'object' || input.mockData === null)) {
|
|
@@ -1528,6 +1878,8 @@ function resolveConfig(input) {
|
|
|
1528
1878
|
mock: input.mock === true,
|
|
1529
1879
|
mockData: input.mock ? (input.mockData ?? {}) : null,
|
|
1530
1880
|
theme,
|
|
1881
|
+
trialEndingDays,
|
|
1882
|
+
syncTrialStart: input.syncTrialStart !== false,
|
|
1531
1883
|
};
|
|
1532
1884
|
}
|
|
1533
1885
|
|
|
@@ -1579,8 +1931,10 @@ class EventEmitter {
|
|
|
1579
1931
|
* extends it with `getOffer()` / `showPaywall()`.
|
|
1580
1932
|
*
|
|
1581
1933
|
* Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
|
|
1582
|
-
* `locale
|
|
1583
|
-
*
|
|
1934
|
+
* `locale`, checkout session IDs and, with a server trial, the trial start date
|
|
1935
|
+
* the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
|
|
1936
|
+
* challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
|
|
1937
|
+
* storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
|
|
1584
1938
|
*/
|
|
1585
1939
|
/** Server-side offer cache is 5 min; mirror it in memory. */
|
|
1586
1940
|
const OFFER_TTL_MS = 5 * 60 * 1000;
|
|
@@ -1591,12 +1945,30 @@ class ExtenshiPayLite {
|
|
|
1591
1945
|
this.endUserRefPromise = null;
|
|
1592
1946
|
this.offer = null;
|
|
1593
1947
|
this.offerInflight = null;
|
|
1948
|
+
/** The signing key the server returned in this session; never one read from storage. */
|
|
1949
|
+
this.serverKey = null;
|
|
1950
|
+
/** Trust order for license signatures; see payment/signature.ts. */
|
|
1951
|
+
this.keys = {
|
|
1952
|
+
known: async () => {
|
|
1953
|
+
const pinned = this.config.entitlementPublicKey;
|
|
1954
|
+
const offline = pinned ?? (await this.readSavedServerKey());
|
|
1955
|
+
return [...new Set([this.serverKey, offline].filter((key) => !!key))];
|
|
1956
|
+
},
|
|
1957
|
+
fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
|
|
1958
|
+
};
|
|
1594
1959
|
this.readyPromise = null;
|
|
1595
1960
|
this.destroyed = false;
|
|
1596
1961
|
this.config = resolveConfig(config);
|
|
1597
1962
|
logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
|
|
1598
1963
|
this.now = deps.now ?? (() => Date.now());
|
|
1599
1964
|
this.storage = deps.storage ?? createStorage();
|
|
1965
|
+
this.openUrl = deps.openUrl;
|
|
1966
|
+
this.syncStorage =
|
|
1967
|
+
!this.config.syncTrialStart || this.config.mock
|
|
1968
|
+
? null
|
|
1969
|
+
: deps.syncStorage === undefined
|
|
1970
|
+
? createSyncStorage()
|
|
1971
|
+
: deps.syncStorage;
|
|
1600
1972
|
const transport = deps.transport ??
|
|
1601
1973
|
(this.config.mock
|
|
1602
1974
|
? new MockTransport(this.config.mockData ?? {})
|
|
@@ -1609,11 +1981,29 @@ class ExtenshiPayLite {
|
|
|
1609
1981
|
cacheTtlMs: this.config.cacheTtlMs,
|
|
1610
1982
|
source: this.config.mock ? 'mock' : 'network',
|
|
1611
1983
|
getEndUserRef: () => this.getEndUserRef(),
|
|
1612
|
-
|
|
1984
|
+
keys: this.keys,
|
|
1613
1985
|
onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
|
|
1986
|
+
onAccepted: () => {
|
|
1987
|
+
void this.trial.evaluate();
|
|
1988
|
+
void this.rememberTrialStart();
|
|
1989
|
+
},
|
|
1990
|
+
getTrialStartHint: () => this.readTrialStartHint(),
|
|
1614
1991
|
onError: (error) => this.reportError(error),
|
|
1615
1992
|
now: this.now,
|
|
1616
1993
|
});
|
|
1994
|
+
this.trial = new TrialNotifier({
|
|
1995
|
+
storage: this.storage,
|
|
1996
|
+
storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
|
|
1997
|
+
endingDays: this.config.trialEndingDays,
|
|
1998
|
+
getTrial: () => this.entitlements.getTrial(),
|
|
1999
|
+
// A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
|
|
2000
|
+
hasPaidAccess: () => {
|
|
2001
|
+
const license = this.entitlements.getCached();
|
|
2002
|
+
return Boolean(license?.regionalFreeUntil || license?.items.some(isLive));
|
|
2003
|
+
},
|
|
2004
|
+
emit: (event, trial) => this.emitter.emit(event, trial),
|
|
2005
|
+
now: this.now,
|
|
2006
|
+
});
|
|
1617
2007
|
this.checkout = new CheckoutManager({
|
|
1618
2008
|
api: this.api,
|
|
1619
2009
|
storage: this.storage,
|
|
@@ -1627,6 +2017,13 @@ class ExtenshiPayLite {
|
|
|
1627
2017
|
(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
|
|
1628
2018
|
now: this.now,
|
|
1629
2019
|
});
|
|
2020
|
+
this.backup = new CloudBackup({
|
|
2021
|
+
storage: this.storage,
|
|
2022
|
+
publishableKey: this.config.publishableKey,
|
|
2023
|
+
apiUrl: this.config.apiUrl,
|
|
2024
|
+
fetch: deps.fetch,
|
|
2025
|
+
mock: this.config.mock,
|
|
2026
|
+
});
|
|
1630
2027
|
this.recovery = new RecoveryManager({
|
|
1631
2028
|
api: this.api,
|
|
1632
2029
|
locale: this.config.locale,
|
|
@@ -1640,7 +2037,7 @@ class ExtenshiPayLite {
|
|
|
1640
2037
|
envelope.payload.publishableKey !== this.config.publishableKey ||
|
|
1641
2038
|
!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
|
|
1642
2039
|
Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
|
|
1643
|
-
(await
|
|
2040
|
+
(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
|
|
1644
2041
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
|
|
1645
2042
|
this.entitlements.stopAutoRefresh();
|
|
1646
2043
|
try {
|
|
@@ -1658,6 +2055,7 @@ class ExtenshiPayLite {
|
|
|
1658
2055
|
this.entitlements.startAutoRefresh();
|
|
1659
2056
|
}
|
|
1660
2057
|
},
|
|
2058
|
+
onStorageGrant: (grant) => this.backup.accept(grant),
|
|
1661
2059
|
});
|
|
1662
2060
|
if (config.onError)
|
|
1663
2061
|
this.emitter.on('error', config.onError);
|
|
@@ -1703,8 +2101,11 @@ class ExtenshiPayLite {
|
|
|
1703
2101
|
catch (error) {
|
|
1704
2102
|
this.reportError(error);
|
|
1705
2103
|
}
|
|
1706
|
-
|
|
2104
|
+
void this.confirmSavedServerKey();
|
|
2105
|
+
if (!this.destroyed) {
|
|
1707
2106
|
this.entitlements.startAutoRefresh();
|
|
2107
|
+
this.trial.start();
|
|
2108
|
+
}
|
|
1708
2109
|
}
|
|
1709
2110
|
/** The anonymous, random id this install is known by. */
|
|
1710
2111
|
getEndUserRef() {
|
|
@@ -1725,6 +2126,16 @@ class ExtenshiPayLite {
|
|
|
1725
2126
|
await this.initialize();
|
|
1726
2127
|
return this.entitlements.get(options);
|
|
1727
2128
|
}
|
|
2129
|
+
/**
|
|
2130
|
+
* The free trial the application set on the server, from the verified license, or null when
|
|
2131
|
+
* there is none (or the license could not be verified yet). Answers offline from the cached
|
|
2132
|
+
* license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
|
|
2133
|
+
* `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
|
|
2134
|
+
*/
|
|
2135
|
+
async getTrial(options = {}) {
|
|
2136
|
+
await this.getEntitlement(options);
|
|
2137
|
+
return this.entitlements.getTrial();
|
|
2138
|
+
}
|
|
1728
2139
|
/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
|
|
1729
2140
|
async isPaid(sku) {
|
|
1730
2141
|
return isEntitled(await this.getEntitlement(), sku);
|
|
@@ -1808,6 +2219,41 @@ class ExtenshiPayLite {
|
|
|
1808
2219
|
throw this.reportError(error);
|
|
1809
2220
|
}
|
|
1810
2221
|
}
|
|
2222
|
+
/**
|
|
2223
|
+
* Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
|
|
2224
|
+
* hosted restore page shows the storage disclosure and the buyer confirms with
|
|
2225
|
+
* the code from the purchase email. `cloudBackup` in the result says whether it is
|
|
2226
|
+
* on. Buyers only; consent is recorded by the server.
|
|
2227
|
+
*/
|
|
2228
|
+
enableCloudBackup(options = {}) {
|
|
2229
|
+
return this.restorePurchase({ ...options, purpose: 'storage' });
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
|
|
2233
|
+
* while cloud backup is off on this installation. Extension pages and background
|
|
2234
|
+
* only: it rejects in a content script, and must never be sent to one.
|
|
2235
|
+
*/
|
|
2236
|
+
async cloudBackupToken() {
|
|
2237
|
+
return this.backup.token();
|
|
2238
|
+
}
|
|
2239
|
+
/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
|
|
2240
|
+
async disableCloudBackup() {
|
|
2241
|
+
try {
|
|
2242
|
+
await this.backup.disable();
|
|
2243
|
+
}
|
|
2244
|
+
catch (error) {
|
|
2245
|
+
throw this.reportError(error);
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
|
|
2249
|
+
async deleteCloudBackup() {
|
|
2250
|
+
try {
|
|
2251
|
+
await this.backup.delete();
|
|
2252
|
+
}
|
|
2253
|
+
catch (error) {
|
|
2254
|
+
throw this.reportError(error);
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
1811
2257
|
/** Read-only license view. Entitlements retain cache/signature/offline semantics. */
|
|
1812
2258
|
async getLicenseSummary(options = {}) {
|
|
1813
2259
|
await this.initialize();
|
|
@@ -1877,6 +2323,7 @@ class ExtenshiPayLite {
|
|
|
1877
2323
|
destroy() {
|
|
1878
2324
|
this.destroyed = true;
|
|
1879
2325
|
this.recovery.stop();
|
|
2326
|
+
this.trial.stop();
|
|
1880
2327
|
this.entitlements.stopAutoRefresh();
|
|
1881
2328
|
this.emitter.removeAll();
|
|
1882
2329
|
}
|
|
@@ -1888,8 +2335,9 @@ class ExtenshiPayLite {
|
|
|
1888
2335
|
if (!this.offerInflight) {
|
|
1889
2336
|
this.offerInflight = this.api
|
|
1890
2337
|
.getOffer(this.config.locale)
|
|
1891
|
-
.then((value) => {
|
|
2338
|
+
.then(async (value) => {
|
|
1892
2339
|
this.offer = { value, fetchedAt: this.now() };
|
|
2340
|
+
await this.rememberServerKey(value.entitlementPublicKey);
|
|
1893
2341
|
return value;
|
|
1894
2342
|
})
|
|
1895
2343
|
.finally(() => {
|
|
@@ -1898,8 +2346,88 @@ class ExtenshiPayLite {
|
|
|
1898
2346
|
}
|
|
1899
2347
|
return this.offerInflight;
|
|
1900
2348
|
}
|
|
1901
|
-
|
|
1902
|
-
return this.config.entitlementPublicKey
|
|
2349
|
+
get serverKeyStorageKey() {
|
|
2350
|
+
return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
|
|
2351
|
+
}
|
|
2352
|
+
async readSavedServerKey() {
|
|
2353
|
+
try {
|
|
2354
|
+
const value = await this.storage.get(this.serverKeyStorageKey);
|
|
2355
|
+
return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
|
|
2356
|
+
}
|
|
2357
|
+
catch {
|
|
2358
|
+
return null;
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
/**
|
|
2362
|
+
* Keeps the server's key next to the license cache so a restart with no network can verify it.
|
|
2363
|
+
* Not with a bundled key: that one already covers the restart, and storage stays untrusted.
|
|
2364
|
+
*/
|
|
2365
|
+
async rememberServerKey(key) {
|
|
2366
|
+
if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
|
|
2367
|
+
return;
|
|
2368
|
+
this.serverKey = key;
|
|
2369
|
+
if (this.config.entitlementPublicKey || this.config.mock)
|
|
2370
|
+
return;
|
|
2371
|
+
try {
|
|
2372
|
+
if ((await this.readSavedServerKey()) !== key)
|
|
2373
|
+
await this.storage.set(this.serverKeyStorageKey, key);
|
|
2374
|
+
}
|
|
2375
|
+
catch (error) {
|
|
2376
|
+
logger.debug('signing key not saved', error);
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* A license verified with the saved key alone is checked against the server once per start:
|
|
2381
|
+
* when the server's key differs (rotation, or an edited storage) the license is fetched again,
|
|
2382
|
+
* and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
|
|
2383
|
+
*/
|
|
2384
|
+
async confirmSavedServerKey() {
|
|
2385
|
+
const used = this.entitlements.verifiedKey;
|
|
2386
|
+
if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
|
|
2387
|
+
return;
|
|
2388
|
+
try {
|
|
2389
|
+
if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
|
|
2390
|
+
return;
|
|
2391
|
+
}
|
|
2392
|
+
catch {
|
|
2393
|
+
return;
|
|
2394
|
+
}
|
|
2395
|
+
try {
|
|
2396
|
+
await this.entitlements.refresh();
|
|
2397
|
+
}
|
|
2398
|
+
catch {
|
|
2399
|
+
await this.entitlements.reverify().catch((error) => this.reportError(error));
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
get trialStartKey() {
|
|
2403
|
+
return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
|
|
2404
|
+
}
|
|
2405
|
+
/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
|
|
2406
|
+
async readTrialStartHint() {
|
|
2407
|
+
if (!this.syncStorage)
|
|
2408
|
+
return null;
|
|
2409
|
+
try {
|
|
2410
|
+
const value = await this.syncStorage.get(this.trialStartKey);
|
|
2411
|
+
return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
|
|
2412
|
+
}
|
|
2413
|
+
catch {
|
|
2414
|
+
return null;
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
|
|
2418
|
+
async rememberTrialStart() {
|
|
2419
|
+
const trial = this.entitlements.getTrial();
|
|
2420
|
+
if (!this.syncStorage || !trial)
|
|
2421
|
+
return;
|
|
2422
|
+
try {
|
|
2423
|
+
const synced = await this.readTrialStartHint();
|
|
2424
|
+
if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
|
|
2425
|
+
return;
|
|
2426
|
+
await this.syncStorage.set(this.trialStartKey, trial.startedAt);
|
|
2427
|
+
}
|
|
2428
|
+
catch (error) {
|
|
2429
|
+
logger.debug('trial start not synced', error);
|
|
2430
|
+
}
|
|
1903
2431
|
}
|
|
1904
2432
|
reportError(error) {
|
|
1905
2433
|
const err = ExtenshiPayError.from(error);
|