dh-auth-library 2.1.2 → 2.2.1

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 CHANGED
@@ -28,7 +28,7 @@ config loads):
28
28
  | Variable | Used for |
29
29
  |---|---|
30
30
  | `ENV` | The environment: `ACC`, `TEST`, `PROD` or `LOCALHOST`. Part of the session file names; on `LOCALHOST` DigiD and eHerkenning use the local login. |
31
- | `PORTAL_BASE_URL` | The klantportaal. Start page of a login when the handler has no `startUrl`, and the page the session refresh checks. |
31
+ | `PORTAL_BASE_URL` | The klantportaal, e.g. `https://klantportaal-zgw.acc.denhaag.nl/`. Start page of a login when the handler has no `startUrl`, and the page the session refresh checks, also for Open Forms sessions. Another app here (e.g. GZAC) breaks those logins and the refresh. |
32
32
  | `WITH_AD_SESSION` | `true` to start every login from an AD session, needed when the apps sit behind the AD login (outside the network). |
33
33
  | `AD_USER`, `AD_PASSWORD` | The AD account used for that AD session. |
34
34
  | `AD_SECRET` | The TOTP secret of the AD account's authenticator; the AD login generates the MFA code from it. |
@@ -45,12 +45,12 @@ A login has two parts:
45
45
  This is the same for every user, so you create a **login handler** once per app.
46
46
  - **The user**: a **`TestProfile`** with the account and its auth type.
47
47
 
48
- `getSessionHandler(testProfile, loginHandler)` combines them, and `SessionManager.getOrCreateSession`
49
- gives you a session file: it logs in when there is none, reuses it while it is younger than
48
+ `createSessionHandler(testProfile.authType, testProfile.account, loginHandler)` combines them, and
49
+ `SessionManager.getOrCreateSession` gives you a session file: it logs in when there is none, reuses it while it is younger than
50
50
  `MAX_SESSION_TIME_IN_MINUTES`, and refreshes it after that.
51
51
 
