@amedia/user 1.8.1 → 1.9.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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @amedia/user
2
2
 
3
+ ## 1.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#1318](https://github.com/amedia/amedia-user-js/pull/1318) [`31e4d53`](https://github.com/amedia/amedia-user-js/commit/31e4d53b8906c3a09ca212566412bda474b2303b) Thanks [@hennikul](https://github.com/hennikul)! - PaywallUnlockRequest now asks the site's subscription provider to re-check the
8
+ reader at POST /api/access/refresh before showing the paywall, polling aID
9
+ meanwhile. withTimeout(ms) bounds the step (default 5000, 0 turns it off).
10
+ refreshAccess() does the step on its own. @amedia/user/node exports
11
+ ACCESS_REFRESH_PATH and parseAccessRefreshRequest for providers. Sites that
12
+ don't serve the path behave as before.
13
+
3
14
  ## 1.8.1
4
15
 
5
16
  ### Patch Changes
package/README.md CHANGED
@@ -349,6 +349,21 @@ page etc.
349
349
  Polling for expected access. Will either return true when required access
350
350
  features are attained, or TimeoutError.
351
351
 
352
+ ### `refreshAccess(accessFeatures: string[], { timeout = 5000 } = {}): Promise<boolean>`
353
+
354
+ The step `PaywallUnlockRequest` takes before showing the paywall, on its own: asks the site's subscription provider to
355
+ re-check the user and polls aID for `accessFeatures` meanwhile. Resolves `true` once aID grants any of them, the same
356
+ rule `PaywallUnlockRequest` uses, and `false` otherwise. With no `accessFeatures` the provider is asked about `pluss`
357
+ and any access counts. The provider is sent the page's address without its query string or fragment. Never throws.
358
+
359
+ ```ts
360
+ import { refreshAccess } from '@amedia/user';
361
+
362
+ if (await refreshAccess(['pluss'], { timeout: 3000 })) {
363
+ location.reload();
364
+ }
365
+ ```
366
+
352
367
  ### `requireVerification(requirement): Promise<{ satisfied: true }>`
353
368
 
354
369
  Make sure the reader has been through aID Identity Verification before you let them do something that requires it.
@@ -472,6 +487,10 @@ calling methods on this request:
472
487
  - `reloadOnAccess()`: If the paywall unlocker finds sufficient access for the user, it will reload the current page
473
488
  - `redirectOnAccess(requestedUrl: string)`: If the paywall unlocker finds sufficient access for the user, it will send
474
489
  the user to `requestedUrl`. (Provides more flexibility than `reloadOnAccess()`)
490
+ - `withTimeout(timeout: number)`: Roughly the most time, in milliseconds, `tryUnlock()` may spend asking the site's
491
+ subscription provider to re-check the user (`POST /api/access/refresh`) and waiting for aID to catch up; the last
492
+ check with aID can finish just after it. Default `5000`. `0` turns this off. Throws a `TypeError` for anything but a
493
+ finite number `>= 0`.
475
494
  - Deprecated (pass in constructor instead): `withAccessFeatures(accessFeatures: string[])`: Specify what access features
476
495
  will give access to the current content.
477
496
 
@@ -483,6 +502,10 @@ try to autologin the user on the current domain, check access, activate subscrip
483
502
  for stuff like IP-based access, etc. When this is done, it will resolve the `Promise` that was returned by
484
503
  `tryUnlock()`.
485
504
 
505
+ If aID says the user has no access, `tryUnlock()` asks the site's subscription provider to check again before giving
506
+ up, and polls aID meanwhile. A `granted` answer keeps it polling until the access arrives or the timeout is reached; any
507
+ other answer, including a `404` from a site that does not serve the path, stops it at once.
508
+
486
509
  The resolution to the promise contains an object with attributes you can use to get details about why the user did not
