@schibsted/account-sdk-browser 5.2.7 → 6.0.0-alpha.10

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.
Files changed (109) hide show
  1. package/README.md +46 -301
  2. package/dist/account-sdk.d.ts +22 -0
  3. package/dist/account.d.ts +179 -0
  4. package/dist/cache.d.ts +65 -0
  5. package/dist/config.d.ts +86 -0
  6. package/dist/globals.d.ts +11 -0
  7. package/dist/has-access-response.d.ts +2 -0
  8. package/dist/identity.d.ts +302 -0
  9. package/dist/index.d.ts +11 -0
  10. package/dist/index.js +828 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/monetization.d.ts +39 -0
  13. package/{src → dist}/object.d.ts +4 -9
  14. package/dist/popup.d.ts +9 -0
  15. package/dist/resolve-browser-window.d.ts +1 -0
  16. package/dist/rest-client.d.ts +102 -0
  17. package/dist/rest-clients.d.ts +10 -0
  18. package/dist/sdk-error.d.ts +29 -0
  19. package/dist/session-response.d.ts +54 -0
  20. package/{src/spidTalk.d.ts → dist/spid-talk.d.ts} +4 -6
  21. package/dist/types/account.d.ts +48 -0
  22. package/dist/types/common.d.ts +28 -0
  23. package/dist/types/identity.d.ts +23 -0
  24. package/dist/types/login.d.ts +125 -0
  25. package/dist/types/monetization.d.ts +26 -0
  26. package/dist/types/session.d.ts +146 -0
  27. package/dist/url.d.ts +8 -0
  28. package/dist/validate.d.ts +50 -0
  29. package/dist/version.d.ts +2 -0
  30. package/package.json +34 -52
  31. package/src/account-sdk.ts +92 -0
  32. package/src/account.ts +332 -0
  33. package/src/{cache.js → cache.ts} +53 -38
  34. package/src/{config.js → config.ts} +7 -32
  35. package/src/globals.ts +8 -0
  36. package/src/has-access-response.ts +35 -0
  37. package/src/identity.ts +1023 -0
  38. package/src/index.ts +40 -0
  39. package/src/monetization.ts +128 -0
  40. package/src/{object.js → object.ts} +9 -16
  41. package/src/popup.ts +74 -0
  42. package/src/resolve-browser-window.ts +11 -0
  43. package/src/rest-client.ts +253 -0
  44. package/src/rest-clients.ts +30 -0
  45. package/src/sdk-error.ts +61 -0
  46. package/src/session-response.ts +100 -0
  47. package/src/{spidTalk.js → spid-talk.ts} +10 -12
  48. package/src/types/account.ts +55 -0
  49. package/src/types/common.ts +32 -0
  50. package/src/types/identity.ts +26 -0
  51. package/src/types/login.ts +150 -0
  52. package/src/types/monetization.ts +29 -0
  53. package/src/types/session.ts +169 -0
  54. package/src/{url.js → url.ts} +6 -10
  55. package/src/{validate.js → validate.ts} +27 -43
  56. package/src/{version.js → version.ts} +1 -2
  57. package/es5/global.js +0 -12968
  58. package/es5/global.js.map +0 -1
  59. package/es5/global.min.js +0 -2
  60. package/es5/global.min.js.map +0 -1
  61. package/es5/identity.js +0 -12212
  62. package/es5/identity.js.map +0 -1
  63. package/es5/identity.min.js +0 -2
  64. package/es5/identity.min.js.map +0 -1
  65. package/es5/index.js +0 -12940
  66. package/es5/index.js.map +0 -1
  67. package/es5/index.min.js +0 -2
  68. package/es5/index.min.js.map +0 -1
  69. package/es5/monetization.js +0 -9176
  70. package/es5/monetization.js.map +0 -1
  71. package/es5/monetization.min.js +0 -2
  72. package/es5/monetization.min.js.map +0 -1
  73. package/es5/payment.js +0 -8853
  74. package/es5/payment.js.map +0 -1
  75. package/es5/payment.min.js +0 -2
  76. package/es5/payment.min.js.map +0 -1
  77. package/identity.d.ts +0 -1
  78. package/identity.js +0 -5
  79. package/index.d.ts +0 -4
  80. package/index.js +0 -9
  81. package/monetization.d.ts +0 -1
  82. package/monetization.js +0 -5
  83. package/payment.d.ts +0 -1
  84. package/payment.js +0 -5
  85. package/src/RESTClient.d.ts +0 -89
  86. package/src/RESTClient.js +0 -193
  87. package/src/SDKError.d.ts +0 -16
  88. package/src/SDKError.js +0 -55
  89. package/src/__mocks__/.eslintrc.yml +0 -8
  90. package/src/__mocks__/RESTClient.js +0 -54
  91. package/src/cache.d.ts +0 -64
  92. package/src/config.d.ts +0 -34
  93. package/src/es5/global.js +0 -13
  94. package/src/es5/identity.js +0 -10
  95. package/src/es5/index.js +0 -13
  96. package/src/es5/monetization.js +0 -10
  97. package/src/es5/payment.js +0 -10
  98. package/src/global-registry.js +0 -20
  99. package/src/identity.d.ts +0 -679
  100. package/src/identity.js +0 -1157
  101. package/src/monetization.d.ts +0 -80
  102. package/src/monetization.js +0 -172
  103. package/src/payment.d.ts +0 -115
  104. package/src/payment.js +0 -211
  105. package/src/popup.d.ts +0 -10
  106. package/src/popup.js +0 -59
  107. package/src/url.d.ts +0 -10
  108. package/src/validate.d.ts +0 -64
  109. package/src/version.d.ts +0 -2