52
52
  ```ts
53
- import { ADLoginHandler, DigidLoginHandler, getSessionHandler, MAX_SESSION_TIME_IN_MINUTES, TestProfile } from 'dh-auth-library';
53
+ import { ADLoginHandler, createSessionHandler, DigidLoginHandler, MAX_SESSION_TIME_IN_MINUTES, TestProfile } from 'dh-auth-library';
54
54
  import { SessionManager } from 'nl-portal-playwright-libraries';
55
55
 
56
56
  // Login handlers, once per app
@@ -69,6 +69,8 @@ export const openFormsDigid = new DigidLoginHandler({
69
69
  // accepts the app's cookie banner after login, so the consent is saved in the session;
70
70
  // left out, no cookie banner is accepted
71
71
  cookieButton: (page) => page.locator('button[class*="cookie-notice__accept"]'),
72
+ // Open Forms' own server session: left out, so parallel workers don't share it (see below)
73
+ excludeCookies: ['openforms_sessionid'],
72
74
  });
73
75
 
74
76
  // Test users only describe the user
@@ -81,7 +83,7 @@ export const digidUser1: TestProfile = {
81
83
  // In a fixture or test: the same user in two apps
82
84
  const klantportaalSession = await SessionManager.getOrCreateSession(
83
85
  browser,
84
- getSessionHandler(digidUser1, klantportaalDigid),
86
+ createSessionHandler(digidUser1.authType, digidUser1.account, klantportaalDigid),
85
87
  MAX_SESSION_TIME_IN_MINUTES,
86
88
  );
87
89
  const context = await browser.newContext({ storageState: klantportaalSession });
@@ -89,17 +91,54 @@ const context = await browser.newContext({ storageState: klantportaalSession });
89
91
 
90
92
  | Login handler | Options |
91
93
  |---|---|
92
- | `ADLoginHandler(targetUrl)` | The app behind the AD login to open, e.g. GZAC. |
93
- | `DigidLoginHandler`, `DigidGemachtigdeLoginHandler` | `loginButton` (required): the app's DigiD button. `startUrl` (optional): defaults to `PORTAL_BASE_URL`. `cookieButton` (optional). |
94
- | eHerkenning handlers | No options yet: they always use the klantportaal (see [Known limitations](#known-limitations)). |
94
+ | `ADLoginHandler(targetUrl, { excludeCookies }?)` | The app behind the AD login to open, e.g. GZAC. The session is saved once that app has opened. |
95
+ | `DigidLoginHandler`, `DigidGemachtigdeLoginHandler` | `loginButton` (required): the app's DigiD button. `startUrl` (optional): defaults to `PORTAL_BASE_URL`. `cookieButton` (optional): the session is saved once the banner is gone. `excludeCookies` (optional). |
96
+ | `EHerkenningLoginHandler`, `EHerkenningBewindvoerderLoginHandler` | The same options as DigiD: `loginButton` (required), `startUrl`, `cookieButton`, `excludeCookies` (optional). |
97
+
98
+ ### Parallel workers: `excludeCookies`
99
+
100
+ All handlers except localhost take `excludeCookies`: the names of cookies to leave out of the saved session. Use it for an app's own server session, such as
101
+ Open Forms' `openforms_sessionid`. Without it, every worker that uses the session file shares
102
+ one server session, and parallel logins break each other (e.g. "Inlogprobleem", or a 403 on
103
+ `POST /api/v2/submissions`). The cookies are left out when the session is created and when it is refreshed.
104
+ Left out, all cookies are saved. Set it on the AD handler too when the AD login opens Open Forms: every
105
+ login, and every test that loads the AD session as `storageState`, starts from that file.
106
+
107
+ The klantportaal doesn't need it: it keeps its tokens in `sessionStorage`, which isn't saved, and has no
108
+ server session cookie of its own.
109
+
110
+ ```ts
111
+ export const openFormsDigid = new DigidLoginHandler({
112
+ startUrl: 'https://openformulieren-zgw.acc.denhaag.nl/<form>/startpagina',
113
+ loginButton: (page) => page.getByRole('link', { name: 'Inloggen met DigiD' }),
114
+ excludeCookies: ['openforms_sessionid'],
115
+ });
116
+ // only when the AD login opens Open Forms (AD_LOGIN_TARGET_URL)
117
+ export const adLogin = new ADLoginHandler('https://openformulieren-zgw.acc.denhaag.nl', {
118
+ excludeCookies: ['openforms_sessionid'],
119
+ });
120
+ ```
95
121
 
96
122
  `loginButton` and `cookieButton` are functions because the page doesn't exist yet when the handler is
97
123
  created. A DigiD handler without `loginButton` is a compile error.
98
124
 
125
+ ### Other ways to create them
126
+
99
127
  `getLoginHandler(authType, options)` creates the same handlers from an auth type, e.g.
100
- `getLoginHandler('ad-session', { startUrl })`, and checks the required options at runtime.
101
- `getSessionHandler(testProfile)` without a handler uses it, which works for auth types that need no
102
- options (eHerkenning, localhost).
128
+ `getLoginHandler('ad-session', { startUrl, excludeCookies })`, and checks the required options at runtime.
129
+
130
+ `getSessionHandler(testProfile, options, loginHandler?)` creates the session handler from options instead of a
131
+ login handler: it calls `getLoginHandler(testProfile.authType, options)`. Pass a `loginHandler` as third
132
+ argument to use that one instead; the options are then ignored.
133
+
134
+ ```ts
135
+ getSessionHandler(digidUser1, {
136
+ loginButton: (page) => page.locator('#oidc-digid'),
137
+ cookieButton: (page) => page.locator('#ppms_cm_agree-to-all'),
138
+ });
139
+ ```
140
+
141
+ The options the auth type needs are checked at runtime, e.g. `getSessionHandler(adUser, { startUrl, excludeCookies })` for AD.
103
142
 
104
143
  The login pages can also be used directly, with the same options:
105
144
 
@@ -121,8 +160,8 @@ await digidLoginPage.loginAndCreateNewSession(digidUser1.account, 'digid-session
121
160
 
122
161
  | 1.x | 2.0 |
123
162
  |---|---|
124
- | `getSessionHandler(digidUser)` | `getSessionHandler(digidUser, new DigidLoginHandler({ loginButton, cookieButton }))` |
125
- | `getSessionHandler(adUser, url)` | `getSessionHandler(adUser, new ADLoginHandler(url))` |
163
+ | `getSessionHandler(digidUser)` | `createSessionHandler(digidUser.authType, digidUser.account, new DigidLoginHandler({ loginButton, cookieButton }))`, or `getSessionHandler(digidUser, { loginButton, cookieButton })` |
164
+ | `getSessionHandler(adUser, url)` | `createSessionHandler(adUser.authType, adUser.account, new ADLoginHandler(url))`, or `getSessionHandler(adUser, { startUrl: url })` |
126
165
  | `getLoginHandler('ad-session', url)` | `getLoginHandler('ad-session', { startUrl: url })` |
127
166
  | DigiD clicked the klantportaal buttons and cookie banner by default | Pass `loginButton` (required) and `cookieButton` |
128
167
  | Dutch method and field names, e.g. `accepteerCookies`, `klikOpDigidLoginOptie`, `*LoginKnop` | English: `acceptCookies`, `clickDigidLoginOption`, `*LoginButton` |
@@ -159,8 +198,6 @@ navigate to the other.
159
198
 
160
199
  ## Known limitations
161
200
 
162
- - eHerkenning doesn't take `LoginOptions` yet: it always starts from `PORTAL_BASE_URL` with the
163
- klantportaal buttons.
164
201
  - `refreshSession` always opens `PORTAL_BASE_URL` to check the session, also for sessions of other
165
202
  apps such as Open Forms. Because the DigiD session is shared (see above), an Open Forms session is
166
203
  checked through the klantportaal.
@@ -168,6 +205,8 @@ navigate to the other.
168
205
  `SESSIONS_DIR` (default `./sessions`); only the folder can be changed. The app is not part of the
169
206
  name, so within one repository two apps that log in the same user use one session file. Because the
170
207
  DigiD session is shared between the klantportaal and Open Forms, that session works for both.
208
+ - The AD login can fail on "Code invoeren" when it runs twice within the same 30 seconds: Microsoft
209
+ accepts each TOTP code only once. A normal run logs in to AD once.
171
210
 
172
211
  ---
173
212
 
@@ -178,8 +217,8 @@ src/
178
217
  ├── auth/
179
218
  │ ├── api/ # getApiTokenFromSession: an API token from a UI session (nl-portal)
180
219
  │ ├── loginhandlers/ # a LoginHandler per login type
181
- │ ├── pages/ # the login pages (AD, DigiD, eHerkenning) and the login overzicht page
182
- │ ├── utils/ # SessionFileHelper (session file names), maskedFill
220
+ │ ├── pages/ # the login pages (AD, DigiD, eHerkenning)
221
+ │ ├── utils/ # SessionFileHelper (session file names), saveSession (excludeCookies), maskedFill
183
222
  │ ├── getLoginHandler.ts, getSessionHandler.ts, sessionHandler.ts
184
223
  ├── constants/ # AuthType and TestProfile
185
224
  tests/ # real-account tests, see below
@@ -197,7 +236,11 @@ through `getSessionHandler` and `SessionManager` (new session, reuse, refresh).
197
236
  described in `tests/data/testProfiles.ts`. `ENV` (`ACC` or `TEST`) picks the environment: the app
198
237
  URLs for it are in `tests/data/environments.ts`. Set `PORTAL_BASE_URL`, `OPEN_FORMS_FORM_URL` or
199
238
  `AD_LOGIN_TARGET_URL` in `.env` only to use other URLs.
200
- 3. Run `pnpm test` or `npm test` (or `npx playwright test --project=sessions` for only the DigiD sessions).
239
+ 3. Run `pnpm test` or `npm test` (or `npx playwright test --project=sessions` for only the DigiD sessions,
240
+ `--project=parallel` for the parallel Open Forms logins).
241
+
242
+ The projects run in this order: `ad` → `sessions` → `openforms-session` → `parallel` (2 workers), because
243
+ they use the same session files. `options` doesn't log in and runs alongside.
201
244
 
202
245
  Variables set in the command take priority over `.env`, e.g. to run against test:
203
246
 
@@ -213,11 +256,13 @@ ENV=TEST pnpm test # or: ENV=TEST npm test
213
256
  |---|---|
214
257
  | `tests/data/testProfiles.ts` | Test data: the test users as `TestProfile`, and the `.env` data each one needs. |
215
258
  | `tests/data/environments.ts` | Test data: the app URLs per environment (`ENV`). |
216
- | `tests/data/apps.ts` | Test data: one login handler per app (AD via GZAC, klantportaal, Open Forms). |
259
+ | `tests/data/apps.ts` | Test data: the apps' URLs, buttons and login handlers (klantportaal, Open Forms with `excludeCookies`). |
217
260
  | `tests/utils/sessions.ts` | Helpers: get, age or remove a session, open an app with a saved session. |
218
261
  | `tests/utils/env.ts` | Read `.env` values, skip a test when they are missing. |
219
- | `tests/ad.setup.ts` | The AD session every other test starts from. |
262
+ | `tests/ad.setup.ts` | The AD session every other test starts from, saved without Open Forms' session cookies. |
220
263
  | `tests/digid.spec.ts` | DigiD sessions for klantportaal and Open Forms. |
264
+ | `tests/openForms.setup.ts` | The Open Forms session the parallel tests share: created and refreshed without `openforms_sessionid`. |
265
+ | `tests/openForms.parallel.spec.ts` | Two workers log in to Open Forms with that one session file at the same time and start the form. |
221
266
  | `tests/getLoginHandler.spec.ts` | Required options, without logging in. |
222
267
 
223
268
  A test whose data is missing in `.env` is skipped with the names of the missing variables.
@@ -9,9 +9,10 @@ import { LoginOptions } from './pages/index';
9
9
  * @param authType type of login
10
10
  * @param options where to start the login, supplied by the consumer of this library.
11
11
  * - `ad-session`: `startUrl` is required - the app behind the firewall to navigate to before logging in.
12
- * - `digid` / `digid_gemachtigde`: `loginButton` is required - the app's DigiD button. `startUrl` defaults
13
- * to `PORTAL_BASE_URL`; `cookieButton` is optional.
14
- * - other auth types: ignored.
12
+ * - `digid` / `digid_gemachtigde` / `eherkenning*`: `loginButton` is required - the app's login button.
13
+ * `startUrl` defaults to `PORTAL_BASE_URL`; `cookieButton` is optional.
14
+ * - all auth types: `excludeCookies` is optional - cookies to leave out of the saved session.
15
+ * - on localhost (`digid`, `eherkenning`): ignored.
15
16
  *
16
17
  * @example
17
18
  * getLoginHandler('digid', {
@@ -3,20 +3,19 @@ import { TestProfile } from '../constants/index';
3
3
  import { LoginOptions } from './pages/index';
4
4
  /**
5
5
  * @param testProfile the test user to log in
6
- * @param loginOptions with the login button and the accept cookiebutton if necessary
7
- * @param loginHandler the login handler for the app the user logs in to, with that app's options, e.g.
8
- * `new DigidLoginHandler({ loginButton, ... })` or `getLoginHandler(authType, options)`. Required for
9
- * auth types that need options (`ad-session`, `digid`, `digid_gemachtigde`); left out, the handler
10
- * for `testProfile.authType` is created without options.
6
+ * @param loginOptions the app's login options, from which the handler for `testProfile.authType` is created
7
+ * with {@link getLoginHandler}: `loginButton` for DigiD and eHerkenning, `startUrl` for `ad-session`, and
8
+ * optionally `cookieButton` and `excludeCookies`. Ignored when `loginHandler` is passed.
9
+ * @param loginHandler a login handler to use instead, e.g. `new DigidLoginHandler({ loginButton, ... })`.
10
+ * With a handler, {@link createSessionHandler}`(testProfile.authType, testProfile.account, loginHandler)`
11
+ * does the same without options.
11
12
  *
12
13
  * @example
13
- * // once per app
14
- * export const openFormsDigid = new DigidLoginHandler({
14
+ * getSessionHandler(digidUser1, {
15
15
  * startUrl: 'https://openformulieren-zgw.acc.denhaag.nl/<form>/startpagina',
16
16
  * loginButton: (page) => page.getByRole('link', { name: 'Inloggen met DigiD' }),
17
17
  * cookieButton: (page) => page.locator('button[class*="cookie-notice__accept"]'),
18
+ * excludeCookies: ['openforms_sessionid'],
18
19
  * });
19
- *
20
- * getSessionHandler(digidUser1, openFormsDigid);
21
20
  */
22
21
  export declare function getSessionHandler(testProfile: TestProfile, loginOptions: LoginOptions, loginHandler?: LoginHandler): import("nl-portal-playwright-libraries").SessionHandler;
@@ -1,6 +1,11 @@
1
1
  import { Page } from '@playwright/test';
2
2
  import { Account } from 'nl-portal-playwright-libraries';
3
3
  export interface LoginHandler {
4
+ /**
5
+ * Names of cookies to leave out of the saved session, also when the session is refreshed.
6
+ * Left out, all cookies are saved.
7
+ */
8
+ readonly excludeCookies?: Array<string>;
4
9
  /**
5
10
  * Log in and persist the resulting session to a storage state file.
6
11
  *
@@ -1,13 +1,18 @@
1
1
  import { Page } from '@playwright/test';
2
2
  import { Account } from 'nl-portal-playwright-libraries';
3
3
  import { LoginHandler } from '../loginHandler';
4
+ import { LoginOptions } from '../pages/index';
4
5
  export declare class ADLoginHandler implements LoginHandler {
5
6
  private readonly targetUrl;
7
+ private readonly options;
6
8
  /**
7
9
  * @param targetUrl URL to navigate to before logging in (the app behind the firewall),
8
10
  * supplied by the consumer of this library
11
+ * @param options optionally the cookies to leave out of the saved session, e.g. the target app's own
12
+ * server session (`openforms_sessionid`), supplied by the consumer of this library
9
13
  */
10
- constructor(targetUrl: string);
14
+ constructor(targetUrl: string, options?: Pick<LoginOptions, 'excludeCookies'>);
15
+ get excludeCookies(): Array<string> | undefined;
11
16
  /**
12
17
  * @param page the Playwright page to perform the login on
13
18
  * @param account login details, supplied by the consumer of this library
@@ -11,6 +11,7 @@ export declare class DigidGemachtigdeLoginHandler implements LoginHandler {
11
11
  * app's cookie banner, supplied by the consumer of this library
12
12
  */
13
13
  constructor(options: LoginOptionsWithButton);
14
+ get excludeCookies(): Array<string> | undefined;
14
15
  /**
15
16
  * @param page the Playwright page to perform the login on
16
17
  * @param account login details, supplied by the consumer of this library
@@ -11,6 +11,7 @@ export declare class DigidLoginHandler implements LoginHandler {
11
11
  * app's cookie banner, supplied by the consumer of this library
12
12
  */
13
13
  constructor(options: LoginOptionsWithButton);
14
+ get excludeCookies(): Array<string> | undefined;
14
15
  /**
15
16
  * @param page the Playwright page to perform the login on
16
17
  * @param account login details, supplied by the consumer of this library
@@ -11,6 +11,7 @@ export declare class EHerkenningBewindvoerderLoginHandler implements LoginHandle
11
11
  * app's cookie banner, supplied by the consumer of this library
12
12
  */
13
13
  constructor(options: LoginOptionsWithButton);
14
+ get excludeCookies(): Array<string> | undefined;
14
15
  /**
15
16
  * @param page the Playwright page to perform the login on
16
17
  * @param account login details, supplied by the consumer of this library
@@ -1,6 +1,6 @@
1
1
  import { Page } from '@playwright/test';
2
2
  import { Account } from 'nl-portal-playwright-libraries';
3
- import { LoginOptionsWithButton } from '../pages';
3
+ import { LoginOptionsWithButton } from '../pages/index';
4
4
  import { LoginHandler } from '../loginHandler';
5
5
  export declare class EHerkenningLoginHandler implements LoginHandler {
6
6
  private readonly options;
@@ -11,6 +11,7 @@ export declare class EHerkenningLoginHandler implements LoginHandler {
11
11
  * app's cookie banner, supplied by the consumer of this library
12
12
  */
13
13
  constructor(options: LoginOptionsWithButton);
14
+ get excludeCookies(): Array<string> | undefined;
14
15
  /**
15
16
  * @param page the Playwright page to perform the login on
16
17
  * @param account login details, supplied by the consumer of this library
@@ -21,6 +21,8 @@ export declare class ADLoginPage extends BasePage {
21
21
  * for switching between environments (e.g. test/acc/prod) when building this URL; this
22
22
  * library does not do that for you.
23
23
  * @param fileName path of the storage state file to write the session to
24
+ * @param excludeCookies names of cookies to leave out of the saved session, e.g. the target app's own
25
+ * server session (`openforms_sessionid`), supplied by the consumer of this library
24
26
  *
25
27
  * @example
26
28
  * // consumer-side lookup, e.g. based on an `ENV` environment variable
@@ -33,7 +35,7 @@ export declare class ADLoginPage extends BasePage {
33
35
  * const env = (process.env.ENV ?? 'test') as keyof typeof TARGET_URL_BY_ENVIRONMENT;
34
36
  * await adLoginPage.loginWithADAccountAndCreateSession(account, TARGET_URL_BY_ENVIRONMENT[env], fileName);
35
37
  */
36
- loginWithADAccountAndCreateSession(account: Account, targetUrl: string, fileName: string): Promise<void>;
38
+ loginWithADAccountAndCreateSession(account: Account, targetUrl: string, fileName: string, excludeCookies?: Array<string>): Promise<void>;
37
39
  /**
38
40
  * Determines the GZAC URL to log in against, based on the current environment.
39
41
  *
@@ -5,7 +5,7 @@ export type LoginOptionsWithButton = LoginOptions & Required<Pick<LoginOptions,
5
5
  export interface LoginOptions {
6
6
  /**
7
7
  * Returns the button that starts the login. A function because the page doesn't exist yet when
8
- * the login handler is created. Required for DigiD; eHerkenning doesn't use these options yet.
8
+ * the login handler is created. Required for DigiD and eHerkenning.
9
9
  */
10
10
  loginButton?: (page: Page) => Locator;
11
11
  /** URL of the page with the login button. Defaults to `PORTAL_BASE_URL`. */
@@ -15,6 +15,12 @@ export interface LoginOptions {
15
15
  * saved in the session. Left out, no cookie banner is accepted.
16
16
  */
17
17
  cookieButton?: (page: Page) => Locator;
18
+ /**
19
+ * Names of cookies to leave out of the saved session, e.g. the app's own server session
20
+ * (`openforms_sessionid`). Otherwise every worker using the session file shares one server
21
+ * session, and parallel logins break each other. Left out, all cookies are saved.
22
+ */
23
+ excludeCookies?: Array<string>;
18
24
  }
19
25
  export declare class BaseLoginPage extends BasePage {
20
26
  constructor(page: Page);
@@ -1,7 +1,7 @@
1
1
  import { Locator, Page } from '@playwright/test';
2
- import { Account, BasePage } from 'nl-portal-playwright-libraries';
3
- import { LoginOptionsWithButton } from './baseLoginPage';
4
- export declare class DigidLoginPage extends BasePage {
2
+ import { Account } from 'nl-portal-playwright-libraries';
3
+ import { BaseLoginPage, LoginOptionsWithButton } from './baseLoginPage';
4
+ export declare class DigidLoginPage extends BaseLoginPage {
5
5
  constructor(page: Page);
6
6
  /**
7
7
  * @param account login details, supplied by the consumer of this library
@@ -17,10 +17,6 @@ export declare class DigidLoginPage extends BasePage {
17
17
  * banner, supplied by the consumer of this library
18
18
  */
19
19
  loginAndCreateNewGemachtigdeSession(account: Account, fileName: string, options: LoginOptionsWithButton): Promise<void>;
20
- /**
21
- * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
22
- */
23
- private acceptCookiesForApp;
24
20
  /**
25
21
  * When there is already an AD session, but for another environment, a special screen asks to
26
22
  * confirm the account before you can continue.
@@ -1,2 +1,3 @@
1
1
  export { SessionFileHelper } from './sessionFileHelper';
2
2
  export { maskedFill } from './maskedFill';
3
+ export { saveSession } from './saveSession';
@@ -0,0 +1,12 @@
1
+ import { BrowserContext } from '@playwright/test';
2
+ /**
3
+ * Writes the context's storage state to `file`, without the cookies in `excludeCookies`
4
+ * (see `LoginOptions.excludeCookies`).
5
+ *
6
+ * Written to a temp file and renamed, so parallel readers never see a half-written file.
7
+ *
8
+ * @param context the browser context to save
9
+ * @param file path of the storage state file to write the session to
10
+ * @param excludeCookies names of the cookies to leave out, supplied by the consumer of this library
11
+ */
12
+ export declare function saveSession(context: BrowserContext, file: string, excludeCookies?: Array<string>): Promise<void>;
package/dist/index.cjs.js CHANGED
@@ -24,10 +24,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  let nl_portal_playwright_libraries = require("nl-portal-playwright-libraries");
25
25
  let _playwright_test = require("@playwright/test");
26
26
  let totp_generator = require("totp-generator");
27
- let node_process = require("node:process");
28
- node_process = __toESM(node_process);
27
+ let node_fs = require("node:fs");
28
+ node_fs = __toESM(node_fs);
29
29
  let node_path = require("node:path");
30
30
  node_path = __toESM(node_path);
31
+ let node_process = require("node:process");
32
+ node_process = __toESM(node_process);
31
33
  //#region src/auth/utils/maskedFill.ts
32
34
  function isEnvValue(value) {
33
35
  return value !== "" && Object.values(process.env).includes(value);
@@ -52,6 +54,26 @@ async function maskedFill(locator, value, propertyName, forceMask = false) {
52
54
  });
53
55
  }
54
56
  //#endregion
57
+ //#region src/auth/utils/saveSession.ts
58
+ /**
59
+ * Writes the context's storage state to `file`, without the cookies in `excludeCookies`
60
+ * (see `LoginOptions.excludeCookies`).
61
+ *
62
+ * Written to a temp file and renamed, so parallel readers never see a half-written file.
63
+ *
64
+ * @param context the browser context to save
65
+ * @param file path of the storage state file to write the session to
66
+ * @param excludeCookies names of the cookies to leave out, supplied by the consumer of this library
67
+ */
68
+ async function saveSession(context, file, excludeCookies = []) {
69
+ const state = await context.storageState();
70
+ state.cookies = state.cookies.filter((cookie) => !excludeCookies.includes(cookie.name));
71
+ node_fs.default.mkdirSync(node_path.default.dirname(file), { recursive: true });
72
+ const tmp = `${file}.${node_process.default.pid}.tmp`;
73
+ node_fs.default.writeFileSync(tmp, JSON.stringify(state, null, 2));
74
+ node_fs.default.renameSync(tmp, file);
75
+ }
76
+ //#endregion
55
77
  //#region src/auth/pages/adLoginPage.ts
56
78
  var gzacUrlProd = "https://alg-zgw.denhaag.nl";
57
79
  var gzacUrlAcp = "https://alg-zgw.acc.denhaag.nl";
@@ -92,6 +114,8 @@ var ADLoginPage = class ADLoginPage extends nl_portal_playwright_libraries.BaseP
92
114
  * for switching between environments (e.g. test/acc/prod) when building this URL; this
93
115
  * library does not do that for you.
94
116
  * @param fileName path of the storage state file to write the session to
117
+ * @param excludeCookies names of cookies to leave out of the saved session, e.g. the target app's own
118
+ * server session (`openforms_sessionid`), supplied by the consumer of this library
95
119
  *
96
120
  * @example
97
121
  * // consumer-side lookup, e.g. based on an `ENV` environment variable
@@ -104,7 +128,7 @@ var ADLoginPage = class ADLoginPage extends nl_portal_playwright_libraries.BaseP
104
128
  * const env = (process.env.ENV ?? 'test') as keyof typeof TARGET_URL_BY_ENVIRONMENT;
105
129
  * await adLoginPage.loginWithADAccountAndCreateSession(account, TARGET_URL_BY_ENVIRONMENT[env], fileName);
106
130
  */
107
- async loginWithADAccountAndCreateSession(account, targetUrl, fileName) {
131
+ async loginWithADAccountAndCreateSession(account, targetUrl, fileName, excludeCookies) {
108
132
  const adLoginPage = new ADLoginPage(this.page);
109
133
  let targetOrigin;
110
134
  try {
@@ -151,11 +175,26 @@ var ADLoginPage = class ADLoginPage extends nl_portal_playwright_libraries.BaseP
151
175
  const token = await totp_generator.TOTP.generate(`${process.env.AD_SECRET}`);
152
176
  await maskedFill(adLoginPage.codeInput, token.otp, "otp", true);
153
177
  await adLoginPage.verifyInput.click();
154
- await adLoginPage.page.waitForTimeout(5e3);
178
+ });
179
+ await _playwright_test.test.step("Skip the Microsoft security prompt and wait for the target app", async () => {
180
+ const notNow = this.page.getByRole("link", { name: /^(Niet nu|Not now)$/ }).or(this.page.getByRole("button", { name: /^(Niet nu|Not now)$/ })).first();
181
+ const onTargetApp = (url) => url.origin === targetOrigin;
182
+ await Promise.race([this.page.waitForURL(onTargetApp, {
183
+ waitUntil: "commit",
184
+ timeout: 6e4
185
+ }), notNow.waitFor({ timeout: 6e4 })]).catch(() => {});
186
+ if (await notNow.isVisible().catch(() => false)) await notNow.click();
187
+ try {
188
+ await this.page.waitForURL(onTargetApp, { timeout: 6e4 });
189
+ } catch {
190
+ const heading = await this.page.getByRole("heading").first().textContent({ timeout: 1e3 }).catch(() => "");
191
+ throw new Error(`AD login didn't return to ${targetOrigin}: stuck on ${this.page.url()} ("${heading?.trim()}")`);
192
+ }
193
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
155
194
  });
