@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
package/dist/core.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* ExtenshiPay SDK v0.
|
|
2
|
+
* ExtenshiPay SDK v0.11.0
|
|
3
3
|
* (c) 2026 Extenshi.io
|
|
4
4
|
* Released under the MIT License.
|
|
5
|
-
* commit
|
|
5
|
+
* commit ed0f776ae9ab7ce6b2c614dbdfe696e9007b0d05 · built by `rollup -c`
|
|
6
6
|
*/
|
|
7
7
|
(function (global, factory) {
|
|
8
8
|
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
|
@@ -92,6 +92,14 @@
|
|
|
92
92
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
93
93
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* `storage`: the buyer turns on the cloud copy of the extension's settings. The
|
|
97
|
+
* hosted page shows the storage disclosure; the claim records consent. Additive:
|
|
98
|
+
* a session without a purpose is a plain restore.
|
|
99
|
+
*/
|
|
100
|
+
const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
|
|
101
|
+
/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
|
|
102
|
+
const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
|
|
95
103
|
|
|
96
104
|
const ERROR_CODES = {
|
|
97
105
|
INVALID_CONFIG: 'INVALID_CONFIG',
|
|
@@ -163,7 +171,7 @@
|
|
|
163
171
|
* developed with no backend: offers and entitlements come from `mockData`, a
|
|
164
172
|
* mock checkout completes after `claimAfterPolls` polls and grants the SKU.
|
|
165
173
|
*/
|
|
166
|
-
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
174
|
+
const DAY_MS$1 = 24 * 60 * 60 * 1000;
|
|
167
175
|
/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
|
|
168
176
|
function mockConsent(value) {
|
|
169
177
|
const consent = value;
|
|
@@ -181,6 +189,10 @@
|
|
|
181
189
|
this.claimAfterPolls = data.claimAfterPolls ?? 1;
|
|
182
190
|
this.withdrawalWaiver =
|
|
183
191
|
data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
|
|
192
|
+
this.seller = data.seller;
|
|
193
|
+
this.trial = null;
|
|
194
|
+
if (data.trial)
|
|
195
|
+
this.setTrial(data.trial.days, data.trial.startedAt);
|
|
184
196
|
}
|
|
185
197
|
async call(procedure, _kind, input) {
|
|
186
198
|
switch (procedure) {
|
|
@@ -202,6 +214,14 @@
|
|
|
202
214
|
setEntitlements(items) {
|
|
203
215
|
this.entitlements = [...items];
|
|
204
216
|
}
|
|
217
|
+
/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
|
|
218
|
+
setTrial(days, startedAt = new Date().toISOString()) {
|
|
219
|
+
const start = Date.parse(startedAt);
|
|
220
|
+
this.trial =
|
|
221
|
+
days === null || !Number.isFinite(start)
|
|
222
|
+
? null
|
|
223
|
+
: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
|
|
224
|
+
}
|
|
205
225
|
cancelSession(sessionId) {
|
|
206
226
|
const session = this.sessions.get(sessionId);
|
|
207
227
|
if (session)
|
|
@@ -221,6 +241,7 @@
|
|
|
221
241
|
offers: [...this.offers],
|
|
222
242
|
entitlementPublicKey: null,
|
|
223
243
|
withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
|
|
244
|
+
...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
|
|
224
245
|
};
|
|
225
246
|
}
|
|
226
247
|
createCheckout(sku, withdrawalWaiver) {
|
|
@@ -258,7 +279,7 @@
|
|
|
258
279
|
grant(sku) {
|
|
259
280
|
const offer = this.offers.find((o) => o.sku === sku);
|
|
260
281
|
const expiresAt = offer?.kind === 'subscription'
|
|
261
|
-
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
|
|
282
|
+
? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
|
|
262
283
|
: null;
|
|
263
284
|
this.entitlements = [
|
|
264
285
|
...this.entitlements.filter((item) => item.sku !== sku),
|
|
@@ -280,6 +301,7 @@
|
|
|
280
301
|
endUserRef,
|
|
281
302
|
entitlements: [...this.entitlements],
|
|
282
303
|
issuedAt: new Date().toISOString(),
|
|
304
|
+
...(this.trial ? { trial: { ...this.trial } } : {}),
|
|
283
305
|
},
|
|
284
306
|
signature: null,
|
|
285
307
|
alg: null,
|
|
@@ -293,12 +315,17 @@
|
|
|
293
315
|
this.transport = transport;
|
|
294
316
|
this.publishableKey = publishableKey;
|
|
295
317
|
}
|
|
296
|
-
/**
|
|
297
|
-
|
|
318
|
+
/**
|
|
319
|
+
* `locale` opens the hosted recovery page (and its email) in the user's language.
|
|
320
|
+
* `purpose` is sent only for `storage`: a plain restore keeps the request older
|
|
321
|
+
* BFFs know, and their non-strict zod input strips the key anyway.
|
|
322
|
+
*/
|
|
323
|
+
createRestoreSession(claimChallenge, locale, purpose) {
|
|
298
324
|
return this.transport.call('pay.createRestoreSession', 'mutation', {
|
|
299
325
|
publishableKey: this.publishableKey,
|
|
300
326
|
claimChallenge,
|
|
301
327
|
...(locale ? { locale } : {}),
|
|
328
|
+
...(purpose === 'storage' ? { purpose } : {}),
|
|
302
329
|
});
|
|
303
330
|
}
|
|
304
331
|
claimRestoreSession(sessionId, claimSecret) {
|
|
@@ -337,10 +364,12 @@
|
|
|
337
364
|
endUserRef,
|
|
338
365
|
});
|
|
339
366
|
}
|
|
340
|
-
|
|
367
|
+
/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
|
|
368
|
+
getEntitlement(endUserRef, trialStartedHint) {
|
|
341
369
|
return this.transport.call('pay.getEntitlement', 'query', {
|
|
342
370
|
publishableKey: this.publishableKey,
|
|
343
371
|
endUserRef,
|
|
372
|
+
...(trialStartedHint ? { trialStartedHint } : {}),
|
|
344
373
|
});
|
|
345
374
|
}
|
|
346
375
|
getPortalUrl(endUserRef, customerId, locale) {
|
|
@@ -738,6 +767,118 @@
|
|
|
738
767
|
openInNewTab: openInNewTab
|
|
739
768
|
});
|
|
740
769
|
|
|
770
|
+
/**
|
|
771
|
+
* Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
|
|
772
|
+
* token: only a verified restore claim issues it; this module keeps it in the
|
|
773
|
+
* SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
|
|
774
|
+
* through `cloudBackupToken()`. The token is never logged and never answered to
|
|
775
|
+
* a content script: route those calls to the background.
|
|
776
|
+
*/
|
|
777
|
+
const REQUEST_TIMEOUT_MS = 10000;
|
|
778
|
+
/** True in a content script, where the token must not be handed out. */
|
|
779
|
+
function inContentScript() {
|
|
780
|
+
const g = globalThis;
|
|
781
|
+
return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
|
|
782
|
+
}
|
|
783
|
+
class CloudBackup {
|
|
784
|
+
constructor(options) {
|
|
785
|
+
this.options = options;
|
|
786
|
+
this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
787
|
+
}
|
|
788
|
+
get storageKey() {
|
|
789
|
+
return `extenshi-pay:${this.options.publishableKey}:storageToken`;
|
|
790
|
+
}
|
|
791
|
+
/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
|
|
792
|
+
async accept(grant) {
|
|
793
|
+
if (!grant || typeof grant !== 'object')
|
|
794
|
+
return undefined;
|
|
795
|
+
try {
|
|
796
|
+
if (grant.state === 'granted') {
|
|
797
|
+
if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
|
|
798
|
+
return undefined;
|
|
799
|
+
await this.options.storage.set(this.storageKey, grant.token);
|
|
800
|
+
return 'on';
|
|
801
|
+
}
|
|
802
|
+
if (grant.state === 'unavailable') {
|
|
803
|
+
await this.options.storage.remove(this.storageKey);
|
|
804
|
+
return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
catch {
|
|
808
|
+
logger.warn('cloud backup state could not be saved');
|
|
809
|
+
}
|
|
810
|
+
return undefined;
|
|
811
|
+
}
|
|
812
|
+
async token() {
|
|
813
|
+
this.assertTrustedContext();
|
|
814
|
+
const value = await this.options.storage.get(this.storageKey);
|
|
815
|
+
return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
|
|
816
|
+
}
|
|
817
|
+
/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
|
|
818
|
+
async disable() {
|
|
819
|
+
const token = await this.token();
|
|
820
|
+
if (!token)
|
|
821
|
+
return;
|
|
822
|
+
if (!this.options.mock) {
|
|
823
|
+
const status = await this.request('/v1/storage/grant', token);
|
|
824
|
+
if (status !== 401)
|
|
825
|
+
this.throwUnlessOk(status);
|
|
826
|
+
}
|
|
827
|
+
await this.options.storage.remove(this.storageKey);
|
|
828
|
+
}
|
|
829
|
+
/** Deletes the buyer's cloud copy and turns the backup off on every device. */
|
|
830
|
+
async delete() {
|
|
831
|
+
const token = await this.token();
|
|
832
|
+
if (!token)
|
|
833
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
|
|
834
|
+
if (!this.options.mock) {
|
|
835
|
+
const status = await this.request('/v1/storage/data', token);
|
|
836
|
+
if (status === 401) {
|
|
837
|
+
// The server no longer accepts this token, so it is useless here; the copy was not deleted.
|
|
838
|
+
await this.options.storage.remove(this.storageKey);
|
|
839
|
+
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 });
|
|
840
|
+
}
|
|
841
|
+
this.throwUnlessOk(status);
|
|
842
|
+
}
|
|
843
|
+
await this.options.storage.remove(this.storageKey);
|
|
844
|
+
}
|
|
845
|
+
assertTrustedContext() {
|
|
846
|
+
if (inContentScript())
|
|
847
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
|
|
848
|
+
}
|
|
849
|
+
throwUnlessOk(status) {
|
|
850
|
+
if (status >= 200 && status < 300)
|
|
851
|
+
return;
|
|
852
|
+
if (status === 429)
|
|
853
|
+
throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
|
|
854
|
+
if (status >= 500)
|
|
855
|
+
throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
|
|
856
|
+
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
|
|
857
|
+
}
|
|
858
|
+
async request(path, token) {
|
|
859
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
860
|
+
const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
|
|
861
|
+
try {
|
|
862
|
+
const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
|
|
863
|
+
method: 'DELETE',
|
|
864
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
865
|
+
credentials: 'omit',
|
|
866
|
+
signal: controller?.signal,
|
|
867
|
+
});
|
|
868
|
+
return response.status;
|
|
869
|
+
}
|
|
870
|
+
catch (error) {
|
|
871
|
+
if (controller?.signal.aborted)
|
|
872
|
+
throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
|
|
873
|
+
throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
|
|
874
|
+
}
|
|
875
|
+
finally {
|
|
876
|
+
if (timer !== null)
|
|
877
|
+
clearTimeout(timer);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
741
882
|
/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
|
|
742
883
|
const LIVE_STATUSES = new Set(['active', 'grace']);
|
|
743
884
|
function isLive(item) {
|
|
@@ -792,9 +933,17 @@
|
|
|
792
933
|
/**
|
|
793
934
|
* Ed25519 verification of the entitlement projection.
|
|
794
935
|
*
|
|
795
|
-
* Tamper resistance, not DRM.
|
|
796
|
-
*
|
|
797
|
-
*
|
|
936
|
+
* Tamper resistance, not DRM. Callers must deny access for both invalid and
|
|
937
|
+
* unverified envelopes outside explicit mocks.
|
|
938
|
+
*
|
|
939
|
+
* Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
|
|
940
|
+
* 1. the key the server returned over HTTPS in this session;
|
|
941
|
+
* 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
|
|
942
|
+
* verification without a round-trip: a key read from extension storage is then never used;
|
|
943
|
+
* 3. without a bundled key, the server key saved in `storage.local` next to the
|
|
944
|
+
* license cache, so a restart with no network can still verify the cache.
|
|
945
|
+
* When none of them verifies an envelope the server is asked for its current key once
|
|
946
|
+
* (a rotated key), and that answer decides.
|
|
798
947
|
*/
|
|
799
948
|
function base64ToBytes(base64) {
|
|
800
949
|
const binary = atob(base64);
|
|
@@ -829,6 +978,140 @@
|
|
|
829
978
|
return 'invalid';
|
|
830
979
|
}
|
|
831
980
|
}
|
|
981
|
+
const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
982
|
+
/**
|
|
983
|
+
* `invalid` only when the server's current key was checked too (or the envelope carries no
|
|
984
|
+
* signature at all). A mismatch against known keys while the server is unreachable is
|
|
985
|
+
* `unverified`: it may be a rotated key, and no paid access is granted either way.
|
|
986
|
+
*/
|
|
987
|
+
async function verifyWithKeys(envelope, source) {
|
|
988
|
+
if (!envelope.signature || envelope.alg !== 'ed25519')
|
|
989
|
+
return { verdict: 'invalid', key: null };
|
|
990
|
+
let known = [];
|
|
991
|
+
try {
|
|
992
|
+
known = await source.known();
|
|
993
|
+
}
|
|
994
|
+
catch {
|
|
995
|
+
known = [];
|
|
996
|
+
}
|
|
997
|
+
let mismatch = false;
|
|
998
|
+
for (const key of known) {
|
|
999
|
+
const verdict = await verifyEntitlementSignature(envelope, key);
|
|
1000
|
+
if (verdict === 'valid')
|
|
1001
|
+
return { verdict, key };
|
|
1002
|
+
if (verdict === 'invalid')
|
|
1003
|
+
mismatch = true;
|
|
1004
|
+
}
|
|
1005
|
+
let current;
|
|
1006
|
+
try {
|
|
1007
|
+
current = await source.fetchCurrent();
|
|
1008
|
+
}
|
|
1009
|
+
catch {
|
|
1010
|
+
return { verdict: 'unverified', key: null };
|
|
1011
|
+
}
|
|
1012
|
+
if (current && !known.includes(current)) {
|
|
1013
|
+
const verdict = await verifyEntitlementSignature(envelope, current);
|
|
1014
|
+
return { verdict, key: verdict === 'valid' ? current : null };
|
|
1015
|
+
}
|
|
1016
|
+
return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/**
|
|
1020
|
+
* The free trial an application configures on the server (`trialDays`).
|
|
1021
|
+
*
|
|
1022
|
+
* The server starts one clock per installation at its first license read and
|
|
1023
|
+
* signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
|
|
1024
|
+
* the verified license like paid access does: no start date in extension
|
|
1025
|
+
* storage, nothing a device clock or a storage edit can move. Offline, the
|
|
1026
|
+
* cached license answers for up to 48 hours.
|
|
1027
|
+
*
|
|
1028
|
+
* `trial:ending` / `trial:ended` fire once per installation and trial (the
|
|
1029
|
+
* marker is kept in the SDK's storage), and not while the user has paid
|
|
1030
|
+
* access. Render state from `getTrial()`; the events are one-time notices.
|
|
1031
|
+
*/
|
|
1032
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
1033
|
+
/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
|
|
1034
|
+
const MAX_TIMER_MS$1 = DAY_MS;
|
|
1035
|
+
/** The trial as of `clock`, or null when the license carries none (or a malformed one). */
|
|
1036
|
+
function trialState(trial, clock) {
|
|
1037
|
+
if (!trial)
|
|
1038
|
+
return null;
|
|
1039
|
+
const startedAt = Date.parse(trial.startedAt);
|
|
1040
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1041
|
+
if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
|
|
1042
|
+
return null;
|
|
1043
|
+
// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
|
|
1044
|
+
const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
|
|
1045
|
+
const left = endsAt - now;
|
|
1046
|
+
return {
|
|
1047
|
+
active: left > 0 && clock.checked,
|
|
1048
|
+
startedAt: trial.startedAt,
|
|
1049
|
+
endsAt: trial.endsAt,
|
|
1050
|
+
daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
|
|
1051
|
+
requiresOnlineCheck: left > 0 && !clock.checked,
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
class TrialNotifier {
|
|
1055
|
+
constructor(options) {
|
|
1056
|
+
this.options = options;
|
|
1057
|
+
this.timer = null;
|
|
1058
|
+
this.running = false;
|
|
1059
|
+
this.pending = Promise.resolve();
|
|
1060
|
+
}
|
|
1061
|
+
start() {
|
|
1062
|
+
this.running = true;
|
|
1063
|
+
void this.evaluate();
|
|
1064
|
+
}
|
|
1065
|
+
stop() {
|
|
1066
|
+
this.running = false;
|
|
1067
|
+
this.clearTimer();
|
|
1068
|
+
}
|
|
1069
|
+
/** Checks the held license; serialized, so two refreshes never send one event twice. */
|
|
1070
|
+
evaluate() {
|
|
1071
|
+
this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
|
|
1072
|
+
return this.pending;
|
|
1073
|
+
}
|
|
1074
|
+
async check() {
|
|
1075
|
+
if (!this.running)
|
|
1076
|
+
return;
|
|
1077
|
+
this.clearTimer();
|
|
1078
|
+
const trial = this.options.getTrial();
|
|
1079
|
+
if (!trial)
|
|
1080
|
+
return;
|
|
1081
|
+
const now = this.options.now();
|
|
1082
|
+
const endsAt = Date.parse(trial.endsAt);
|
|
1083
|
+
const endingAt = endsAt - this.options.endingDays * DAY_MS;
|
|
1084
|
+
const event = trial.daysLeft === 0
|
|
1085
|
+
? 'trial:ended'
|
|
1086
|
+
: trial.active && this.options.endingDays > 0 && now >= endingAt
|
|
1087
|
+
? 'trial:ending'
|
|
1088
|
+
: null;
|
|
1089
|
+
if (event && !this.options.hasPaidAccess())
|
|
1090
|
+
await this.send(event, trial);
|
|
1091
|
+
if (!this.running || trial.daysLeft === 0)
|
|
1092
|
+
return;
|
|
1093
|
+
const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
|
|
1094
|
+
this.timer = setTimeout(() => {
|
|
1095
|
+
this.timer = null;
|
|
1096
|
+
void this.evaluate();
|
|
1097
|
+
}, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
|
|
1098
|
+
}
|
|
1099
|
+
async send(event, trial) {
|
|
1100
|
+
const id = `${trial.startedAt}|${trial.endsAt}`;
|
|
1101
|
+
const field = event === 'trial:ended' ? 'ended' : 'ending';
|
|
1102
|
+
const stored = (await this.options.storage.get(this.options.storageKey));
|
|
1103
|
+
const sent = stored && typeof stored === 'object' ? stored : {};
|
|
1104
|
+
if (sent[field] === id || !this.running)
|
|
1105
|
+
return;
|
|
1106
|
+
await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
|
|
1107
|
+
this.options.emit(event, trial);
|
|
1108
|
+
}
|
|
1109
|
+
clearTimer() {
|
|
1110
|
+
if (this.timer !== null)
|
|
1111
|
+
clearTimeout(this.timer);
|
|
1112
|
+
this.timer = null;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
832
1115
|
|
|
833
1116
|
/**
|
|
834
1117
|
* Entitlement cache + refresh.
|
|
@@ -836,13 +1119,18 @@
|
|
|
836
1119
|
* The cached envelope is a cache OF the server projection, never a second
|
|
837
1120
|
* source of truth: it is verified when stored and re-verified on load (once
|
|
838
1121
|
* the project's public key is known), served without a round-trip while the
|
|
839
|
-
* TTL holds, served for
|
|
1122
|
+
* TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
|
|
840
1123
|
* locally by `expiresAt`. Background refresh polls at most every 15 minutes
|
|
841
1124
|
* and backs off exponentially on errors.
|
|
842
1125
|
*/
|
|
843
1126
|
const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
|
|
844
1127
|
const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
|
|
1128
|
+
/** Offline allowance when the signed license names none (older servers and caches). */
|
|
845
1129
|
const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
|
|
1130
|
+
/** Ceiling for a signed `offlineSeconds`. */
|
|
1131
|
+
const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
|
|
1132
|
+
/** `setTimeout` fires at once past this delay. */
|
|
1133
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
846
1134
|
// Allow small server/client clock skew without granting more than the signed age limit.
|
|
847
1135
|
const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
848
1136
|
const CACHE_VERSION = 1;
|
|
@@ -861,6 +1149,8 @@
|
|
|
861
1149
|
this.options = options;
|
|
862
1150
|
this.held = null;
|
|
863
1151
|
this.inflight = null;
|
|
1152
|
+
/** Device clock against the server's at the last license check; null within 5 minutes. */
|
|
1153
|
+
this.clockSkew = null;
|
|
864
1154
|
this.timer = null;
|
|
865
1155
|
this.refreshGeneration = 0;
|
|
866
1156
|
this.deadlineTimer = null;
|
|
@@ -902,8 +1192,10 @@
|
|
|
902
1192
|
envelope: JSON.parse(JSON.stringify(record.envelope)),
|
|
903
1193
|
fetchedAt: record.fetchedAt,
|
|
904
1194
|
verified: false,
|
|
1195
|
+
key: null,
|
|
905
1196
|
source: this.source === 'mock' ? 'mock' : 'cache',
|
|
906
1197
|
};
|
|
1198
|
+
this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
|
|
907
1199
|
this.lastFingerprint = this.fingerprint();
|
|
908
1200
|
return this.snapshot();
|
|
909
1201
|
}
|
|
@@ -914,8 +1206,7 @@
|
|
|
914
1206
|
if (this.source === 'mock')
|
|
915
1207
|
return;
|
|
916
1208
|
const held = this.held;
|
|
917
|
-
const key = await this.
|
|
918
|
-
const verdict = await verifyEntitlementSignature(held.envelope, key);
|
|
1209
|
+
const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
|
|
919
1210
|
if (held !== this.held)
|
|
920
1211
|
return;
|
|
921
1212
|
if (verdict === 'invalid') {
|
|
@@ -924,19 +1215,39 @@
|
|
|
924
1215
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
|
|
925
1216
|
}
|
|
926
1217
|
held.verified = verdict === 'valid';
|
|
1218
|
+
held.key = key;
|
|
927
1219
|
if (!held.verified) {
|
|
928
1220
|
throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
|
|
929
1221
|
}
|
|
930
1222
|
this.scheduleDeadline();
|
|
931
1223
|
}
|
|
1224
|
+
/** The key the held license was verified with; null when there is none or it is unverified. */
|
|
1225
|
+
get verifiedKey() {
|
|
1226
|
+
return this.held?.verified ? this.held.key : null;
|
|
1227
|
+
}
|
|
932
1228
|
getCached() {
|
|
933
1229
|
return this.held ? this.snapshot() : null;
|
|
934
1230
|
}
|
|
1231
|
+
/** The server trial in the held license; null without one, or while the license is unverified. */
|
|
1232
|
+
getTrial() {
|
|
1233
|
+
const held = this.held;
|
|
1234
|
+
if (!held || (this.source !== 'mock' && !held.verified))
|
|
1235
|
+
return null;
|
|
1236
|
+
const now = this.now();
|
|
1237
|
+
const issuedAt = Date.parse(held.envelope.payload.issuedAt);
|
|
1238
|
+
return trialState(held.envelope.payload.trial, {
|
|
1239
|
+
now,
|
|
1240
|
+
issuedAt,
|
|
1241
|
+
// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
|
|
1242
|
+
checked: this.source === 'mock' ||
|
|
1243
|
+
(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
935
1246
|
isFresh() {
|
|
936
1247
|
return (this.held !== null &&
|
|
937
1248
|
(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
|
|
938
1249
|
this.now() >= this.held.fetchedAt &&
|
|
939
|
-
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs,
|
|
1250
|
+
this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
|
|
940
1251
|
}
|
|
941
1252
|
async get(options = {}) {
|
|
942
1253
|
if (!options.force && this.isFresh())
|
|
@@ -951,7 +1262,7 @@
|
|
|
951
1262
|
logger.debug('serving cached entitlement after refresh failure', err.code);
|
|
952
1263
|
return this.snapshot();
|
|
953
1264
|
}
|
|
954
|
-
return
|
|
1265
|
+
return this.snapshot();
|
|
955
1266
|
}
|
|
956
1267
|
}
|
|
957
1268
|
/** Fetches the projection from the backend, verifies and stores it. */
|
|
@@ -959,7 +1270,8 @@
|
|
|
959
1270
|
if (!this.inflight) {
|
|
960
1271
|
this.inflight = (async () => {
|
|
961
1272
|
const endUserRef = await this.options.getEndUserRef();
|
|
962
|
-
const
|
|
1273
|
+
const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
|
|
1274
|
+
const envelope = await this.options.api.getEntitlement(endUserRef, hint);
|
|
963
1275
|
return this.accept(envelope, this.source);
|
|
964
1276
|
})().finally(() => {
|
|
965
1277
|
this.inflight = null;
|
|
@@ -981,9 +1293,9 @@
|
|
|
981
1293
|
if (envelope.payload.endUserRef !== endUserRef) {
|
|
982
1294
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
|
|
983
1295
|
}
|
|
984
|
-
const verdict = this.source === 'mock'
|
|
985
|
-
? 'unverified'
|
|
986
|
-
: await
|
|
1296
|
+
const { verdict, key } = this.source === 'mock'
|
|
1297
|
+
? { verdict: 'unverified', key: null }
|
|
1298
|
+
: await verifyWithKeys(envelope, this.options.keys);
|
|
987
1299
|
if (verdict === 'invalid') {
|
|
988
1300
|
await this.discard();
|
|
989
1301
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
|
|
@@ -993,15 +1305,19 @@
|
|
|
993
1305
|
}
|
|
994
1306
|
const fetchedAt = this.now();
|
|
995
1307
|
const issuedAt = Date.parse(envelope.payload.issuedAt);
|
|
1308
|
+
// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
|
|
1309
|
+
if (this.source !== 'mock')
|
|
1310
|
+
this.measureClockSkew(fetchedAt, issuedAt);
|
|
996
1311
|
if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
|
|
997
1312
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
|
|
998
1313
|
}
|
|
999
|
-
this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
|
|
1314
|
+
this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
|
|
1000
1315
|
const record = { v: CACHE_VERSION, envelope, fetchedAt };
|
|
1001
1316
|
await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
|
|
1002
1317
|
this.backoffMs = 0;
|
|
1003
1318
|
this.scheduleDeadline();
|
|
1004
1319
|
this.notifyIfChanged();
|
|
1320
|
+
this.options.onAccepted?.();
|
|
1005
1321
|
return this.snapshot();
|
|
1006
1322
|
}
|
|
1007
1323
|
/** Drain an older installation refresh before changing identity. */
|
|
@@ -1055,7 +1371,7 @@
|
|
|
1055
1371
|
this.deadlineTimer = null;
|
|
1056
1372
|
this.notifyIfChanged();
|
|
1057
1373
|
this.scheduleDeadline();
|
|
1058
|
-
}, remaining);
|
|
1374
|
+
}, Math.min(remaining, MAX_TIMER_MS));
|
|
1059
1375
|
}
|
|
1060
1376
|
schedule(delayMs) {
|
|
1061
1377
|
const generation = this.refreshGeneration;
|
|
@@ -1076,14 +1392,12 @@
|
|
|
1076
1392
|
}
|
|
1077
1393
|
}, delayMs);
|
|
1078
1394
|
}
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
return null;
|
|
1086
|
-
}
|
|
1395
|
+
measureClockSkew(local, server) {
|
|
1396
|
+
const ms = local - server;
|
|
1397
|
+
this.clockSkew =
|
|
1398
|
+
Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
|
|
1399
|
+
? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
|
|
1400
|
+
: null;
|
|
1087
1401
|
}
|
|
1088
1402
|
async discard() {
|
|
1089
1403
|
this.held = null;
|
|
@@ -1106,13 +1420,25 @@
|
|
|
1106
1420
|
if (!this.held)
|
|
1107
1421
|
return NaN;
|
|
1108
1422
|
// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
|
|
1109
|
-
return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) +
|
|
1423
|
+
return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
|
|
1424
|
+
}
|
|
1425
|
+
/** The signed allowance of the held license, or 48 hours when it names none. */
|
|
1426
|
+
offlineAgeMs() {
|
|
1427
|
+
const seconds = this.held?.envelope.payload.offlineSeconds;
|
|
1428
|
+
if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
|
|
1429
|
+
return MAX_OFFLINE_AGE_MS;
|
|
1430
|
+
return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
|
|
1110
1431
|
}
|
|
1111
1432
|
snapshot() {
|
|
1112
1433
|
if (!this.held)
|
|
1113
|
-
return EMPTY_ENTITLEMENT;
|
|
1434
|
+
return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
|
|
1114
1435
|
if (this.source !== 'mock' && !this.held.verified) {
|
|
1115
|
-
return {
|
|
1436
|
+
return {
|
|
1437
|
+
...EMPTY_ENTITLEMENT,
|
|
1438
|
+
requiresOnlineCheck: true,
|
|
1439
|
+
clockSkew: this.clockSkew,
|
|
1440
|
+
source: this.held.source,
|
|
1441
|
+
};
|
|
1116
1442
|
}
|
|
1117
1443
|
const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
|
|
1118
1444
|
const hasPaidAccess = collectFeatures(items).length > 0 ||
|
|
@@ -1128,6 +1454,7 @@
|
|
|
1128
1454
|
features: requiresOnlineCheck ? [] : collectFeatures(items),
|
|
1129
1455
|
requiresOnlineCheck,
|
|
1130
1456
|
offlineUntil,
|
|
1457
|
+
clockSkew: this.clockSkew,
|
|
1131
1458
|
verified: this.held.verified,
|
|
1132
1459
|
issuedAt: this.held.envelope.payload.issuedAt,
|
|
1133
1460
|
fetchedAt: this.held.fetchedAt,
|
|
@@ -1216,6 +1543,16 @@
|
|
|
1216
1543
|
this.map.delete(key);
|
|
1217
1544
|
}
|
|
1218
1545
|
}
|
|
1546
|
+
/**
|
|
1547
|
+
* The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
|
|
1548
|
+
* only the trial start there (never `endUserRef`), so devices on one synced account share the
|
|
1549
|
+
* trial. Uninstalling clears it from the account, so it does not survive a reinstall.
|
|
1550
|
+
*/
|
|
1551
|
+
function createSyncStorage() {
|
|
1552
|
+
const g = extensionGlobals();
|
|
1553
|
+
const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
|
|
1554
|
+
return area ? new ExtensionStorage(area) : null;
|
|
1555
|
+
}
|
|
1219
1556
|
function createStorage() {
|
|
1220
1557
|
const g = extensionGlobals();
|
|
1221
1558
|
const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
|
|
@@ -1272,7 +1609,7 @@
|
|
|
1272
1609
|
const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1273
1610
|
const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
|
|
1274
1611
|
const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1275
|
-
const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
|
|
1612
|
+
const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
|
|
1276
1613
|
if (!Number.isFinite(Date.parse(created.expiresAt)))
|
|
1277
1614
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
|
|
1278
1615
|
const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
|
|
@@ -1332,8 +1669,9 @@
|
|
|
1332
1669
|
break;
|
|
1333
1670
|
if (claim.state === 'complete') {
|
|
1334
1671
|
const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
|
|
1672
|
+
const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
|
|
1335
1673
|
await this.options.storage.remove(this.pendingKey);
|
|
1336
|
-
return { state: 'complete', entitlement };
|
|
1674
|
+
return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
|
|
1337
1675
|
}
|
|
1338
1676
|
if (claim.state !== 'pending')
|
|
1339
1677
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
|
|
@@ -1362,9 +1700,10 @@
|
|
|
1362
1700
|
const DEFAULT_API_URL = 'https://bff.extenshi.io';
|
|
1363
1701
|
const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
1364
1702
|
const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1703
|
+
const DEFAULT_TRIAL_ENDING_DAYS = 2;
|
|
1365
1704
|
|
|
1366
1705
|
/** Kept in sync with package.json by tests/unit/version.test.ts. */
|
|
1367
|
-
const VERSION = '0.
|
|
1706
|
+
const VERSION = '0.11.0';
|
|
1368
1707
|
|
|
1369
1708
|
/**
|
|
1370
1709
|
* The user's language as the SDK sends it. Kept apart from the paywall
|
|
@@ -1434,7 +1773,7 @@
|
|
|
1434
1773
|
if (!isHttpUrl(apiUrl))
|
|
1435
1774
|
errors.push('apiUrl must be an http(s) URL');
|
|
1436
1775
|
const entitlementPublicKey = input.entitlementPublicKey ?? null;
|
|
1437
|
-
if (entitlementPublicKey !== null &&
|
|
1776
|
+
if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
|
|
1438
1777
|
errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
|
|
1439
1778
|
}
|
|
1440
1779
|
const environment = input.environment ?? 'production';
|
|
@@ -1456,6 +1795,9 @@
|
|
|
1456
1795
|
const theme = input.theme ?? {};
|
|
1457
1796
|
if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
|
|
1458
1797
|
errors.push('theme.mode must be light, dark or auto');
|
|
1798
|
+
const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
|
|
1799
|
+
if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
|
|
1800
|
+
errors.push('trialEndingDays must be a whole number of days between 0 and 365');
|
|
1459
1801
|
if (input.mock &&
|
|
1460
1802
|
input.mockData !== undefined &&
|
|
1461
1803
|
(typeof input.mockData !== 'object' || input.mockData === null)) {
|
|
@@ -1476,6 +1818,8 @@
|
|
|
1476
1818
|
mock: input.mock === true,
|
|
1477
1819
|
mockData: input.mock ? (input.mockData ?? {}) : null,
|
|
1478
1820
|
theme,
|
|
1821
|
+
trialEndingDays,
|
|
1822
|
+
syncTrialStart: input.syncTrialStart !== false,
|
|
1479
1823
|
};
|
|
1480
1824
|
}
|
|
1481
1825
|
|
|
@@ -1604,8 +1948,10 @@
|
|
|
1604
1948
|
* extends it with `getOffer()` / `showPaywall()`.
|
|
1605
1949
|
*
|
|
1606
1950
|
* Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
|
|
1607
|
-
* `locale
|
|
1608
|
-
*
|
|
1951
|
+
* `locale`, checkout session IDs and, with a server trial, the trial start date
|
|
1952
|
+
* the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
|
|
1953
|
+
* challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
|
|
1954
|
+
* storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
|
|
1609
1955
|
*/
|
|
1610
1956
|
/** Server-side offer cache is 5 min; mirror it in memory. */
|
|
1611
1957
|
const OFFER_TTL_MS = 5 * 60 * 1000;
|
|
@@ -1616,12 +1962,30 @@
|
|
|
1616
1962
|
this.endUserRefPromise = null;
|
|
1617
1963
|
this.offer = null;
|
|
1618
1964
|
this.offerInflight = null;
|
|
1965
|
+
/** The signing key the server returned in this session; never one read from storage. */
|
|
1966
|
+
this.serverKey = null;
|
|
1967
|
+
/** Trust order for license signatures; see payment/signature.ts. */
|
|
1968
|
+
this.keys = {
|
|
1969
|
+
known: async () => {
|
|
1970
|
+
const pinned = this.config.entitlementPublicKey;
|
|
1971
|
+
const offline = pinned ?? (await this.readSavedServerKey());
|
|
1972
|
+
return [...new Set([this.serverKey, offline].filter((key) => !!key))];
|
|
1973
|
+
},
|
|
1974
|
+
fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
|
|
1975
|
+
};
|
|
1619
1976
|
this.readyPromise = null;
|
|
1620
1977
|
this.destroyed = false;
|
|
1621
1978
|
this.config = resolveConfig(config);
|
|
1622
1979
|
logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
|
|
1623
1980
|
this.now = deps.now ?? (() => Date.now());
|
|
1624
1981
|
this.storage = deps.storage ?? createStorage();
|
|
1982
|
+
this.openUrl = deps.openUrl;
|
|
1983
|
+
this.syncStorage =
|
|
1984
|
+
!this.config.syncTrialStart || this.config.mock
|
|
1985
|
+
? null
|
|
1986
|
+
: deps.syncStorage === undefined
|
|
1987
|
+
? createSyncStorage()
|
|
1988
|
+
: deps.syncStorage;
|
|
1625
1989
|
const transport = deps.transport ??
|
|
1626
1990
|
(this.config.mock
|
|
1627
1991
|
? new MockTransport(this.config.mockData ?? {})
|
|
@@ -1634,11 +1998,26 @@
|
|
|
1634
1998
|
cacheTtlMs: this.config.cacheTtlMs,
|
|
1635
1999
|
source: this.config.mock ? 'mock' : 'network',
|
|
1636
2000
|
getEndUserRef: () => this.getEndUserRef(),
|
|
1637
|
-
|
|
2001
|
+
keys: this.keys,
|
|
1638
2002
|
onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
|
|
2003
|
+
onAccepted: () => {
|
|
2004
|
+
void this.trial.evaluate();
|
|
2005
|
+
void this.rememberTrialStart();
|
|
2006
|
+
},
|
|
2007
|
+
getTrialStartHint: () => this.readTrialStartHint(),
|
|
1639
2008
|
onError: (error) => this.reportError(error),
|
|
1640
2009
|
now: this.now,
|
|
1641
2010
|
});
|
|
2011
|
+
this.trial = new TrialNotifier({
|
|
2012
|
+
storage: this.storage,
|
|
2013
|
+
storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
|
|
2014
|
+
endingDays: this.config.trialEndingDays,
|
|
2015
|
+
getTrial: () => this.entitlements.getTrial(),
|
|
2016
|
+
// A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
|
|
2017
|
+
hasPaidAccess: () => (this.entitlements.getCached()?.items ?? []).some(isLive),
|
|
2018
|
+
emit: (event, trial) => this.emitter.emit(event, trial),
|
|
2019
|
+
now: this.now,
|
|
2020
|
+
});
|
|
1642
2021
|
this.checkout = new CheckoutManager({
|
|
1643
2022
|
api: this.api,
|
|
1644
2023
|
storage: this.storage,
|
|
@@ -1652,6 +2031,13 @@
|
|
|
1652
2031
|
(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
|
|
1653
2032
|
now: this.now,
|
|
1654
2033
|
});
|
|
2034
|
+
this.backup = new CloudBackup({
|
|
2035
|
+
storage: this.storage,
|
|
2036
|
+
publishableKey: this.config.publishableKey,
|
|
2037
|
+
apiUrl: this.config.apiUrl,
|
|
2038
|
+
fetch: deps.fetch,
|
|
2039
|
+
mock: this.config.mock,
|
|
2040
|
+
});
|
|
1655
2041
|
this.recovery = new RecoveryManager({
|
|
1656
2042
|
api: this.api,
|
|
1657
2043
|
locale: this.config.locale,
|
|
@@ -1665,7 +2051,7 @@
|
|
|
1665
2051
|
envelope.payload.publishableKey !== this.config.publishableKey ||
|
|
1666
2052
|
!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
|
|
1667
2053
|
Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
|
|
1668
|
-
(await
|
|
2054
|
+
(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
|
|
1669
2055
|
throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
|
|
1670
2056
|
this.entitlements.stopAutoRefresh();
|
|
1671
2057
|
try {
|
|
@@ -1683,6 +2069,7 @@
|
|
|
1683
2069
|
this.entitlements.startAutoRefresh();
|
|
1684
2070
|
}
|
|
1685
2071
|
},
|
|
2072
|
+
onStorageGrant: (grant) => this.backup.accept(grant),
|
|
1686
2073
|
});
|
|
1687
2074
|
if (config.onError)
|
|
1688
2075
|
this.emitter.on('error', config.onError);
|
|
@@ -1728,8 +2115,11 @@
|
|
|
1728
2115
|
catch (error) {
|
|
1729
2116
|
this.reportError(error);
|
|
1730
2117
|
}
|
|
1731
|
-
|
|
2118
|
+
void this.confirmSavedServerKey();
|
|
2119
|
+
if (!this.destroyed) {
|
|
1732
2120
|
this.entitlements.startAutoRefresh();
|
|
2121
|
+
this.trial.start();
|
|
2122
|
+
}
|
|
1733
2123
|
}
|
|
1734
2124
|
/** The anonymous, random id this install is known by. */
|
|
1735
2125
|
getEndUserRef() {
|
|
@@ -1750,6 +2140,16 @@
|
|
|
1750
2140
|
await this.initialize();
|
|
1751
2141
|
return this.entitlements.get(options);
|
|
1752
2142
|
}
|
|
2143
|
+
/**
|
|
2144
|
+
* The free trial the application set on the server, from the verified license, or null when
|
|
2145
|
+
* there is none (or the license could not be verified yet). Answers offline from the cached
|
|
2146
|
+
* license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
|
|
2147
|
+
* `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
|
|
2148
|
+
*/
|
|
2149
|
+
async getTrial(options = {}) {
|
|
2150
|
+
await this.getEntitlement(options);
|
|
2151
|
+
return this.entitlements.getTrial();
|
|
2152
|
+
}
|
|
1753
2153
|
/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
|
|
1754
2154
|
async isPaid(sku) {
|
|
1755
2155
|
return isEntitled(await this.getEntitlement(), sku);
|
|
@@ -1833,6 +2233,41 @@
|
|
|
1833
2233
|
throw this.reportError(error);
|
|
1834
2234
|
}
|
|
1835
2235
|
}
|
|
2236
|
+
/**
|
|
2237
|
+
* Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
|
|
2238
|
+
* hosted restore page shows the storage disclosure and the buyer confirms with
|
|
2239
|
+
* the code from the purchase email. `cloudBackup` in the result says whether it is
|
|
2240
|
+
* on. Buyers only; consent is recorded by the server.
|
|
2241
|
+
*/
|
|
2242
|
+
enableCloudBackup(options = {}) {
|
|
2243
|
+
return this.restorePurchase({ ...options, purpose: 'storage' });
|
|
2244
|
+
}
|
|
2245
|
+
/**
|
|
2246
|
+
* The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
|
|
2247
|
+
* while cloud backup is off on this installation. Extension pages and background
|
|
2248
|
+
* only: it rejects in a content script, and must never be sent to one.
|
|
2249
|
+
*/
|
|
2250
|
+
async cloudBackupToken() {
|
|
2251
|
+
return this.backup.token();
|
|
2252
|
+
}
|
|
2253
|
+
/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
|
|
2254
|
+
async disableCloudBackup() {
|
|
2255
|
+
try {
|
|
2256
|
+
await this.backup.disable();
|
|
2257
|
+
}
|
|
2258
|
+
catch (error) {
|
|
2259
|
+
throw this.reportError(error);
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
|
|
2263
|
+
async deleteCloudBackup() {
|
|
2264
|
+
try {
|
|
2265
|
+
await this.backup.delete();
|
|
2266
|
+
}
|
|
2267
|
+
catch (error) {
|
|
2268
|
+
throw this.reportError(error);
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
1836
2271
|
/** Read-only license view. Entitlements retain cache/signature/offline semantics. */
|
|
1837
2272
|
async getLicenseSummary(options = {}) {
|
|
1838
2273
|
await this.initialize();
|
|
@@ -1902,6 +2337,7 @@
|
|
|
1902
2337
|
destroy() {
|
|
1903
2338
|
this.destroyed = true;
|
|
1904
2339
|
this.recovery.stop();
|
|
2340
|
+
this.trial.stop();
|
|
1905
2341
|
this.entitlements.stopAutoRefresh();
|
|
1906
2342
|
this.emitter.removeAll();
|
|
1907
2343
|
}
|
|
@@ -1913,8 +2349,9 @@
|
|
|
1913
2349
|
if (!this.offerInflight) {
|
|
1914
2350
|
this.offerInflight = this.api
|
|
1915
2351
|
.getOffer(this.config.locale)
|
|
1916
|
-
.then((value) => {
|
|
2352
|
+
.then(async (value) => {
|
|
1917
2353
|
this.offer = { value, fetchedAt: this.now() };
|
|
2354
|
+
await this.rememberServerKey(value.entitlementPublicKey);
|
|
1918
2355
|
return value;
|
|
1919
2356
|
})
|
|
1920
2357
|
.finally(() => {
|
|
@@ -1923,8 +2360,88 @@
|
|
|
1923
2360
|
}
|
|
1924
2361
|
return this.offerInflight;
|
|
1925
2362
|
}
|
|
1926
|
-
|
|
1927
|
-
return this.config.entitlementPublicKey
|
|
2363
|
+
get serverKeyStorageKey() {
|
|
2364
|
+
return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
|
|
2365
|
+
}
|
|
2366
|
+
async readSavedServerKey() {
|
|
2367
|
+
try {
|
|
2368
|
+
const value = await this.storage.get(this.serverKeyStorageKey);
|
|
2369
|
+
return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
|
|
2370
|
+
}
|
|
2371
|
+
catch {
|
|
2372
|
+
return null;
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Keeps the server's key next to the license cache so a restart with no network can verify it.
|
|
2377
|
+
* Not with a bundled key: that one already covers the restart, and storage stays untrusted.
|
|
2378
|
+
*/
|
|
2379
|
+
async rememberServerKey(key) {
|
|
2380
|
+
if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
|
|
2381
|
+
return;
|
|
2382
|
+
this.serverKey = key;
|
|
2383
|
+
if (this.config.entitlementPublicKey || this.config.mock)
|
|
2384
|
+
return;
|
|
2385
|
+
try {
|
|
2386
|
+
if ((await this.readSavedServerKey()) !== key)
|
|
2387
|
+
await this.storage.set(this.serverKeyStorageKey, key);
|
|
2388
|
+
}
|
|
2389
|
+
catch (error) {
|
|
2390
|
+
logger.debug('signing key not saved', error);
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* A license verified with the saved key alone is checked against the server once per start:
|
|
2395
|
+
* when the server's key differs (rotation, or an edited storage) the license is fetched again,
|
|
2396
|
+
* and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
|
|
2397
|
+
*/
|
|
2398
|
+
async confirmSavedServerKey() {
|
|
2399
|
+
const used = this.entitlements.verifiedKey;
|
|
2400
|
+
if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
|
|
2401
|
+
return;
|
|
2402
|
+
try {
|
|
2403
|
+
if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
|
|
2404
|
+
return;
|
|
2405
|
+
}
|
|
2406
|
+
catch {
|
|
2407
|
+
return;
|
|
2408
|
+
}
|
|
2409
|
+
try {
|
|
2410
|
+
await this.entitlements.refresh();
|
|
2411
|
+
}
|
|
2412
|
+
catch {
|
|
2413
|
+
await this.entitlements.reverify().catch((error) => this.reportError(error));
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
get trialStartKey() {
|
|
2417
|
+
return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
|
|
2418
|
+
}
|
|
2419
|
+
/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
|
|
2420
|
+
async readTrialStartHint() {
|
|
2421
|
+
if (!this.syncStorage)
|
|
2422
|
+
return null;
|
|
2423
|
+
try {
|
|
2424
|
+
const value = await this.syncStorage.get(this.trialStartKey);
|
|
2425
|
+
return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
|
|
2426
|
+
}
|
|
2427
|
+
catch {
|
|
2428
|
+
return null;
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
|
|
2432
|
+
async rememberTrialStart() {
|
|
2433
|
+
const trial = this.entitlements.getTrial();
|
|
2434
|
+
if (!this.syncStorage || !trial)
|
|
2435
|
+
return;
|
|
2436
|
+
try {
|
|
2437
|
+
const synced = await this.readTrialStartHint();
|
|
2438
|
+
if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
|
|
2439
|
+
return;
|
|
2440
|
+
await this.syncStorage.set(this.trialStartKey, trial.startedAt);
|
|
2441
|
+
}
|
|
2442
|
+
catch (error) {
|
|
2443
|
+
logger.debug('trial start not synced', error);
|
|
2444
|
+
}
|
|
1928
2445
|
}
|
|
1929
2446
|
reportError(error) {
|
|
1930
2447
|
const err = ExtenshiPayError.from(error);
|
|
@@ -1938,8 +2455,10 @@
|
|
|
1938
2455
|
exports.CHECKOUT_POLL_INTERVAL_MS = CHECKOUT_POLL_INTERVAL_MS;
|
|
1939
2456
|
exports.CHECKOUT_TIMEOUT_MS = CHECKOUT_TIMEOUT_MS;
|
|
1940
2457
|
exports.CheckoutManager = CheckoutManager;
|
|
2458
|
+
exports.CloudBackup = CloudBackup;
|
|
1941
2459
|
exports.DEFAULT_API_URL = DEFAULT_API_URL;
|
|
1942
2460
|
exports.DEFAULT_CACHE_TTL_MS = DEFAULT_CACHE_TTL_MS;
|
|
2461
|
+
exports.DEFAULT_TRIAL_ENDING_DAYS = DEFAULT_TRIAL_ENDING_DAYS;
|
|
1943
2462
|
exports.EMPTY_ENTITLEMENT = EMPTY_ENTITLEMENT;
|
|
1944
2463
|
exports.END_USER_REF_STORAGE_KEY = END_USER_REF_STORAGE_KEY;
|
|
1945
2464
|
exports.ERROR_CODES = ERROR_CODES;
|
|
@@ -1967,10 +2486,12 @@
|
|
|
1967
2486
|
exports.PAY_OFFER_KINDS = PAY_OFFER_KINDS;
|
|
1968
2487
|
exports.PAY_PUBLISHABLE_KEY_HEX_LENGTH = PAY_PUBLISHABLE_KEY_HEX_LENGTH;
|
|
1969
2488
|
exports.PAY_PUBLISHABLE_KEY_PREFIX = PAY_PUBLISHABLE_KEY_PREFIX;
|
|
2489
|
+
exports.PAY_RESTORE_PURPOSES = PAY_RESTORE_PURPOSES;
|
|
1970
2490
|
exports.PAY_SKU_RE = PAY_SKU_RE;
|
|
1971
2491
|
exports.PAY_WITHDRAWAL_WAIVER_VERSION = PAY_WITHDRAWAL_WAIVER_VERSION;
|
|
1972
2492
|
exports.PayApi = PayApi;
|
|
1973
2493
|
exports.RecoveryManager = RecoveryManager;
|
|
2494
|
+
exports.STORAGE_TOKEN_RE = STORAGE_TOKEN_RE;
|
|
1974
2495
|
exports.TRPC_PATH = TRPC_PATH;
|
|
1975
2496
|
exports.VERSION = VERSION;
|
|
1976
2497
|
exports.applyLocalExpiry = applyLocalExpiry;
|
|
@@ -1980,6 +2501,7 @@
|
|
|
1980
2501
|
exports.collectFeatures = collectFeatures;
|
|
1981
2502
|
exports.createRecoveryStorage = createRecoveryStorage;
|
|
1982
2503
|
exports.createStorage = createStorage;
|
|
2504
|
+
exports.createSyncStorage = createSyncStorage;
|
|
1983
2505
|
exports.getOrCreateEndUserRef = getOrCreateEndUserRef;
|
|
1984
2506
|
exports.hasFeature = hasFeature;
|
|
1985
2507
|
exports.isEntitled = isEntitled;
|