package/README.md CHANGED
@@ -2,334 +2,79 @@
2
2
  [![Code coverage](https://codecov.io/gh/schibsted/account-sdk-browser/branch/master/graph/badge.svg)](https://codecov.io/gh/schibsted/account-sdk-browser)
3
3
  [![Snyk](https://snyk.io/test/github/schibsted/account-sdk-browser/badge.svg?targetFile=package.json)](https://snyk.io/test/github/schibsted/account-sdk-browser)
4
4
 
5
- # Schibsted account SDK for browsers
5
+ # Schibsted Account SDK for browsers
6
6
 
7
- Welcome! This is the home of the Schibsted account JavaScript SDK for use by any website that wishes
8
- to use Schibsted account to sign up and log in users. Use it to generate URLs for your site's "Log
9
- in" button, query the logged-in status of your users, and to check whether they have access to
10
- products and subscriptions, etc.
7
+ Welcome! This is the home of the Schibsted Account JavaScript SDK for browsers. Use it to let users
8
+ sign up and log in with Schibsted Account, read the current session, and check access to products
9
+ and features.
11
10
 
12
- ## Getting started
11
+ For detailed Account SDK API documentation, check [TYPEDOC](./TYPEDOC.md).
13
12
 
14
- This sdk mainly communicates with a service named Session Service, which is available on brand
15
- domains (i.e. id.vg.no) to avoid Third-Party Cookie request.
13
+ ## Before You Start
16
14
 
17
- Since browsers started to block Third-Party Cookies, your top domain from local machine needs to
18
- match your Session Service top domain. Otherwise, the Session Service cookie will be a third-party cookie
19
- and will not be sent with a XHR request.
15
+ The SDK communicates mainly with Session Service on a brand domain such as `id.vg.no`. Your website
16
+ and Session Service domain must share the same top-level site so browser cookies are sent with XHR
17
+ requests.
20
18
 
21
- The same applies to cross scheme requests. The Session Service is hosted on https and therefore you need to [run your site with HTTPS locally](https://web.dev/how-to-use-local-https/).
19
+ For local development:
22
20
 
23
- For example if your `pre` domain is pre.sdk-example.com, and it uses id.pre.sdk-example.com Session Service
24
- domain, your local domain should be local.sdk-example.com.
21
+ - serve your site over HTTPS, because Session Service is hosted over HTTPS
22
+ - use a local hostname with the same top-level site as the configured Session Service domain
25
23
 
26
- 1. Do `npm install --save @schibsted/account-sdk-browser`
27
- 1. Use this library as you would any other npm module: `import { Identity, Monetization, Payment } from '@schibsted/account-sdk-browser'`
28
- With CommonJS it is possible to `require` the modules Identity, Monetization and Payment
29
- by appending `/identity`, `/monetization'` or `/payment'`.
30
- 1. Build your site as you prefer. This library uses modern JavaScript syntax (including async/await
31
- and other ES2017 and WHATWG features) by default. We recommend that you do any transpilation
32
- yourself for the browser versions you need to cater to. See [this paragraph](#polyfills) for
33
- info about our Babel-ified version and info about polyfills.
34
- 1. Initiate the SDK and provide at least `clientId`, `env` and `sessionDomain`.
24
+ For example, if your pre-production site is `pre.sdk-example.com` and uses
25
+ `id.pre.sdk-example.com` as Session Service, use a local hostname such as
26
+ `local.sdk-example.com`.
35
27
 
36
- If this is for a new site and there is no sessionDomain yet, contact
37
- [support](mailto:schibstedaccount@schibsted.com) to initiate the process.
28
+ If this is a new site and you do not have a `sessionDomain` yet, contact
29
+ [support](mailto:schibstedaccount@schibsted.com).
38
30
 
39
- ## Migration to 5.x.x (ITP)
31
+ ## Development
40
32
 
41
- Follow the [migration guide](./MIGRATION.md).
42
-
43
- ## Simplified login widget
44
-
45
- 1. Ensure that your site has no site specific terms and conditions in the Schibsted account login flow.
46
- 1. Define rules for when and how often the simplified login prompt should be shown to unique users on your site. How you do this is up to you, but we recommend starting with showing the prompt once per user before potentially increasing this frequency over time.
47
- 1. Set up a function to check if users landing on your domain [is logged in](https://schibsted.github.io/account-sdk-browser/Identity.html#isLoggedIn) to your site.
48
- 1. If the user is not logged-in to your site, call the [showSimplifiedLoginWidget](https://schibsted.github.io/account-sdk-browser/Identity.html#showSimplifiedLoginWidget) function. The `showSimplifiedLoginWidget` accepts the same params as login function (`state` is required, it might be string or async function). If the simplified login prompt is to be loaded, `showSimplifiedLoginWidget` will return `true`.
49
- 1. Set up a way to store information about which users have been shown the simplified login prompt. How you do this is up to you, but one way is to use localStorage. Use this information to execute on the rules defined in #2.
50
-
51
- ## Example project
52
-
53
- There is an example that demonstrates how the SDK can be used. The code is
54
- [here](https://schibsted.ghe.com/user-identity/sdk-example), and you can see it live
55
- [here](https://pro.sdk-example.com). You have a use-case that we haven't thought of? Ask us to add
56
- it by creating an [issue](https://schibsted.ghe.com/user-identity/sdk-example/issues/new).
57
-
58
- You can use that code as inspiration or just fork and play with it. The account-sdk-browser NPM
59
- module is used for authenticating the user with Schibsted account. Take a look at how the SDK is
60
- initialized.
61
-
62
- When a user wants to log in to your site, you direct them to a UI flow hosted by **Schibsted Account**.
63
- We authenticate the user and redirect them back to your site. This final redirect back to your site is performed in accordance with the OAuth2 specification.
64
- This means we pass a `code` in the query string of that redirect URI.
65
- You can use that `code` on your site's backend, along with your client credentials (client ID and secret), to obtain an *Access Token* (AT) and a *Refresh Token* (RT).
66
- You should not send the AT (and **never** the RT!) to the browser. Instead, keep them on the server side and associate them with the specific user session.
67
- This allows you to call Schibsted Account APIs on behalf of that user.
68
-
69
- ## Events
70
-
71
- The SDK fires events on the instances when something we deem interesting is happening. For example the
72
- [Identity](https://schibsted.github.io/account-sdk-browser/Identity.html) class
73
- emits some events when the user is logged in or logged out. This SDK uses a familar interface that's
74
- very similar to Node's [EventEmitter](https://nodejs.org/api/events.html). The most important
75
- methods are `.on(eventName, listener)` (to subscribe to an event) and `.off(eventName, listener)`
76
- (to unsubscribe to an event).
77
-
78
- The SDK also emits global events on the `window` when a new instance is created.
79
- Events are emitted for:
80
-
81
- | Class | event name |
82
- | ------------ | ----------------------- |
83
- | Identity | `schIdentity:ready` |
84
- | Monetization | `schMonetization:ready` |
85
- | Payment | `schPayment:ready` |
86
-
87
- ```js
88
- window.addEventListener('schIdentity:ready', e => {
89
- // The event contains the initialized instance (e.detail.instance);
90
- }
33
+ Install dependencies and run the standard checks:
91
34
 
35
+ ```sh
36
+ npm ci
37
+ npm run build
38
+ npm test
39
+ npm run lint
40
+ npm run typecheck
92
41
  ```
93
42
 
94
- ## Identity
95
-
96
- Let's start with a bit of example code:
97
-
98
- #### Example
99
-
100
- ```javascript
101
- import { Identity } from '@schibsted/account-sdk-browser';
43
+ ## API Documentation
102
44
 
103
- const identity = new Identity({
104
- clientId: '56e9a5d1eee0000000000000',
105
- redirectUri: 'https://awesomenews.site', // ensure it's listed in selfservice
106
- env: 'PRE', // Schibsted account env. A url or a special key: 'PRE', 'PRO', 'PRO_NO', 'PRO_FI' or 'PRO_DK'
107
- sessionDomain: 'https://id.awesomenews.site', // client-configured session-service domain
108
- });
45
+ Public API documentation is generated from TypeScript source comments with TypeDoc.
109
46
 
110
- async function whenSiteLoaded() {
111
- const loginContainer = document.getElementById('login-container');
112
- if (await identity.isLoggedIn()) {
113
- const user = await identity.getUser();
114
- const span = document.createElement('span');
115
- span.textContent = `Hello ${user.givenName}`;
116
- loginContainer.appendChild(span);
117
- } else {
118
- loginContainer.innerHTML = '<button class="login-button">Log in</button>';
119
- }
120
- }
121
-
122
- function userClicksLogIn() {
123
- identity.login({ state: 'some-random-string-1234-foobar-wonky-pig' });
124
- }
47
+ ```sh
48
+ npm run docs:build
49
+ npm run docs:open
125
50
  ```
126
51
 
127
- #### Regarding `state`
128
-
129
- This parameter is an OpenID Connect parameter (described in [this paragraph in the
130
- spec](http://openid.net/specs/openid-connect-core-1_0.html#rfc.section.3.1.2.1)). It's formatted as
131
- an opaque string. This means you can send anything that can be serialized to a string. In practice,
132
- we have good experience sending something like a JSON value like a base64-url-encoded value — it's
133
- just an easy way to avoid browsers or backends messing with special characters.
134
-
135
- But as a trivial example, if you call `Identity.login(..)` with params
136
- `redirectUri=https://site.com&state=article%3D1234` — then at the end of the authentication flow,
137
- the user will be sent back to your redirectUri, and the `state` parameter will be forwarded along
138
- with the auth `code` parameter.
139
-
140
- It is recommended that you provide a unique identifier as part of the state, to prevent CSRF
141
- attacks. For example this can be accomplished by:
142
-
143
- 1. Your backend generates random token: `1234abcd`, saves it in some tokenCache, and forwards to
144
- your browser frontend
145
- 1. Your frontend calls `Identity.login` with `state = base64Urlencode({ token: '1234abcd', article:
146
- '1234', ... })`
147
- 1. When auth flow completes, the user is redirected back to your site. Then, your backend sees the
148
- query parameters `code` (which it can exchange for OAuth tokens for the user) and `state`
149
- 1. Your backend can do `decodedState = base64Urldecode(query.state)` and then verify that its
150
- `tokenCache.contains(decodedState.token)`. If that fails, then possibly a CSRF attack was
151
- attempted. If successful, remove the token from the tokenCache so the same token can't be used
152
- again, and continue to show `decodedState.article`
153
-
154
- #### Authentication methods
155
-
156
- Although Schibsted account abstracts away the details of how the users sign up or log in, it's worth
157
- mentioning that your end users have a few ways to log in:
158
-
159
- * Username & password: pretty self-explanatory; users register using an email address and a
160
- self-chosen password
161
- * Passwordless - email: here, the users enter their email address and receive a one-time code that
162
- they can use to log in
163
- * Multifactor authentication: first client indicates which methods should be preferred, later these
164
- will be included (if fulfilled) in `AMR` claim of IDToken
165
-
166
- The default is username & password. If you wish to use one of the passwordless login methods, the
167
- `login()` function takes an optional parameter called `acrValues` (Authentication Context Class Reference).
168
- The `acrValues` parameter with multifactor authentication can take following values:
169
-
170
- * `eid` - authentication using BankID (for DEV and PRE environments you can choose between country specific solution by specifying `eid-no` or `eid-se` instead)
171
- * `otp-email` - passwordless authentication using code sent to registered email
172
- * `password` - force password authentication (even if user is already logged in)
173
- * `otp` - authentication using registered one time code generator (https://tools.ietf.org/html/rfc6238)
174
- * `sms` - authentication using SMS code sent to phone number
175
- * `password otp sms` - those authentication methods might be combined
176
-
177
- The classic way to authenticate a user, is to send them from your site to the Schibsted account
178
- domain, let the user authenticate there, and then have us redirect them back to your site. If you
179
- prefer, we also provide a popup that you can use. In this method, the authentication happens on a
180
- separate popup window and at the end of the auth flow. We recommend that you make the popup send a
181
- signal to your main page — using
182
- [postMessage](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) or something
183
- similar — to indicate that the user is logged in. If the popup window fails to open, it'll
184
- automatically fall back to the redirect flow. The SDK Example project mentioned above demonstrates
185
- how it can work. Again, you can see [sdk-example](https://schibsted.ghe.com/user-identity/sdk-example) if you
186
- want a working example.
187
-
188
- #### Is the user logged in?
189
-
190
- Schibsted account relies on browser cookies to determine whether a user is recognized as logged in.
191
- The SDK provides functions that can be used to check if the user that's visiting your site is
192
- already a Schibsted user or not.
52
+ During documentation work, use:
193
53
 
194
- * [Identity#isLoggedIn](https://schibsted.github.io/account-sdk-browser/Identity.html#isLoggedIn)
195
- tells you if the user that is visiting your site is already logged in to Schibsted account or not.
196
-
197
- * [Identity#isConnected](https://schibsted.github.io/account-sdk-browser/Identity.html#isConnected)
198
- tells you if the user is connected to your client. A user might have `isLoggedIn=true` and at the
199
- same time `isConnected=false` if they have logged in to Schibsted account, but not accepted terms
200
- and privacy policy for your site.
201
-
202
- If you've lately changed your terms & conditions, maybe the user still hasn't accepted them. In that
203
- case they are considered *not connected*. In that case, if they click "Log in" from your site, we
204
- will just ask them to accept those terms and redirect them right back to your site.
205
-
206
- #### Logging out
207
-
208
- If you want to log the user out of Schibsted account, you can call
209
- [Identity#logout](https://schibsted.github.io/account-sdk-browser/Identity.html#logout). This
210
- will remove the Schibsted account brand session. User will still be logged into Schibsted account.
211
-
212
- ## Monetization
213
-
214
- The preferred method for checking whether a user has access to a product/subscription is
215
- [Monetization#hasAccess](https://schibsted.github.io/account-sdk-browser/Monetization.html#hasAccess).
216
- It requires using Session Service, and supports both Schibsted account productId's and Zuora
217
- feature id's.
218
-
219
- #### Example
220
-
221
- ```javascript
222
- import { Monetization } from '@schibsted/account-sdk-browser';
223
-
224
- const monetization = new Monetization({
225
- clientId: '56e9a5d1eee0000000000000',
226
- redirectUri: 'https://awesomenews.site', // ensure it's listed in selfservice
227
- sessionDomain: 'https://id.aweseome.site', // client-configured session-service domain
228
- env: 'PRE', // Schibsted account env. A url or a special key: 'PRE', 'PRO' or 'PRO_NO'
229
- });
230
-
231
- try {
232
- // Check if the user has access to a a particular product
233
- const userId = await identity.getUserId();
234
- const data = await monetization.hasAccess([productId], userId);
235
- alert(`User has access to ${productId}? ${data.entitled}`);
236
- } catch (err) {
237
- alert(`Could not query if the user has access to ${productId} because ${err}`);
238
- }
239
- ```
240
-
241
- ## Payment
242
-
243
- This class provides methods for paying with a so-called paylink, buying a product, getting links to
244
- pages for redeeming voucher codes, reviewing payment history, and more.
245
-
246
- #### Example
247
-
248
- ```javascript
249
- import { Payment } from '@schibsted/account-sdk-browser';
250
-
251
- const paymentSDK = new Payment({
252
- clientId: '56e9a5d1eee0000000000000',
253
- redirectUri: 'https://awesomenews.site', // ensure it's listed in selfservice
254
- env: 'PRE', // Schibsted account env. A url or a special key: 'PRE', 'PRO' or 'PRO_NO'
255
- });
256
-
257
- // Get the url to paymentSDK with paylink
258
- const paylink = '...';
259
- const paylinkUrl = paymentSDK.purchasePaylinkUrl(paylink);
260
-
261
- // Or another example --- pay with paylink in a popup
262
- paymentSDK.payWithPaylink(paylink);
54
+ ```sh
55
+ npm run docs:watch
263
56
  ```
264
57
 
265
- ## Appendix
266
-
267
- #### Polyfills
268
-
269
- This SDK uses modern JavaScript features. If you support older browsers, you should use a tool like
270
- babel to transform the JavaScript as needed. However, since certain teams have deployment pipelines
271
- where it's difficult to do their own transpilation, we do provide some opt-in es5 files as well:
58
+ Generated docs are written to `docs/` and are not committed.
272
59
 
273
- 1. `@schibsted/account-sdk-browser/es5`: Include both `Identity`, `Monetization` and `Payment`.
274
- 1. `@schibsted/account-sdk-browser/es5/global`: Include both `Identity`, `Monetization` and
275
- `Payment`. In addition, add them as variables to the global `window` object.
276
- 1. `@schibsted/account-sdk-browser/es5/identity`, `@schibsted/account-sdk-browser/es5/monetization`
277
- or `@schibsted/account-sdk-browser/es5/payment` can be used to only include each class by itself.
60
+ ## Example Project
278
61
 
279
- But then regardless of whether you use the es5 versions or not, you might need to polyfill certain
280
- things that might be missing in the browsers you wish to support. A quick test using IE11 showed
281
- that we needed polyfills for `Promise`, `URL`, `Object.entries`, `fetch`, `Number.isFinite` and
282
- `Number.isInteger`.
283
-
284
- #### Cookies
285
-
286
- There are some cookies used by Schibsted account. They should all be considered opaque on the
287
- browser side. Nevertheless, here is a short description of them.
288
-
289
- 1. The **autologin** cookie (often called 'the remember-me-cookie'): The cookie name in the
290
- production environments is `vgs_email`, because reasons (on PRE, it is called `spid-pre-data`).
291
- It's a JSON string that's encoded using the standard `encodeURIComponent()` function and is an
292
- object that contains two pieces of information that's important:
293
- * `remember`: if set to `true`, the user chose to be remembered and this means we usually support
294
- auto-login (that is, if you call the Schibsted account hassession service, and no session can
295
- be found in the session database, it will automatically create a new one for the user so that
296
- they don't have to authenticate again. If it is `false`, it should be interpreted as the user
297
- does not want to be automatically logged in to any site when their session expires
298
- * `v`: the version number
299
- 1. The **session** cookies: Cookie names in production environments are `identity`, and `SPID_SE` or
300
- `SPID_NO`. It contains:
301
- * `user`: an object (if it's missing, a call to hassession will return a `401` with a
302
- `UserException` that says `No session found`)
303
- * `userId` identifies the user. We use this property to compare "old" user with "new" user and
304
- fire events that indicate that the user has changed
305
- * `is_logged_in` indicates if the user is logged in
306
- * `user_tags`: a map that contains some flags about the user; namely:
307
- * `is_logged_in` indicates if the user is logged in (this seems to be a duplicate of a
308
- property with a similar name in the parent `user` object)
309
- * `terms`: a map of term ids that indicate if they've been accepted by the user.
310
- * `referer` (yep, missing the double "rr"..): If this is missing, a call to hassession will
311
- return a `401` with a `UserException` that says `No session found`.
62
+ The internal example integration is available in the
63
+ [sdk-example repository](https://schibsted.ghe.com/user-identity/sdk-example).
312
64
 
313
65
  ## Publishing
314
66
 
315
- Versioning and changelog are handled by [Release Please (GitHub Action)](https://github.com/googleapis/release-please). Publishing to [npmjs.org](https://www.npmjs.com/package/@schibsted/account-sdk-browser) is handled by the [npm-publish workflow](./.github/workflows/npm-publish.yml). See the [Release Please workflow](./.github/workflows/release-please.yml) and [`release-please-config.json`](./release-please-config.json).
67
+ Versioning and changelog updates are handled by
68
+ [Release Please](https://github.com/googleapis/release-please). The release configuration lives in
69
+ [`release-please-config.json`](./release-please-config.json), and publishing to
70
+ [npmjs.org](https://www.npmjs.com/package/@schibsted/account-sdk-browser) is handled by the
71
+ [npm-publish workflow](./.github/workflows/npm-publish.yml) when a GitHub Release is published.
316
72
 
317
- When publishable changes have been merged to `master`, Release Please will create (or update) a release pull request.
318
- The suggested version is based on the commit messages in accordance with the [Conventional Commits](https://www.conventionalcommits.org/) specification — `fix:` bumps the patch version, `feat:` bumps the minor version, and `feat!:` or a `BREAKING CHANGE:` footer bumps the major version.
319
- Other prefixes (`chore:`, `docs:`, `test:`, `refactor:`, `ci:`, `build:`, `style:`) do not trigger a release and are hidden from the changelog.
73
+ Use [Conventional Commits](https://www.conventionalcommits.org/) for changes that should be picked
74
+ up by release automation.
320
75
 
321
- To release/publish the changes simply merge the corresponding pull request and wait for the publish workflow to finish.
322
- Release-please will create a git tag (e.g. `v5.2.7`) and a GitHub Release, and the [publish workflow](./.github/workflows/npm-publish.yml) will push the package to npmjs.org.
323
-
324
-
325
- ## LICENSE
76
+ ## License
326
77
 
327
78
  Copyright (c) 2026 Schibsted Products & Technology AS
328
79
 
329
- Licensed under the [MIT
330
- License](https://schibsted.ghe.com/user-identity/account-sdk-browser/blob/master/LICENSE.md)
331
-
332
- Unless required by applicable law or agreed to in writing, software distributed under the License is
333
- distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
334
- implied. See the License for the specific language governing permissions and limitations under the
335
- License.
80
+ Licensed under the [MIT License](./LICENSE.md).
@@ -0,0 +1,22 @@
1
+ import { Account } from './account.js';
2
+ import { AccountConfig } from './types/account.js';
3
+ /**
4
+ * Creates and registers the single Account SDK instance for the current browser window.
5
+ *
6
+ * The created instance is stored on `window.schAccount` and the SDK emits
7
+ * `schAccount:ready` with the instance in `event.detail.instance`.
8
+ *
9
+ * @param config - Client, redirect, environment, and Session Service configuration.
10
+ * @throws {SDKError} If the SDK cannot run in the current browser context, if an Account instance
11
+ * has already been initialized, or if configuration validation fails.
12
+ * @group Core API
13
+ */
14
+ export declare function createAccountSdk(config: AccountConfig): Account;
15
+ /**
16
+ * Resolves the Account SDK instance registered by `createAccountSdk()`.
17
+ *
18
+ * If the instance already exists, the promise resolves immediately. Otherwise it waits for
19
+ * `schAccount:ready` and rejects if initialization does not happen within the SDK timeout.
20
+ * @group Core API
21
+ */
22
+ export declare function getAccountSdk(): Promise<Account>;
@@ -0,0 +1,179 @@
1
+ import { AccountConfig, AccountEventListener, AccountEventName } from './types/account.js';
2
+ import { LoginOptions, SimplifiedLoginData, SimplifiedLoginWidgetLoginOptions, SimplifiedLoginWidgetOptions } from './types/login.js';
3
+ import { HasAccessResult } from './types/monetization.js';
4
+ import { ConnectedSessionResponse, SessionResponse, SessionUserId } from './types/session.js';
5
+ /**
6
+ * Unified client-side interface for a configured Schibsted Account integration.
7
+ *
8
+ * Create an instance with `createAccountSdk()` unless you explicitly need to construct it
9
+ * yourself. The instance coordinates identity, login, session, and access-check features for one
10
+ * configured client.
11
+ *
12
+ * @group Core API
13
+ */
14
+ export declare class Account {
15
+ #private;
16
+ constructor(config: AccountConfig);
17
+ /**
18
+ * Queries Session Service and returns the current browser session state.
19
+ *
20
+ * This call may trigger a full-page session refresh redirect. Configure
21
+ * `callbackBeforeRedirect` if your app needs to persist state before that navigation.
22
+ *
23
+ * @throws {SDKError} If the Session Service call fails.
24
+ */
25
+ hasSession(): Promise<SessionResponse>;
26
+ /**
27
+ * Checks whether the browser currently has a Schibsted Account session.
28
+ *
29
+ * Returns `false` instead of throwing when the session lookup fails.
30
+ */
31
+ isLoggedIn(): Promise<boolean>;
32
+ /**
33
+ * Checks whether the current user is connected to the configured client.
34
+ *
35
+ * A user can be logged in to Schibsted Account without being connected to your client, for
36
+ * example before accepting required terms.
37
+ */
38
+ isConnected(): Promise<boolean>;
39
+ /**
40
+ * Returns the connected user session data.
41
+ *
42
+ * @throws {SDKError} If the user is not connected to the configured client.
43
+ */
44
+ getUser(): Promise<ConnectedSessionResponse>;
45
+ /**
46
+ * Returns the realm-specific Schibsted Account user id as a number.
47
+ *
48
+ * Use `getUserUuid()` when you need the globally unique user id.
49
+ *
50
+ * @throws {SDKError} If the user is not connected to the configured client.
51
+ */
52
+ getUserId(): Promise<number>;
53
+ /**
54
+ * Returns an external identifier for the authenticated user, scoped to the configured client
55
+ * and external party.
56
+ *
57
+ * @param externalParty - External party for which the identifier is generated.
58
+ * @param optionalSuffix - Optional suffix included when generating the identifier.
59
+ * @throws {SDKError} If the session lookup fails, the session does not contain a `pairId`, or
60
+ * `externalParty` is empty.
61
+ * @deprecated Retained for compatibility with existing integrations. Avoid new usage.
62
+ */
63
+ getExternalId(externalParty: string, optionalSuffix?: string): Promise<string>;
64
+ /**
65
+ * Returns the globally unique user id from the current session.
66
+ *
67
+ * @throws {SDKError} If the user is not connected to the configured client.
68
+ */
69
+ getUserUuid(): Promise<string>;
70
+ /**
71
+ * Returns the user SDRN from the current session.
72
+ *
73
+ * @throws {SDKError} If the SDRN is missing from the session response.
74
+ */
75
+ getUserSDRN(): Promise<string>;
76
+ /**
77
+ * Returns minimal user context for simplified login prompts.
78
+ *
79
+ * Returns `null` if the global account session cannot be read.
80
+ */
81
+ getUserContextData(): Promise<SimplifiedLoginData | null>;
82
+ /**
83
+ * Returns the Varnish `sp_id` value from the current session when present.
84
+ */
85
+ getSpId(): Promise<string | null>;
86
+ /**
87
+ * Starts the login flow with either a full-page redirect or a popup.
88
+ *
89
+ * Call this from a user gesture when `preferPopup` is enabled, otherwise browser popup blockers
90
+ * may block the popup and the SDK will fall back to redirect navigation.
91
+ *
92
+ * @param options - Login URL parameters.
93
+ * @returns A popup window reference when a popup is opened; otherwise `null`.
94
+ */
95
+ login(options: LoginOptions): Window | null;
96
+ /**
97
+ * Logs the user out from the brand Session Service session and redirects the browser.
98
+ *
99
+ * @param redirectUri - Where Session Service should redirect the browser after logout.
100
+ */
101
+ logout(redirectUri?: string): void;
102
+ /**
103
+ * Builds the login URL without navigating the browser.
104
+ *
105
+ * @param options - Login URL parameters.
106
+ */
107
+ loginUrl(options: LoginOptions): string;
108
+ /**
109
+ * Builds the logout URL without navigating the browser.
110
+ *
111
+ * @param redirectUri - Where Session Service should redirect the browser after logout.
112
+ */
113
+ logoutUrl(redirectUri?: string): string;
114
+ /**
115
+ * Builds the Schibsted Account profile page URL.
116
+ *
117
+ * @param redirectUri - Where the account page should redirect the browser afterwards.
118
+ */
119
+ accountUrl(redirectUri?: string): string;
120
+ /**
121
+ * Loads and displays the simplified login widget when user context is available.
122
+ *
123
+ * Your application decides how often to call this method. The `state` field in `loginParams`
124
+ * may be a string or a function that resolves to a string.
125
+ * Widget open and cancel events can be observed with `on()`.
126
+ *
127
+ * @returns `true` when the widget was displayed.
128
+ * @throws {SDKError} If user context data is missing or the widget script cannot be loaded.
129
+ */
130
+ showSimplifiedLoginWidget(loginParams: SimplifiedLoginWidgetLoginOptions, options?: SimplifiedLoginWidgetOptions): Promise<boolean>;
131
+ /**
132
+ * Enables or disables caching for subsequent session lookups.
133
+ *
134
+ * Changing this setting does not remove an existing cached session.
135
+ */
136
+ setSessionCachingEnabled(enabled: boolean): void;
137
+ /**
138
+ * Removes the cached Session Service user session response.
139
+ */
140
+ clearCachedUserSession(): void;
141
+ /**
142
+ * Checks whether the current user has access to any of the requested products or features.
143
+ *
144
+ * When `productIds` is omitted, the ids configured as `defaultProductIds` are used.
145
+ * Results are cached according to the TTL returned by Session Service.
146
+ *
147
+ * @param productIds - Product or feature ids to check instead of the configured defaults.
148
+ * @returns Access data, or `null` when the user is not entitled.
149
+ * @throws {SDKError} If product ids are not provided or configured, `sessionDomain` is missing,
150
+ * the current user cannot be resolved, input is invalid, or the request fails.
151
+ */
152
+ hasAccess(productIds?: string[] | undefined): Promise<HasAccessResult | null>;
153
+ /**
154
+ * Removes a cached access-check result.
155
+ *
156
+ * @param productIds - Product or feature ids used for the cached lookup.
157
+ * @param userId - User id used for the cached lookup.
158
+ */
159
+ clearCachedAccessResult(productIds: string[], userId: SessionUserId): void;
160
+ /**
161
+ * Subscribes to Account events.
162
+ *
163
+ * Supported event names are defined by {@link AccountEventName}.
164
+ *
165
+ * @param event - Event name.
166
+ * @param listener - Listener that receives an `Event` or `CustomEvent`.
167
+ */
168
+ on<EventName extends AccountEventName>(event: EventName, listener: AccountEventListener<EventName>): this;
169
+ /**
170
+ * Unsubscribes from Account events.
171
+ *
172
+ * Supported event names are defined by {@link AccountEventName}.
173
+ *
174
+ * @param event - Event name.
175
+ * @param listener - Listener to remove.
176
+ */
177
+ off<EventName extends AccountEventName>(event: EventName, listener: AccountEventListener<EventName>): this;
178
+ }
179
+ export default Account;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Cache implementation used when web storage is available. Wraps a `Storage` instance.
3
+ * @private
4
+ */
5
+ declare class WebStorageCache {
6
+ store: Storage;
7
+ get: (key: string) => string | null;
8
+ set: (key: string, value: string) => void;
9
+ delete: (key: string) => void;
10
+ /**
11
+ * Create web storage cache object
12
+ * @param store - A reference to either `sessionStorage` or `localStorage` from a
13
+ * `Window` object
14
+ */
15
+ constructor(store: Storage);
16
+ }
17
+ /**
18
+ * Cache implementation used when web storage is not available. Stores entries in an in-memory object.
19
+ * @private
20
+ */
21
+ declare class LiteralCache {
22
+ store: Record<string, string>;
23
+ get: (key: string) => string | undefined;
24
+ set: (key: string, value: string) => void;
25
+ delete: (key: string) => void;
26
+ /**
27
+ * Create JS object literal cache object
28
+ */
29
+ constructor();
30
+ }
31
+ /**
32
+ * Cache class that attempts WebStorage (session/local storage), and falls back to JS object literal
33
+ * @private
34
+ */
35
+ export default class Cache {
36
+ cache: WebStorageCache | LiteralCache;
37
+ type: string;
38
+ /**
39
+ * @param storeProvider - A function to return a WebStorage instance (either
40
+ * `sessionStorage` or `localStorage` from a `Window` object)
41
+ * @throws {SDKError} - If sessionStorage or localStorage are not accessible
42
+ */
43
+ constructor(storeProvider?: () => Storage);
44
+ /**
45
+ * Get a value from cache (checks that the object has not expired)
46
+ * @param key
47
+ * @private
48
+ */
49
+ get(key: string): unknown;
50
+ /**
51
+ * Set a cache entry
52
+ * @param key
53
+ * @param value
54
+ * @param expiresIn - Value in milliseconds until the entry expires
55
+ * @private
56
+ */
57
+ set(key: string, value: unknown, expiresIn?: number): void;
58
+ /**
59
+ * Delete a cache entry
60
+ * @param key
61
+ * @private
62
+ */
63
+ delete(key: string): void;
64
+ }
65
+ export {};