156
195
  }
157
196
  await _playwright_test.test.step("Save session state", async () => {
158
- await adLoginPage.page.context().storageState({ path: fileName });
197
+ await saveSession(adLoginPage.page.context(), fileName, excludeCookies);
159
198
  });
160
199
  }
161
200
  /**
@@ -181,12 +220,19 @@ var ADLoginPage = class ADLoginPage extends nl_portal_playwright_libraries.BaseP
181
220
  //#region src/auth/loginhandlers/adLoginHandler.ts
182
221
  var ADLoginHandler = class {
183
222
  targetUrl;
223
+ options;
184
224
  /**
185
225
  * @param targetUrl URL to navigate to before logging in (the app behind the firewall),
186
226
  * supplied by the consumer of this library
227
+ * @param options optionally the cookies to leave out of the saved session, e.g. the target app's own
228
+ * server session (`openforms_sessionid`), supplied by the consumer of this library
187
229
  */
188
- constructor(targetUrl) {
230
+ constructor(targetUrl, options = {}) {
189
231
  this.targetUrl = targetUrl;
232
+ this.options = options;
233
+ }
234
+ get excludeCookies() {
235
+ return this.options.excludeCookies;
190
236
  }
191
237
  /**
192
238
  * @param page the Playwright page to perform the login on
@@ -194,7 +240,7 @@ var ADLoginHandler = class {
194
240
  * @param file path of the storage state file to write the session to
195
241
  */
196
242
  async loginAndCreateSessionStorage(page, account, file) {
197
- await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file);
243
+ await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file, this.excludeCookies);
198
244
  }
