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