487
510
  get access (or if he had access if you don't opt for reload or redirect). The object contains the following:
488
511
 
package/index.d.ts CHANGED
@@ -212,6 +212,7 @@ declare class PaywallUnlockRequest {
212
212
  private requestedAccessFeatures;
213
213
  private reload;
214
214
  private requestedUrl;
215
+ private timeout;
215
216
  constructor(requestedAccessFeatures?: string[]);
216
217
  /**
217
218
  * @deprecated Required now. Set in constructor
@@ -219,6 +220,14 @@ declare class PaywallUnlockRequest {
219
220
  withAccessFeatures(accessFeatures: string[]): this;
220
221
  reloadOnAccess(): this;
221
222
  redirectOnAccess(requestedUrl: string): this;
223
+ /**
224
+ * Roughly the most time, in milliseconds, `tryUnlock()` may spend asking
225
+ * the site's subscription provider to re-check the reader and waiting for
226
+ * aID to catch up. Default 5000. 0 skips that step.
227
+ *
228
+ * @throws TypeError unless a finite number >= 0
229
+ */
230
+ withTimeout(timeout: number): this;
222
231
  tryUnlock(): Promise<PaywallUnlockResponse>;
223
232
  }
224
233
 
@@ -229,17 +238,42 @@ declare class EmergencyModeError extends Error {
229
238
 
230
239
  declare class TimeoutError extends Error {
231
240
  }
241
+ type PollForAccessOptions = {
242
+ /** Stops new polls; a poll already in flight still counts. */
243
+ signal?: AbortSignal;
244
+ /** Decides whether the access is enough. Default: every required feature. */
245
+ isSatisfied?: (access: string[]) => boolean;
246
+ };
232
247
  /**
233
248
  * Poll for access on current site.
234
249
  * Use this when you expect the reader to have gained access, but need to
235
250
  * be sure before telling the reader that everything's good.
236
251
  *
237
252
  * @throws EmergencyModeError if in emergency mode
238
- * @throws TimeoutError if access cannot be attained within given timeout
253
+ * @throws TimeoutError if access cannot be attained within given timeout, or
254
+ * polling was aborted before it was
239
255
  * @throws Error if unknown error
240
256
  * @returns true
241
257
  */
242
- declare const pollForAccess: (requiredAccessFeatures?: string[], timeout_millis?: number) => Promise<true>;
258
+ declare const pollForAccess: (requiredAccessFeatures?: string[], timeout_millis?: number, { signal, isSatisfied, }?: PollForAccessOptions) => Promise<true>;
259
+
260
+ declare const DEFAULT_ACCESS_REFRESH_TIMEOUT = 5000;
261
+ type RefreshAccessOptions = {
262
+ /** Budget for the refresh request and polling together, in milliseconds. */
263
+ timeout?: number;
264
+ };
265
+ /**
266
+ * Asks the site's subscription provider to re-check the reader, and polls aID
267
+ * meanwhile. Resolves true once aID grants any of `accessFeatures`, the same
268
+ * rule `PaywallUnlockRequest` uses. Without features the provider is asked
269
+ * about `pluss` and any access counts.
270
+ *
271
+ * Needs the reader's page: it polls the current browser session. A server
272
+ * takes part by serving `ACCESS_REFRESH_PATH`, not by calling this.
273
+ *
274
+ * Never throws.
275
+ */
276
+ declare const refreshAccess: (accessFeatures: string[], options?: RefreshAccessOptions) => Promise<boolean>;
243
277
 
244
278
  /**
245
279
  * Builds the aID Identity Verification URL for a requirement, for a link or a
@@ -299,5 +333,5 @@ declare const aidUrls: {
299
333
  sites: URL;
300
334
  };
301
335
 
302
- export { EmergencyModeError, FetchTimeoutError, PaywallError, PaywallUnlockRequest, PrivacyPreferences, SiteAccessRequest, SiteAccessResponse, TimeoutError, UserDataRequest, ValidationError, aidUrls, getLoginUrl, getVerificationOutcome, getVerificationProviders, getVerificationUrl, goToLoginPage, logout, pollForAccess, requestDataRefresh, requireVerification };
303
- export type { PaywallUnlockResponse, State, UserAttributes, VerifiableAttribute, VerificationError, VerificationOutcome, VerificationRequirement, VerificationSource, VerificationStatus };
336
+ export { DEFAULT_ACCESS_REFRESH_TIMEOUT, EmergencyModeError, FetchTimeoutError, PaywallError, PaywallUnlockRequest, PrivacyPreferences, SiteAccessRequest, SiteAccessResponse, TimeoutError, UserDataRequest, ValidationError, aidUrls, getLoginUrl, getVerificationOutcome, getVerificationProviders, getVerificationUrl, goToLoginPage, logout, pollForAccess, refreshAccess, requestDataRefresh, requireVerification };
337
+ export type { PaywallUnlockResponse, PollForAccessOptions, RefreshAccessOptions, State, UserAttributes, VerifiableAttribute, VerificationError, VerificationOutcome, VerificationRequirement, VerificationSource, VerificationStatus };
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "url": "git+https://github.com/amedia/amedia-user-js.git"
7
7
  },
8
8
  "author": "Amedia Produkt og Teknologi AS (https://amedia.no)",
9
- "version": "1.8.1",
9
+ "version": "1.9.0",
10
10
  "type": "module",
11
11
  "exports": {
12
12
  ".": {
package/user.node.d.ts CHANGED
@@ -652,6 +652,25 @@ declare const PAGE_OWNER_ATTRIBUTE = "data-aid-uuid";
652
652
  */
653
653
  declare const findForeignUuids: (currentUuid: string, markedUuids: Iterable<string>) => string[];
654
654
 
655
+ /**
656
+ * Served by the site's subscription provider on the site's own origin, not by
657
+ * aID. `granted` means the provider has already posted the access to aID.
658
+ */
659
+ declare const ACCESS_REFRESH_PATH = "/api/access/refresh";
660
+ /** `url` is the reader's page, without query string or fragment. */
661
+ type AccessRefreshRequest = {
662
+ accessFeatures: string[];
663
+ url: string;
664
+ };
665
+ type AccessRefreshResponse = {
666
+ status: 'granted';
667
+ } | {
668
+ status: 'denied';
669
+ };
670
+ type AccessRefreshOutcome = 'granted' | 'denied' | 'unrecognised';
671
+ /** For providers: validates an incoming body. Throws a TypeError naming the field. */
672
+ declare const parseAccessRefreshRequest: (body: unknown) => AccessRefreshRequest;
673
+
655
674
  interface AidClientOptions {
656
675
  /** Absolute base URL for aID (e.g. "https://aid.example.no"). Required. */
657
676
  baseUrl: string;
@@ -895,5 +914,5 @@ interface ValidatedToken {
895
914
  */
896
915
  declare const validateToken: (jwt: string, options: ValidateTokenOptions) => Promise<ValidatedToken>;
897
916
 
898
- export { AffiliationType, AidProblem, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LOGGED_OUT_PROBLEMS, LoginStatus, MAX_AGE_CEILING_SECONDS, PAGE_OWNER_ATTRIBUTE, ProblemJsonError, ResponseError, SESSION_HEADER, SITE_HEADER, ServerError, VERIFIABLE_ATTRIBUTES, VERIFICATION_SOURCES, ValidationError, buildVerificationUrl, clearJwksCache, createAidClient, createOnSiteClient, createShamoClient, fetchVerificationProviders, findForeignUuids, isAidProblem, isLoggedOut, namesNoReader, normalizeVerificationRequirement, readVerificationOutcome, validateToken, verificationSourceOf, verificationUrlFor };
899
- export type { AccessFeatures, AidClient, AidClientOptions, AidProblemType, JwksOptions, OnSiteClient, OnSiteClientOptions, PrimarySite, ServerVerificationRequirement, ServiceUser, ShamoClient, ShamoClientOptions, State, UserAttributes, ValidateTokenOptions, ValidatedToken, VerifiableAttribute, VerificationError, VerificationOutcome, VerificationProvider, VerificationRequirement, VerificationSource, VerificationStatus };
917
+ export { ACCESS_REFRESH_PATH, AffiliationType, AidProblem, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LOGGED_OUT_PROBLEMS, LoginStatus, MAX_AGE_CEILING_SECONDS, PAGE_OWNER_ATTRIBUTE, ProblemJsonError, ResponseError, SESSION_HEADER, SITE_HEADER, ServerError, VERIFIABLE_ATTRIBUTES, VERIFICATION_SOURCES, ValidationError, buildVerificationUrl, clearJwksCache, createAidClient, createOnSiteClient, createShamoClient, fetchVerificationProviders, findForeignUuids, isAidProblem, isLoggedOut, namesNoReader, normalizeVerificationRequirement, parseAccessRefreshRequest, readVerificationOutcome, validateToken, verificationSourceOf, verificationUrlFor };
918
+ export type { AccessFeatures, AccessRefreshOutcome, AccessRefreshRequest, AccessRefreshResponse, AidClient, AidClientOptions, AidProblemType, JwksOptions, OnSiteClient, OnSiteClientOptions, PrimarySite, ServerVerificationRequirement, ServiceUser, ShamoClient, ShamoClientOptions, State, UserAttributes, ValidateTokenOptions, ValidatedToken, VerifiableAttribute, VerificationError, VerificationOutcome, VerificationProvider, VerificationRequirement, VerificationSource, VerificationStatus };
package/user.node.js CHANGED
@@ -10,6 +10,10 @@ function tryParseJSON(value) {
10
10
  }
11
11
  }
12
12
 
13
+ // These guards check for truthy values of the expected type.
14
+ // Falsy values (0, false, empty string) intentionally return false.
15
+ const isRecord = (argument) => !!argument && typeof argument === 'object';
16
+
13
17
  class ResponseError extends Error {
14
18
  constructor(body, response, nestedException) {
15
19
  const message = `Request failed (${response.status}/${response.statusText}: ${response.url || '[missing url]'}) Body: ${body || '[empty body received]'}`;
@@ -728,6 +732,28 @@ const findForeignUuids = (currentUuid, markedUuids) => {
728
732
  return [...new Set(Array.from(markedUuids, normalize))].filter((uuid) => uuid !== current);
729
733
  };
730
734
 
735
+ /**
736
+ * Served by the site's subscription provider on the site's own origin, not by
737
+ * aID. `granted` means the provider has already posted the access to aID.
738
+ */
739
+ const ACCESS_REFRESH_PATH = '/api/access/refresh';
740
+ /** For providers: validates an incoming body. Throws a TypeError naming the field. */
741
+ const parseAccessRefreshRequest = (body) => {
742
+ if (!isRecord(body)) {
743
+ throw new TypeError('access refresh request must be a JSON object');
744
+ }
745
+ const { accessFeatures, url } = body;
746
+ if (!Array.isArray(accessFeatures) ||
747
+ accessFeatures.length === 0 ||
748
+ !accessFeatures.every((feature) => typeof feature === 'string' && feature)) {
749
+ throw new TypeError('accessFeatures must be a non-empty array of strings');
750
+ }
751
+ if (typeof url !== 'string' || !url) {
752
+ throw new TypeError('url must be a non-empty string');
753
+ }
754
+ return { accessFeatures: [...accessFeatures], url };
755
+ };
756
+
731
757
  /**
732
758
  * Reject URLs that are not absolute http(s) — protects against SSRF via
733
759
  * `file:`, `gopher:`, missing scheme (empty → relative), or malformed input
@@ -1026,5 +1052,5 @@ function mapJoseError(err) {
1026
1052
  return new ValidationError('validation_failed', String(err));
1027
1053
  }
1028
1054
 
1029
- export { AffiliationType, AidProblem, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LOGGED_OUT_PROBLEMS, LoginStatus, MAX_AGE_CEILING_SECONDS, PAGE_OWNER_ATTRIBUTE, ProblemJsonError, ResponseError, SESSION_HEADER, SITE_HEADER, ServerError, VERIFIABLE_ATTRIBUTES, VERIFICATION_SOURCES, ValidationError, buildVerificationUrl, clearJwksCache, createAidClient, createOnSiteClient, createShamoClient, fetchVerificationProviders, findForeignUuids, isAidProblem, isLoggedOut, namesNoReader, normalizeVerificationRequirement, readVerificationOutcome, validateToken, verificationSourceOf, verificationUrlFor };
1055
+ export { ACCESS_REFRESH_PATH, AffiliationType, AidProblem, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LOGGED_OUT_PROBLEMS, LoginStatus, MAX_AGE_CEILING_SECONDS, PAGE_OWNER_ATTRIBUTE, ProblemJsonError, ResponseError, SESSION_HEADER, SITE_HEADER, ServerError, VERIFIABLE_ATTRIBUTES, VERIFICATION_SOURCES, ValidationError, buildVerificationUrl, clearJwksCache, createAidClient, createOnSiteClient, createShamoClient, fetchVerificationProviders, findForeignUuids, isAidProblem, isLoggedOut, namesNoReader, normalizeVerificationRequirement, parseAccessRefreshRequest, readVerificationOutcome, validateToken, verificationSourceOf, verificationUrlFor };
1030
1056
  //# sourceMappingURL=user.node.js.map