199
245
  };
200
246
  //#endregion
@@ -263,8 +309,26 @@ var SessionFileHelper = class {
263
309
  }
264
310
  };
265
311
  //#endregion
312
+ //#region src/auth/pages/baseLoginPage.ts
313
+ var BaseLoginPage = class extends nl_portal_playwright_libraries.BasePage {
314
+ constructor(page) {
315
+ super(page);
316
+ }
317
+ /**
318
+ * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
319
+ */
320
+ async acceptCookiesForApp(options) {
321
+ if (options.cookieButton) try {
322
+ const cookieButton = options.cookieButton(this.page);
323
+ await cookieButton.click();
324
+ await cookieButton.waitFor({ state: "hidden" });
325
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
326
+ } catch (_noShowError) {}
327
+ }
328
+ };
329
+ //#endregion
266
330
  //#region src/auth/pages/digidLoginPage.ts
267
- var DigidLoginPage = class extends nl_portal_playwright_libraries.BasePage {
331
+ var DigidLoginPage = class extends BaseLoginPage {
268
332
  constructor(page) {
269
333
  super(page);
270
334
  }
@@ -291,7 +355,7 @@ var DigidLoginPage = class extends nl_portal_playwright_libraries.BasePage {
291
355
  await this.loginWithDigid(account);
292
356
  await this.acceptCookiesForApp(options);
293
357
  }
294
- await this.page.context().storageState({ path: fileName });
358
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
295
359
  });
296
360
  }
297
361
  /**
@@ -314,16 +378,10 @@ var DigidLoginPage = class extends nl_portal_playwright_libraries.BasePage {
314
378
  }
315
379
  await this.loginWithDigid(account, true);
316
380
  await this.acceptCookiesForApp(options);
317
- await this.page.context().storageState({ path: fileName });
381
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
318
382
  });
319
383
  }
320
384
  /**
321
- * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
322
- */
323
- async acceptCookiesForApp(options) {
324
- if (options.cookieButton) await options.cookieButton(this.page).click();
325
- }
326
- /**
327
385
  * When there is already an AD session, but for another environment, a special screen asks to
328
386
  * confirm the account before you can continue.
329
387
  */
@@ -376,6 +434,9 @@ var DigidGemachtigdeLoginHandler = class {
376
434
  constructor(options) {
377
435
  this.options = options;
378
436
  }
437
+ get excludeCookies() {
438
+ return this.options.excludeCookies;
439
+ }
379
440
  /**
380
441
  * @param page the Playwright page to perform the login on
381
442
  * @param account login details, supplied by the consumer of this library
@@ -386,19 +447,6 @@ var DigidGemachtigdeLoginHandler = class {
386
447
  }
387
448
  };
388
449
  //#endregion
389
- //#region src/auth/pages/baseLoginPage.ts
390
- var BaseLoginPage = class extends nl_portal_playwright_libraries.BasePage {
391
- constructor(page) {
392
- super(page);
393
- }
394
- /**
395
- * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
396
- */
397
- async acceptCookiesForApp(options) {
398
- if (options.cookieButton) await options.cookieButton(this.page).click();
399
- }
400
- };
401
- //#endregion
402
450
  //#region src/auth/pages/eHerkenningLoginPage.ts
403
451
  var EHerkenningLoginPage = class extends BaseLoginPage {
404
452
  dropdownSelectIdentityProvider;
@@ -453,7 +501,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
453
501
  await this.loginButton.click();
454
502
  }
455
503
  await this.loginWithEHerkenning(account, options);
456
- await this.page.context().storageState({ path: fileName });
504
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
457
505
  });
458
506
  }
459
507
  /**
@@ -485,7 +533,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
485
533
  await loginButton.click();
486
534
  }
487
535
  await this.loginWithEHerkenningVestiging(account, options);
488
- await this.page.context().storageState({ path: fileName });
536
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
489
537
  });
490
538
  }
491
539
  /**
@@ -530,7 +578,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
530
578
  await this.acceptCookiesForApp(options);
531
579
  });
532
580
  if (file) await _playwright_test.test.step("Save session state", async () => {
533
- await this.page.context().storageState({ path: file });
581
+ await saveSession(this.page.context(), file, options.excludeCookies);
534
582
  });
535
583
  }
536
584
  };
@@ -547,6 +595,9 @@ var DigidLoginHandler = class {
547
595
  constructor(options) {
548
596
  this.options = options;
549
597
  }
598
+ get excludeCookies() {
599
+ return this.options.excludeCookies;
600
+ }
550
601
  /**
551
602
  * @param page the Playwright page to perform the login on
552
603
  * @param account login details, supplied by the consumer of this library
@@ -569,6 +620,9 @@ var EHerkenningBewindvoerderLoginHandler = class {
569
620
  constructor(options) {
570
621
  this.options = options;
571
622
  }
623
+ get excludeCookies() {
624
+ return this.options.excludeCookies;
625
+ }
572
626
  /**
573
627
  * @param page the Playwright page to perform the login on
574
628
  * @param account login details, supplied by the consumer of this library
@@ -591,6 +645,9 @@ var EHerkenningLoginHandler = class {
591
645
  constructor(options) {
592
646
  this.options = options;
593
647
  }
648
+ get excludeCookies() {
649
+ return this.options.excludeCookies;
650
+ }
594
651
  /**
595
652
  * @param page the Playwright page to perform the login on
596
653
  * @param account login details, supplied by the consumer of this library
@@ -622,9 +679,10 @@ var LocalhostLoginHandler = class {
622
679
  * @param authType type of login
623
680
  * @param options where to start the login, supplied by the consumer of this library.
624
681
  * - `ad-session`: `startUrl` is required - the app behind the firewall to navigate to before logging in.
625
- * - `digid` / `digid_gemachtigde`: `loginButton` is required - the app's DigiD button. `startUrl` defaults
626
- * to `PORTAL_BASE_URL`; `cookieButton` is optional.
627
- * - other auth types: ignored.
682
+ * - `digid` / `digid_gemachtigde` / `eherkenning*`: `loginButton` is required - the app's login button.
683
+ * `startUrl` defaults to `PORTAL_BASE_URL`; `cookieButton` is optional.
684
+ * - all auth types: `excludeCookies` is optional - cookies to leave out of the saved session.
685
+ * - on localhost (`digid`, `eherkenning`): ignored.
628
686
  *
629
687
  * @example
630
688
  * getLoginHandler('digid', {
@@ -645,7 +703,7 @@ function getLoginHandler(authType, options = {}) {
645
703
  case "eherkenning_bewindvoerder": return new EHerkenningBewindvoerderLoginHandler(loginOptions(authType, options));
646
704
  case "ad-session":
647
705
  if (!options.startUrl) throw new Error("startUrl is required when authType is 'ad-session'");
648
- return new ADLoginHandler(options.startUrl);
706
+ return new ADLoginHandler(options.startUrl, { excludeCookies: options.excludeCookies });
649
707
  default: throw new Error(`Unsupported auth type: ${authType}. If needed please create a new LoginHandler and register it here in getLoginHandler().`);
650
708
  }
651
709
  }
@@ -729,7 +787,7 @@ function createSessionHandler(authType, account, loginHandler) {
729
787
  }
730
788
  } else {
731
789
  console.log(`Current session was still valid and will be refreshed now: ${file}`);
732
- await page.context().storageState({ path: file });
790
+ await saveSession(page.context(), file, loginHandler.excludeCookies);
733
791
  }
734
792
  await page.close();
735
793
  }
@@ -792,21 +850,20 @@ function getApiTokenFromSession(baseTest, handler) {
792
850
  //#region src/auth/getSessionHandler.ts
793
851
  /**
794
852
  * @param testProfile the test user to log in
795
- * @param loginOptions with the login button and the accept cookiebutton if necessary
796
- * @param loginHandler the login handler for the app the user logs in to, with that app's options, e.g.
797
- * `new DigidLoginHandler({ loginButton, ... })` or `getLoginHandler(authType, options)`. Required for
798
- * auth types that need options (`ad-session`, `digid`, `digid_gemachtigde`); left out, the handler
799
- * for `testProfile.authType` is created without options.
853
+ * @param loginOptions the app's login options, from which the handler for `testProfile.authType` is created
854
+ * with {@link getLoginHandler}: `loginButton` for DigiD and eHerkenning, `startUrl` for `ad-session`, and
855
+ * optionally `cookieButton` and `excludeCookies`. Ignored when `loginHandler` is passed.
856
+ * @param loginHandler a login handler to use instead, e.g. `new DigidLoginHandler({ loginButton, ... })`.
857
+ * With a handler, {@link createSessionHandler}`(testProfile.authType, testProfile.account, loginHandler)`
858
+ * does the same without options.
800
859
  *
801
860
  * @example
802
- * // once per app
803
- * export const openFormsDigid = new DigidLoginHandler({
861
+ * getSessionHandler(digidUser1, {
804
862
  * startUrl: 'https://openformulieren-zgw.acc.denhaag.nl/<form>/startpagina',
805
863
  * loginButton: (page) => page.getByRole('link', { name: 'Inloggen met DigiD' }),
806
864
  * cookieButton: (page) => page.locator('button[class*="cookie-notice__accept"]'),
865
+ * excludeCookies: ['openforms_sessionid'],
807
866
  * });
808
- *
809
- * getSessionHandler(digidUser1, openFormsDigid);
810
867
  */
811
868
  function getSessionHandler(testProfile, loginOptions, loginHandler) {
812
869
  return createSessionHandler(testProfile.authType, testProfile.account, loginHandler ?? getLoginHandler(testProfile.authType, loginOptions));
@@ -829,3 +886,4 @@ exports.getApiTokenFromSession = getApiTokenFromSession;
829
886
  exports.getLoginHandler = getLoginHandler;
830
887
  exports.getSessionHandler = getSessionHandler;
831
888
  exports.maskedFill = maskedFill;
889
+ exports.saveSession = saveSession;
package/dist/index.es.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { BasePage, LocalLoginPage, SessionManager, Url, getUrl, isRunningOnLocalhost, urls } from "nl-portal-playwright-libraries";
2
2
  import { test } from "@playwright/test";
3
3
  import { TOTP } from "totp-generator";
4
+ import fs from "node:fs";
5
+ import * as path$1 from "node:path";
6
+ import path from "node:path";
4
7
  import * as process$2 from "node:process";
5
8
  import process$1 from "node:process";
6
- import * as path from "node:path";
7
9
  //#region src/auth/utils/maskedFill.ts
8
10
  function isEnvValue(value) {
9
11
  return value !== "" && Object.values(process.env).includes(value);
@@ -28,6 +30,26 @@ async function maskedFill(locator, value, propertyName, forceMask = false) {
28
30
  });
29
31
  }
30
32
  //#endregion
33
+ //#region src/auth/utils/saveSession.ts
34
+ /**
35
+ * Writes the context's storage state to `file`, without the cookies in `excludeCookies`
36
+ * (see `LoginOptions.excludeCookies`).
37
+ *
38
+ * Written to a temp file and renamed, so parallel readers never see a half-written file.
39
+ *
40
+ * @param context the browser context to save
41
+ * @param file path of the storage state file to write the session to
42
+ * @param excludeCookies names of the cookies to leave out, supplied by the consumer of this library
43
+ */
44
+ async function saveSession(context, file, excludeCookies = []) {
45
+ const state = await context.storageState();
46
+ state.cookies = state.cookies.filter((cookie) => !excludeCookies.includes(cookie.name));
47
+ fs.mkdirSync(path.dirname(file), { recursive: true });
48
+ const tmp = `${file}.${process$1.pid}.tmp`;
49
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2));
50
+ fs.renameSync(tmp, file);
51
+ }
52
+ //#endregion
31
53
  //#region src/auth/pages/adLoginPage.ts
32
54
  var gzacUrlProd = "https://alg-zgw.denhaag.nl";
33
55
  var gzacUrlAcp = "https://alg-zgw.acc.denhaag.nl";
@@ -68,6 +90,8 @@ var ADLoginPage = class ADLoginPage extends BasePage {
68
90
  * for switching between environments (e.g. test/acc/prod) when building this URL; this
69
91
  * library does not do that for you.
70
92
  * @param fileName path of the storage state file to write the session to
93
+ * @param excludeCookies names of cookies to leave out of the saved session, e.g. the target app's own
94
+ * server session (`openforms_sessionid`), supplied by the consumer of this library
71
95
  *
72
96
  * @example
73
97
  * // consumer-side lookup, e.g. based on an `ENV` environment variable
@@ -80,7 +104,7 @@ var ADLoginPage = class ADLoginPage extends BasePage {
80
104
  * const env = (process.env.ENV ?? 'test') as keyof typeof TARGET_URL_BY_ENVIRONMENT;
81
105
  * await adLoginPage.loginWithADAccountAndCreateSession(account, TARGET_URL_BY_ENVIRONMENT[env], fileName);
82
106
  */
83
- async loginWithADAccountAndCreateSession(account, targetUrl, fileName) {
107
+ async loginWithADAccountAndCreateSession(account, targetUrl, fileName, excludeCookies) {
84
108
  const adLoginPage = new ADLoginPage(this.page);
85
109
  let targetOrigin;
86
110
  try {
@@ -127,11 +151,26 @@ var ADLoginPage = class ADLoginPage extends BasePage {
127
151
  const token = await TOTP.generate(`${process.env.AD_SECRET}`);
128
152
  await maskedFill(adLoginPage.codeInput, token.otp, "otp", true);
129
153
  await adLoginPage.verifyInput.click();
130
- await adLoginPage.page.waitForTimeout(5e3);
154
+ });
155
+ await test.step("Skip the Microsoft security prompt and wait for the target app", async () => {
156
+ const notNow = this.page.getByRole("link", { name: /^(Niet nu|Not now)$/ }).or(this.page.getByRole("button", { name: /^(Niet nu|Not now)$/ })).first();
157
+ const onTargetApp = (url) => url.origin === targetOrigin;
158
+ await Promise.race([this.page.waitForURL(onTargetApp, {
159
+ waitUntil: "commit",
160
+ timeout: 6e4
161
+ }), notNow.waitFor({ timeout: 6e4 })]).catch(() => {});
162
+ if (await notNow.isVisible().catch(() => false)) await notNow.click();
163
+ try {
164
+ await this.page.waitForURL(onTargetApp, { timeout: 6e4 });
165
+ } catch {
166
+ const heading = await this.page.getByRole("heading").first().textContent({ timeout: 1e3 }).catch(() => "");
167
+ throw new Error(`AD login didn't return to ${targetOrigin}: stuck on ${this.page.url()} ("${heading?.trim()}")`);
168
+ }
169
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
131
170
  });
132
171
  }
133
172
  await test.step("Save session state", async () => {
134
- await adLoginPage.page.context().storageState({ path: fileName });
173
+ await saveSession(adLoginPage.page.context(), fileName, excludeCookies);
135
174
  });
136
175
  }
137
176
  /**
@@ -157,12 +196,19 @@ var ADLoginPage = class ADLoginPage extends BasePage {
157
196
  //#region src/auth/loginhandlers/adLoginHandler.ts
158
197
  var ADLoginHandler = class {
159
198
  targetUrl;
199
+ options;
160
200
  /**
161
201
  * @param targetUrl URL to navigate to before logging in (the app behind the firewall),
162
202
  * supplied by the consumer of this library
203
+ * @param options optionally the cookies to leave out of the saved session, e.g. the target app's own
204
+ * server session (`openforms_sessionid`), supplied by the consumer of this library
163
205
  */
164
- constructor(targetUrl) {
206
+ constructor(targetUrl, options = {}) {
165
207
  this.targetUrl = targetUrl;
208
+ this.options = options;
209
+ }
210
+ get excludeCookies() {
211
+ return this.options.excludeCookies;
166
212
  }
167
213
  /**
168
214
  * @param page the Playwright page to perform the login on
@@ -170,12 +216,12 @@ var ADLoginHandler = class {
170
216
  * @param file path of the storage state file to write the session to
171
217
  */
172
218
  async loginAndCreateSessionStorage(page, account, file) {
173
- await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file);
219
+ await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file, this.excludeCookies);
174
220
  }
175
221
  };
176
222
  //#endregion
177
223
  //#region src/auth/utils/sessionFileHelper.ts
178
- var sessionsDir = process$2.env.SESSIONS_DIR ?? path.resolve(process$2.cwd(), "sessions");
224
+ var sessionsDir = process$2.env.SESSIONS_DIR ?? path$1.resolve(process$2.cwd(), "sessions");
179
225
  var environment = process$2.env.ENV ?? "test";
180
226
  /**
181
227
  * Easy way to create the filenames for the sessions
@@ -186,61 +232,79 @@ var SessionFileHelper = class {
186
232
  * @param account login details, supplied by the consumer of this library; only `username` is used
187
233
  */
188
234
  static getLocalhostFileName(browser, account) {
189
- return path.join(sessionsDir, `${browser.browserType().name()}-${environment}-${account.username}.json`);
235
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-${environment}-${account.username}.json`);
190
236
  }
191
237
  /**
192
238
  * @param browser the browser instance the session file name is based on
193
239
  * @param account login details, supplied by the consumer of this library; only `username` is used
194
240
  */
195
241
  static getLocalhostFileNameBedrijf(browser, account) {
196
- return path.join(sessionsDir, `${browser.browserType().name()}-${environment}-${account.username}.json`);
242
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-${environment}-${account.username}.json`);
197
243
  }
198
244
  /**
199
245
  * @param browser the browser instance the session file name is based on
200
246
  * @param account login details, supplied by the consumer of this library; only `username` is used
201
247
  */
202
248
  static getDigidFileName(browser, account) {
203
- return path.join(sessionsDir, `${browser.browserType().name()}-digid-${environment}-${account.username}.json`);
249
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-digid-${environment}-${account.username}.json`);
204
250
  }
205
251
  /**
206
252
  * @param browser the browser instance the session file name is based on
207
253
  * @param account login details, supplied by the consumer of this library; only `username` is used
208
254
  */
209
255
  static getDigidGemachtigdeFileName(browser, account) {
210
- return path.join(sessionsDir, `${browser.browserType().name()}-digid-gemachtigde-${environment}-${account.username}.json`);
256
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-digid-gemachtigde-${environment}-${account.username}.json`);
211
257
  }
212
258
  /**
213
259
  * @param browser the browser instance the session file name is based on
214
260
  * @param account login details, supplied by the consumer of this library; only `username` is used
215
261
  */
216
262
  static getEHerkenningFileName(browser, account) {
217
- return path.join(sessionsDir, `${browser.browserType().name()}-eherkenning-${environment}-${account.username}.json`);
263
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-eherkenning-${environment}-${account.username}.json`);
218
264
  }
219
265
  /**
220
266
  * @param browser the browser instance the session file name is based on
221
267
  * @param account login details, supplied by the consumer of this library; only `username` is used
222
268
  */
223
269
  static getEHerkenningVestigingFileName(browser, account) {
224
- return path.join(sessionsDir, `${browser.browserType().name()}-eherkenning-vestiging-${environment}-${account.username}.json`);
270
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-eherkenning-vestiging-${environment}-${account.username}.json`);
225
271
  }
226
272
  /**
227
273
  * @param browser the browser instance the session file name is based on
228
274
  * @param account login details, supplied by the consumer of this library; only `username` is used
229
275
  */
230
276
  static getEHerkenningBewindvoerderFileName(browser, account) {
231
- return path.join(sessionsDir, `${browser.browserType().name()}-eherkenning-bewindvoerder-${environment}-${account.username}.json`);
277
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-eherkenning-bewindvoerder-${environment}-${account.username}.json`);
232
278
  }
233
279
  /**
234
280
  * @param browser the browser instance the session file name is based on
235
281
  * @param account login details, supplied by the consumer of this library; only `username` is used
236
282
  */
237
283
  static getADFileName(browser, account) {
238
- return path.join(sessionsDir, `${browser.browserType().name()}-ad-${environment}-${account.username}.json`);
284
+ return path$1.join(sessionsDir, `${browser.browserType().name()}-ad-${environment}-${account.username}.json`);
285
+ }
286
+ };
287
+ //#endregion
288
+ //#region src/auth/pages/baseLoginPage.ts
289
+ var BaseLoginPage = class extends BasePage {
290
+ constructor(page) {
291
+ super(page);
292
+ }
293
+ /**
294
+ * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
295
+ */
296
+ async acceptCookiesForApp(options) {
297
+ if (options.cookieButton) try {
298
+ const cookieButton = options.cookieButton(this.page);
299
+ await cookieButton.click();
300
+ await cookieButton.waitFor({ state: "hidden" });
301
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
302
+ } catch (_noShowError) {}
239
303
  }
240
304
  };
241
305
  //#endregion
242
306
  //#region src/auth/pages/digidLoginPage.ts
243
- var DigidLoginPage = class extends BasePage {
307
+ var DigidLoginPage = class extends BaseLoginPage {
244
308
  constructor(page) {
245
309
  super(page);
246
310
  }
@@ -267,7 +331,7 @@ var DigidLoginPage = class extends BasePage {
267
331
  await this.loginWithDigid(account);
268
332
  await this.acceptCookiesForApp(options);
269
333
  }
270
- await this.page.context().storageState({ path: fileName });
334
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
271
335
  });
272
336
  }
273
337
  /**
@@ -290,16 +354,10 @@ var DigidLoginPage = class extends BasePage {
290
354
  }
291
355
  await this.loginWithDigid(account, true);
292
356
  await this.acceptCookiesForApp(options);
293
- await this.page.context().storageState({ path: fileName });
357
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
294
358
  });
295
359
  }
296
360
  /**
297
- * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
298
- */
299
- async acceptCookiesForApp(options) {
300
- if (options.cookieButton) await options.cookieButton(this.page).click();
301
- }
302
- /**
303
361
  * When there is already an AD session, but for another environment, a special screen asks to
304
362
  * confirm the account before you can continue.
305
363
  */
@@ -352,6 +410,9 @@ var DigidGemachtigdeLoginHandler = class {
352
410
  constructor(options) {
353
411
  this.options = options;
354
412
  }
413
+ get excludeCookies() {
414
+ return this.options.excludeCookies;
415
+ }
355
416
  /**
356
417
  * @param page the Playwright page to perform the login on
357
418
  * @param account login details, supplied by the consumer of this library
@@ -362,19 +423,6 @@ var DigidGemachtigdeLoginHandler = class {
362
423
  }
363
424
  };
364
425
  //#endregion
365
- //#region src/auth/pages/baseLoginPage.ts
366
- var BaseLoginPage = class extends BasePage {
367
- constructor(page) {
368
- super(page);
369
- }
370
- /**
371
- * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
372
- */
373
- async acceptCookiesForApp(options) {
374
- if (options.cookieButton) await options.cookieButton(this.page).click();
375
- }
376
- };
377
- //#endregion
378
426
  //#region src/auth/pages/eHerkenningLoginPage.ts
379
427
  var EHerkenningLoginPage = class extends BaseLoginPage {
380
428
  dropdownSelectIdentityProvider;
@@ -429,7 +477,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
429
477
  await this.loginButton.click();
430
478
  }
431
479
  await this.loginWithEHerkenning(account, options);
432
- await this.page.context().storageState({ path: fileName });
480
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
433
481
  });
434
482
  }
435
483
  /**
@@ -461,7 +509,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
461
509
  await loginButton.click();
462
510
  }
463
511
  await this.loginWithEHerkenningVestiging(account, options);
464
- await this.page.context().storageState({ path: fileName });
512
+ await saveSession(this.page.context(), fileName, options.excludeCookies);
465
513
  });
466
514
  }
467
515
  /**
@@ -506,7 +554,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
506
554
  await this.acceptCookiesForApp(options);
507
555
  });
508
556
  if (file) await test.step("Save session state", async () => {
509
- await this.page.context().storageState({ path: file });
557
+ await saveSession(this.page.context(), file, options.excludeCookies);
510
558
  });
511
559
  }
512
560
  };
@@ -523,6 +571,9 @@ var DigidLoginHandler = class {
523
571
  constructor(options) {
524
572
  this.options = options;
525
573
  }
574
+ get excludeCookies() {
575
+ return this.options.excludeCookies;
576
+ }
526
577
  /**
527
578
  * @param page the Playwright page to perform the login on
528
579
  * @param account login details, supplied by the consumer of this library
@@ -545,6 +596,9 @@ var EHerkenningBewindvoerderLoginHandler = class {
545
596
  constructor(options) {
546
597
  this.options = options;
547
598
  }
599
+ get excludeCookies() {
600
+ return this.options.excludeCookies;
601
+ }
548
602
  /**
549
603
  * @param page the Playwright page to perform the login on
550
604
  * @param account login details, supplied by the consumer of this library
@@ -567,6 +621,9 @@ var EHerkenningLoginHandler = class {
567
621
  constructor(options) {
568
622
  this.options = options;
569
623
  }
624
+ get excludeCookies() {
625
+ return this.options.excludeCookies;
626
+ }
570
627
  /**
571
628
  * @param page the Playwright page to perform the login on
572
629
  * @param account login details, supplied by the consumer of this library
@@ -598,9 +655,10 @@ var LocalhostLoginHandler = class {
598
655
  * @param authType type of login
599
656
  * @param options where to start the login, supplied by the consumer of this library.
600
657
  * - `ad-session`: `startUrl` is required - the app behind the firewall to navigate to before logging in.
601
- * - `digid` / `digid_gemachtigde`: `loginButton` is required - the app's DigiD button. `startUrl` defaults
602
- * to `PORTAL_BASE_URL`; `cookieButton` is optional.
603
- * - other auth types: ignored.
658
+ * - `digid` / `digid_gemachtigde` / `eherkenning*`: `loginButton` is required - the app's login button.
659
+ * `startUrl` defaults to `PORTAL_BASE_URL`; `cookieButton` is optional.
660
+ * - all auth types: `excludeCookies` is optional - cookies to leave out of the saved session.
661
+ * - on localhost (`digid`, `eherkenning`): ignored.
604
662
  *
605
663
  * @example
606
664
  * getLoginHandler('digid', {
@@ -621,7 +679,7 @@ function getLoginHandler(authType, options = {}) {
621
679
  case "eherkenning_bewindvoerder": return new EHerkenningBewindvoerderLoginHandler(loginOptions(authType, options));
622
680
  case "ad-session":
623
681
  if (!options.startUrl) throw new Error("startUrl is required when authType is 'ad-session'");
624
- return new ADLoginHandler(options.startUrl);
682
+ return new ADLoginHandler(options.startUrl, { excludeCookies: options.excludeCookies });
625
683
  default: throw new Error(`Unsupported auth type: ${authType}. If needed please create a new LoginHandler and register it here in getLoginHandler().`);
626
684
  }
627
685
  }
@@ -705,7 +763,7 @@ function createSessionHandler(authType, account, loginHandler) {
705
763
  }
706
764
  } else {
707
765
  console.log(`Current session was still valid and will be refreshed now: ${file}`);
708
- await page.context().storageState({ path: file });
766
+ await saveSession(page.context(), file, loginHandler.excludeCookies);
709
767
  }
710
768
  await page.close();
711
769
  }
@@ -768,24 +826,23 @@ function getApiTokenFromSession(baseTest, handler) {
768
826
  //#region src/auth/getSessionHandler.ts
769
827
  /**
770
828
  * @param testProfile the test user to log in
771
- * @param loginOptions with the login button and the accept cookiebutton if necessary
772
- * @param loginHandler the login handler for the app the user logs in to, with that app's options, e.g.
773
- * `new DigidLoginHandler({ loginButton, ... })` or `getLoginHandler(authType, options)`. Required for
774
- * auth types that need options (`ad-session`, `digid`, `digid_gemachtigde`); left out, the handler
775
- * for `testProfile.authType` is created without options.
829
+ * @param loginOptions the app's login options, from which the handler for `testProfile.authType` is created
830
+ * with {@link getLoginHandler}: `loginButton` for DigiD and eHerkenning, `startUrl` for `ad-session`, and
831
+ * optionally `cookieButton` and `excludeCookies`. Ignored when `loginHandler` is passed.
832
+ * @param loginHandler a login handler to use instead, e.g. `new DigidLoginHandler({ loginButton, ... })`.
833
+ * With a handler, {@link createSessionHandler}`(testProfile.authType, testProfile.account, loginHandler)`
834
+ * does the same without options.
776
835
  *
777
836
  * @example
778
- * // once per app
779
- * export const openFormsDigid = new DigidLoginHandler({
837
+ * getSessionHandler(digidUser1, {
780
838
  * startUrl: 'https://openformulieren-zgw.acc.denhaag.nl/<form>/startpagina',
781
839
  * loginButton: (page) => page.getByRole('link', { name: 'Inloggen met DigiD' }),
782
840
  * cookieButton: (page) => page.locator('button[class*="cookie-notice__accept"]'),
841
+ * excludeCookies: ['openforms_sessionid'],
783
842
  * });
784
- *
785
- * getSessionHandler(digidUser1, openFormsDigid);
786
843
  */
787
844
  function getSessionHandler(testProfile, loginOptions, loginHandler) {
788
845
  return createSessionHandler(testProfile.authType, testProfile.account, loginHandler ?? getLoginHandler(testProfile.authType, loginOptions));
789
846
  }
790
847
  //#endregion
791
- export { ADLoginHandler, ADLoginPage, BaseLoginPage, DigidGemachtigdeLoginHandler, DigidLoginHandler, DigidLoginPage, EHerkenningBewindvoerderLoginHandler, EHerkenningLoginHandler, EHerkenningLoginPage, LocalhostLoginHandler, MAX_SESSION_TIME_IN_MINUTES, SessionFileHelper, createSessionHandler, getApiTokenFromSession, getLoginHandler, getSessionHandler, maskedFill };
848
+ export { ADLoginHandler, ADLoginPage, BaseLoginPage, DigidGemachtigdeLoginHandler, DigidLoginHandler, DigidLoginPage, EHerkenningBewindvoerderLoginHandler, EHerkenningLoginHandler, EHerkenningLoginPage, LocalhostLoginHandler, MAX_SESSION_TIME_IN_MINUTES, SessionFileHelper, createSessionHandler, getApiTokenFromSession, getLoginHandler, getSessionHandler, maskedFill, saveSession };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dh-auth-library",
3
- "version": "2.1.2",
3
+ "version": "2.2.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Gemeente-DenHaag/dh-auth-library.git"