dh-auth-library 2.4.0 → 3.0.2

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
@@ -4,7 +4,7 @@ A Playwright library for all logins used by Den Haag applications: AD, DigiD and
4
4
  It logs in, stores the session and keeps it alive during a test run, so each repository doesn't
5
5
  need its own login implementation.
6
6
 
7
- It is published as an npm package.
7
+ It is published as an npm package.
8
8
 
9
9
  ---
10
10
 
@@ -1,7 +1,7 @@
1
1
  import { Page } from '@playwright/test';
2
- import { Account } from 'nl-portal-playwright-libraries';
3
2
  import { LoginHandler } from '../loginHandler';
4
3
  import { LoginOptions } from '../pages/index';
4
+ import { Account } from 'nl-portal-playwright-libraries';
5
5
  /** Logs in to AD. Past the max age the session is logged in again, not refreshed, so a longer max age (e.g. 24h) saves logins. */
6
6
  export declare class ADLoginHandler implements LoginHandler {
7
7
  private readonly targetUrl;
@@ -1,7 +1,7 @@
1
1
  import { Page } from '@playwright/test';
2
- import { Account } from 'nl-portal-playwright-libraries';
3
2
  import { LoginHandler } from '../loginHandler';
4
3
  import { LoginOptionsWithButton } from '../pages/index';
4
+ import { Account } from 'nl-portal-playwright-libraries';
5
5
  export declare class DigidGemachtigdeLoginHandler implements LoginHandler {
6
6
  private readonly options;
7
7
  /**
@@ -1,7 +1,7 @@
1
1
  import { Page } from '@playwright/test';
2
- import { Account } from 'nl-portal-playwright-libraries';
3
2
  import { LoginOptionsWithButton } from '../pages/index';
4
3
  import { LoginHandler } from '../loginHandler';
4
+ import { Account } from 'nl-portal-playwright-libraries';
5
5
  export declare class DigidLoginHandler implements LoginHandler {
6
6
  private readonly options;
7
7
  /**
@@ -1,7 +1,7 @@
1
1
  import { Page } from '@playwright/test';
2
- import { Account } from 'nl-portal-playwright-libraries';
3
2
  import { LoginHandler } from '../loginHandler';
4
3
  import { LoginOptionsWithButton } from '../pages/index';
4
+ import { Account } from 'nl-portal-playwright-libraries';
5
5
  export declare class EHerkenningBewindvoerderLoginHandler implements LoginHandler {
6
6
  private readonly options;
7
7
  /**
@@ -1,7 +1,7 @@
1
1
  import { Page } from '@playwright/test';
2
- import { Account } from 'nl-portal-playwright-libraries';
3
2
  import { LoginOptionsWithButton } from '../pages/index';
4
3
  import { LoginHandler } from '../loginHandler';
4
+ import { Account } from 'nl-portal-playwright-libraries';
5
5
  export declare class EHerkenningLoginHandler implements LoginHandler {
6
6
  private readonly options;
7
7
  /**
@@ -24,8 +24,18 @@ export interface LoginOptions {
24
24
  }
25
25
  export declare class BaseLoginPage extends BasePage {
26
26
  constructor(page: Page);
27
+ /**
28
+ * Waits until the login is back on the app (the origin of `startUrl`, or `PORTAL_BASE_URL`), so a failed login
29
+ * throws instead of saving the page it ended on.
30
+ */
31
+ waitForApp(options: LoginOptionsWithButton): Promise<void>;
27
32
  /**
28
33
  * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
29
34
  */
30
35
  acceptCookiesForApp(options: LoginOptionsWithButton): Promise<void>;
36
+ /**
37
+ * When there is already an AD session, but for another environment, a special screen asks to
38
+ * confirm the account before you can continue.
39
+ */
40
+ handleAnySpecialADLoginScreen(): Promise<void>;
31
41
  }
@@ -1,6 +1,6 @@
1
1
  import { Locator, Page } from '@playwright/test';
2
- import { Account } from 'nl-portal-playwright-libraries';
3
2
  import { BaseLoginPage, LoginOptionsWithButton } from './baseLoginPage';
3
+ import { Account } from 'nl-portal-playwright-libraries';
4
4
  export declare class DigidLoginPage extends BaseLoginPage {
5
5
  constructor(page: Page);
6
6
  /**
@@ -17,11 +17,6 @@ export declare class DigidLoginPage extends BaseLoginPage {
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
- * When there is already an AD session, but for another environment, a special screen asks to
22
- * confirm the account before you can continue.
23
- */
24
- handleAnySpecialADLoginScreen(): Promise<void>;
25
20
  /**
26
21
  * @param account login details, supplied by the consumer of this library
27
22
  * @param gemachtigde whether to log in as an authorized representative (machtiging) instead of a regular user
@@ -1,6 +1,6 @@
1
1
  import { Page } from '@playwright/test';
2
- import { Account } from 'nl-portal-playwright-libraries';
3
2
  import { BaseLoginPage, LoginOptionsWithButton } from './baseLoginPage';
3
+ import { Account } from 'nl-portal-playwright-libraries';
4
4
  export declare class EHerkenningLoginPage extends BaseLoginPage {
5
5
  private readonly dropdownSelectIdentityProvider;
6
6
  private readonly buttonConfirmIdentityProviderSelection;
@@ -11,7 +11,16 @@ export declare class EHerkenningLoginPage extends BaseLoginPage {
11
11
  private readonly continueLink;
12
12
  private readonly inputBsn;
13
13
  private readonly searchButton;
14
+ private readonly organisations;
14
15
  constructor(page: Page);
16
+ /**
17
+ * Picks the organisation to log in for. With one, eHerkenning asks to confirm it ("U bent gemachtigd") and
18
+ * `account.identifier`, when set, must be its exact name or KvK number; with more, it lists them and
19
+ * `account.identifier` picks one.
20
+ *
21
+ * @param account login details, supplied by the consumer of this library
22
+ */
23
+ private selectOrganisation;
15
24
  /**
16
25
  * @param account login details, supplied by the consumer of this library
17
26
  */
@@ -1,6 +1,6 @@
1
1
  import { Account, SessionHandler } from 'nl-portal-playwright-libraries';
2
2
  import { LoginHandler } from './loginHandler';
3
- import { AuthType } from '../constants/index';
3
+ import { AuthType } from '../constants';
4
4
  /** Default max age for `SessionManager.getOrCreateSession`. For an `ad-session`, a longer one (e.g. 24h) saves AD logins. */
5
5
  export declare const MAX_SESSION_TIME_IN_MINUTES = 10;
6
6
  /**
@@ -25,6 +25,9 @@ export declare class SessionFileHelper {
25
25
  */
26
26
  static getDigidGemachtigdeFileName(browser: Browser, account: Account): string;
27
27
  /**
28
+ * One file per user, also for the eHerkenning vestiging and bewindvoerder files: `account.identifier` isn't part
29
+ * of the name.
30
+ *
28
31
  * @param browser the browser instance the session file name is based on
29
32
  * @param account login details, supplied by the consumer of this library; only `username` is used
30
33
  */
package/dist/index.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let nl_portal_playwright_libraries = require("nl-portal-playwright-libraries");
25
24
  let _playwright_test = require("@playwright/test");
26
25
  let totp_generator = require("totp-generator");
@@ -30,7 +29,7 @@ let node_path = require("node:path");
30
29
  node_path = __toESM(node_path);
31
30
  let node_process = require("node:process");
32
31
  node_process = __toESM(node_process);
33
- //#region src/auth/utils/maskedFill.ts
32
+ // src/auth/utils/maskedFill.ts
34
33
  function isEnvValue(value) {
35
34
  return value !== "" && Object.values(process.env).includes(value);
36
35
  }
@@ -53,8 +52,7 @@ async function maskedFill(locator, value, propertyName, forceMask = false) {
53
52
  await locator.blur();
54
53
  });
55
54
  }
56
- //#endregion
57
- //#region src/auth/utils/saveSession.ts
55
+ // src/auth/utils/saveSession.ts
58
56
  /**
59
57
  * Writes the context's storage state to `file`, without the cookies in `excludeCookies`
60
58
  * (see `LoginOptions.excludeCookies`).
@@ -73,8 +71,7 @@ async function saveSession(context, file, excludeCookies = []) {
73
71
  node_fs.default.writeFileSync(tmp, JSON.stringify(state, null, 2));
74
72
  node_fs.default.renameSync(tmp, file);
75
73
  }
76
- //#endregion
77
- //#region src/auth/pages/adLoginPage.ts
74
+ // src/auth/pages/adLoginPage.ts
78
75
  var gzacUrlProd = "https://alg-zgw.denhaag.nl";
79
76
  var gzacUrlAcp = "https://alg-zgw.acc.denhaag.nl";
80
77
  var gzacUrlTest = "https://alg-zgw.test.denhaag.nl";
@@ -218,8 +215,7 @@ var ADLoginPage = class ADLoginPage extends nl_portal_playwright_libraries.BaseP
218
215
  else throw new Error("Cannot find current environment for baseUrl: " + baseUrl);
219
216
  }
220
217
  };
221
- //#endregion
222
- //#region src/auth/loginhandlers/adLoginHandler.ts
218
+ // src/auth/loginhandlers/adLoginHandler.ts
223
219
  /** Logs in to AD. Past the max age the session is logged in again, not refreshed, so a longer max age (e.g. 24h) saves logins. */
224
220
  var ADLoginHandler = class {
225
221
  targetUrl;
@@ -246,8 +242,7 @@ var ADLoginHandler = class {
246
242
  await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file, this.excludeCookies);
247
243
  }
248
244
  };
249
- //#endregion
250
- //#region src/auth/utils/sessionFileHelper.ts
245
+ // src/auth/utils/sessionFileHelper.ts
251
246
  var sessionsDir = node_process.env.SESSIONS_DIR ?? node_path.resolve(node_process.cwd(), "sessions");
252
247
  var environment = node_process.env.ENV ?? "test";
253
248
  /**
@@ -283,6 +278,9 @@ var SessionFileHelper = class {
283
278
  return node_path.join(sessionsDir, `${browser.browserType().name()}-digid-gemachtigde-${environment}-${account.username}.json`);
284
279
  }
285
280
  /**
281
+ * One file per user, also for the eHerkenning vestiging and bewindvoerder files: `account.identifier` isn't part
282
+ * of the name.
283
+ *
286
284
  * @param browser the browser instance the session file name is based on
287
285
  * @param account login details, supplied by the consumer of this library; only `username` is used
288
286
  */
@@ -311,26 +309,48 @@ var SessionFileHelper = class {
311
309
  return node_path.join(sessionsDir, `${browser.browserType().name()}-ad-${environment}-${account.username}.json`);
312
310
  }
313
311
  };
314
- //#endregion
315
- //#region src/auth/pages/baseLoginPage.ts
312
+ // src/auth/pages/baseLoginPage.ts
316
313
  var BaseLoginPage = class extends nl_portal_playwright_libraries.BasePage {
317
314
  constructor(page) {
318
315
  super(page);
319
316
  }
320
317
  /**
318
+ * Waits until the login is back on the app (the origin of `startUrl`, or `PORTAL_BASE_URL`), so a failed login
319
+ * throws instead of saving the page it ended on.
320
+ */
321
+ async waitForApp(options) {
322
+ const appOrigin = new URL(options.startUrl ?? this.getBaseUrl()).origin;
323
+ await this.page.waitForURL((url) => url.origin === appOrigin, {
324
+ waitUntil: "commit",
325
+ timeout: 3e4
326
+ }).catch(() => {
327
+ throw new Error(`Login didn't return to ${appOrigin}, stuck on ${this.page.url()}`);
328
+ });
329
+ }
330
+ /**
321
331
  * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
322
332
  */
323
333
  async acceptCookiesForApp(options) {
324
334
  if (options.cookieButton) try {
325
335
  const cookieButton = options.cookieButton(this.page);
326
- await cookieButton.click();
336
+ await cookieButton.click({ timeout: 5e3 });
327
337
  await cookieButton.waitFor({ state: "hidden" });
328
338
  await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
329
339
  } catch (_noShowError) {}
330
340
  }
341
+ /**
342
+ * When there is already an AD session, but for another environment, a special screen asks to
343
+ * confirm the account before you can continue.
344
+ */
345
+ async handleAnySpecialADLoginScreen() {
346
+ try {
347
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
348
+ await this.page.locator(`//div[contains(@data-test-id,'${process.env.AD_USER}')]`).first().waitFor({ timeout: 1e3 });
349
+ await this.page.locator(`//div[contains(@data-test-id,'${process.env.AD_USER}')]`).first().click();
350
+ } catch (_error) {}
351
+ }
331
352
  };
332
- //#endregion
333
- //#region src/auth/pages/digidLoginPage.ts
353
+ // src/auth/pages/digidLoginPage.ts
334
354
  var DigidLoginPage = class extends BaseLoginPage {
335
355
  constructor(page) {
336
356
  super(page);
@@ -357,6 +377,7 @@ var DigidLoginPage = class extends BaseLoginPage {
357
377
  }
358
378
  if (!this.page.url().match(/authn/)) {
359
379
  await this.loginWithDigid(account);
380
+ await this.waitForApp(options);
360
381
  await this.acceptCookiesForApp(options);
361
382
  }
362
383
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -383,22 +404,12 @@ var DigidLoginPage = class extends BaseLoginPage {
383
404
  await loginButton.click();
384
405
  }
385
406
  await this.loginWithDigid(account, true);
407
+ await this.waitForApp(options);
386
408
  await this.acceptCookiesForApp(options);
387
409
  await saveSession(this.page.context(), fileName, options.excludeCookies);
388
410
  });
389
411
  }
390
412
  /**
391
- * When there is already an AD session, but for another environment, a special screen asks to
392
- * confirm the account before you can continue.
393
- */
394
- async handleAnySpecialADLoginScreen() {
395
- try {
396
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
397
- await this.page.locator(`//div[contains(@data-test-id,'${node_process.default.env.AD_USER}')]`).first().waitFor({ timeout: 1e3 });
398
- await this.page.locator(`//div[contains(@data-test-id,'${node_process.default.env.AD_USER}')]`).first().click();
399
- } catch (_error) {}
400
- }
401
- /**
402
413
  * @param account login details, supplied by the consumer of this library
403
414
  * @param gemachtigde whether to log in as an authorized representative (machtiging) instead of a regular user
404
415
  */
@@ -428,8 +439,7 @@ var DigidLoginPage = class extends BaseLoginPage {
428
439
  });
429
440
  }
430
441
  };
431
- //#endregion
432
- //#region src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
442
+ // src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
433
443
  var DigidGemachtigdeLoginHandler = class {
434
444
  options;
435
445
  /**
@@ -453,8 +463,7 @@ var DigidGemachtigdeLoginHandler = class {
453
463
  await new DigidLoginPage(page).loginAndCreateNewGemachtigdeSession(account, file, this.options);
454
464
  }
455
465
  };
456
- //#endregion
457
- //#region src/auth/pages/eHerkenningLoginPage.ts
466
+ // src/auth/pages/eHerkenningLoginPage.ts
458
467
  var EHerkenningLoginPage = class extends BaseLoginPage {
459
468
  dropdownSelectIdentityProvider;
460
469
  buttonConfirmIdentityProviderSelection;
@@ -465,6 +474,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
465
474
  continueLink;
466
475
  inputBsn;
467
476
  searchButton;
477
+ organisations;
468
478
  constructor(page) {
469
479
  super(page);
470
480
  this.dropdownSelectIdentityProvider = page.locator("#identity_provider");
@@ -476,15 +486,42 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
476
486
  this.inputBsn = page.locator("#bsn-input");
477
487
  this.searchButton = page.locator("#search-submit");
478
488
  this.continueLink = page.getByRole("link", { name: /Verder|Continue|Ga verder/ });
489
+ this.organisations = page.locator("li.select-authorization-list");
490
+ }
491
+ /**
492
+ * Picks the organisation to log in for. With one, eHerkenning asks to confirm it ("U bent gemachtigd") and
493
+ * `account.identifier`, when set, must be its exact name or KvK number; with more, it lists them and
494
+ * `account.identifier` picks one.
495
+ *
496
+ * @param account login details, supplied by the consumer of this library
497
+ */
498
+ async selectOrganisation(account) {
499
+ await this.organisations.or(this.continueButton).first().waitFor({ timeout: 1e4 }).catch(() => {});
500
+ if (await this.organisations.first().isVisible()) {
501
+ const listed = async () => (await this.organisations.allInnerTexts()).map((text) => text.replace(/\s+/g, " ").trim()).join(" | ");
502
+ if (!account.identifier) throw new Error(`${account.username} can log in for more than one organisation: set account.identifier to one of ${await listed()}`);
503
+ const organisation = /^\d+$/.test(account.identifier) ? this.organisations.filter({ hasText: new RegExp(`KvK: ${account.identifier}(?!\\d)`) }) : this.organisations.filter({ has: this.page.getByText(account.identifier, { exact: true }) });
504
+ if (await organisation.count() !== 1) throw new Error(`${account.username} can't log in for "${account.identifier}": set account.identifier to one of ${await listed()}`);
505
+ await organisation.locator("a").click();
506
+ } else if (await this.continueButton.isVisible()) {
507
+ if (account.identifier) {
508
+ const [, name, kvk] = (await this.page.locator("body").innerText()).match(/(?:voor|for) (.+?) \((\d+)\)/) ?? [];
509
+ if (account.identifier !== name && account.identifier !== kvk) throw new Error(`${account.username} logs in for ${name ? `${name} (${kvk})` : "an organisation that eHerkenning does not name"}, not "${account.identifier}"`);
510
+ }
511
+ await this.continueButton.click();
512
+ }
479
513
  }
480
514
  /**
481
515
  * @param account login details, supplied by the consumer of this library
482
516
  */
483
517
  async tryLoginWithEHerkenning(account) {
484
518
  await _playwright_test.test.step("Fill eHerkenning credentials and submit", async () => {
485
- await this.dropdownSelectIdentityProvider.selectOption("Digidentity AD 1.13 (preproduction)");
486
- await this.page.locator("#remember").click();
487
- await this.buttonConfirmIdentityProviderSelection.click();
519
+ await this.dropdownSelectIdentityProvider.or(this.textfieldUsername).first().waitFor();
520
+ if (await this.dropdownSelectIdentityProvider.isVisible()) {
521
+ await this.dropdownSelectIdentityProvider.selectOption("Digidentity AD 1.13 (preproduction)");
522
+ await this.page.locator("#remember").click();
523
+ await this.buttonConfirmIdentityProviderSelection.click();
524
+ }
488
525
  await this.textfieldUsername.fill(account.username);
489
526
  await this.continueButton.click();
490
527
  await maskedFill(this.textfieldPassword, account.password, "password");
@@ -501,14 +538,14 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
501
538
  const loginButton = options.loginButton(this.page);
502
539
  const { startUrl } = options;
503
540
  await this.openPage(startUrl);
504
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
541
+ await this.handleAnySpecialADLoginScreen();
505
542
  try {
506
543
  await loginButton.click();
507
544
  } catch (_error) {
508
545
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
509
- await this.openPage();
510
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
511
- await this.loginButton.click();
546
+ await this.openPage(startUrl);
547
+ await this.handleAnySpecialADLoginScreen();
548
+ await loginButton.click();
512
549
  }
513
550
  await this.loginWithEHerkenning(account, options);
514
551
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -521,8 +558,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
521
558
  async loginWithEHerkenning(account, options) {
522
559
  await this.tryLoginWithEHerkenning(account);
523
560
  await _playwright_test.test.step("Confirm eHerkenning login and accept cookies", async () => {
524
- await this.page.waitForTimeout(2e3);
525
- if (await this.continueButton.isVisible()) await this.continueButton.click();
561
+ await this.selectOrganisation(account);
562
+ await this.waitForApp(options);
526
563
  await this.acceptCookiesForApp(options);
527
564
  });
528
565
  }
@@ -536,13 +573,13 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
536
573
  const loginButton = options.loginButton(this.page);
537
574
  const { startUrl } = options;
538
575
  await this.openPage(startUrl);
539
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
576
+ await this.handleAnySpecialADLoginScreen();
540
577
  try {
541
578
  await loginButton.click();
542
579
  } catch (_error) {
543
580
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
544
- await this.openPage();
545
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
581
+ await this.openPage(startUrl);
582
+ await this.handleAnySpecialADLoginScreen();
546
583
  await loginButton.click();
547
584
  }
548
585
  await this.loginWithEHerkenningVestiging(account, options);
@@ -556,8 +593,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
556
593
  async loginWithEHerkenningVestiging(account, options) {
557
594
  await this.tryLoginWithEHerkenning(account);
558
595
  await _playwright_test.test.step("Confirm eHerkenning vestiging login and accept cookies", async () => {
559
- await this.page.waitForTimeout(2e3);
560
- if (await this.continueButton.isVisible()) await this.continueButton.click();
596
+ await this.selectOrganisation(account);
597
+ await this.waitForApp(options);
561
598
  await this.acceptCookiesForApp(options);
562
599
  });
563
600
  }
@@ -567,28 +604,38 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
567
604
  * @param file optional path of the storage state file to write the session to
568
605
  */
569
606
  async loginAsProfessionalBewindvoerder(gemachtigde, options, file) {
570
- await _playwright_test.test.step("Open bewindvoerder login option", async () => {
571
- const loginButton = options.loginButton(this.page);
572
- const { startUrl } = options;
607
+ const loginButton = options.loginButton(this.page);
608
+ const { startUrl } = options;
609
+ const openLogin = async () => {
573
610
  await this.openPage(startUrl);
574
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
611
+ await this.handleAnySpecialADLoginScreen();
575
612
  await loginButton.click();
613
+ };
614
+ await _playwright_test.test.step("Open bewindvoerder login option", async () => {
615
+ try {
616
+ await openLogin();
617
+ } catch (_error) {
618
+ console.error(`EHerkenning bewindvoerder Loginbutton click failed with error: ${_error}`);
619
+ await openLogin();
620
+ }
576
621
  });
577
622
  await _playwright_test.test.step("Login with eHerkenning credentials as bewindvoerder", async () => {
578
623
  try {
579
624
  await this.tryLoginWithEHerkenning(gemachtigde);
580
625
  } catch (_error) {
581
- await this.openPage();
626
+ await openLogin();
582
627
  await this.tryLoginWithEHerkenning(gemachtigde);
583
628
  }
584
629
  });
585
630
  await _playwright_test.test.step("Search for client by BSN and accept cookies", async () => {
586
- if (gemachtigde.bsn != null) {
631
+ const bsn = gemachtigde.identifier;
632
+ if (bsn != null) {
587
633
  await this.continueLink.click();
588
- await maskedFill(this.inputBsn, gemachtigde.bsn, "bsn");
634
+ await maskedFill(this.inputBsn, bsn, "bsn");
589
635
  }
590
636
  await this.searchButton.click();
591
637
  await this.continueLink.click();
638
+ await this.waitForApp(options);
592
639
  await this.acceptCookiesForApp(options);
593
640
  });
594
641
  if (file) await _playwright_test.test.step("Save session state", async () => {
@@ -596,8 +643,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
596
643
  });
597
644
  }
598
645
  };
599
- //#endregion
600
- //#region src/auth/loginhandlers/digidLoginHandler.ts
646
+ // src/auth/loginhandlers/digidLoginHandler.ts
601
647
  var DigidLoginHandler = class {
602
648
  options;
603
649
  /**
@@ -621,8 +667,7 @@ var DigidLoginHandler = class {
621
667
  await new DigidLoginPage(page).loginAndCreateNewSession(account, file, this.options);
622
668
  }
623
669
  };
624
- //#endregion
625
- //#region src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
670
+ // src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
626
671
  var EHerkenningBewindvoerderLoginHandler = class {
627
672
  options;
628
673
  /**
@@ -646,8 +691,7 @@ var EHerkenningBewindvoerderLoginHandler = class {
646
691
  await new EHerkenningLoginPage(page).loginAsProfessionalBewindvoerder(account, this.options, file);
647
692
  }
648
693
  };
649
- //#endregion
650
- //#region src/auth/loginhandlers/eHerkenningLoginHandler.ts
694
+ // src/auth/loginhandlers/eHerkenningLoginHandler.ts
651
695
  var EHerkenningLoginHandler = class {
652
696
  options;
653
697
  /**
@@ -671,8 +715,7 @@ var EHerkenningLoginHandler = class {
671
715
  await new EHerkenningLoginPage(page).loginWithEHerkenningVestigingAndCreateSession(file, account, this.options);
672
716
  }
673
717
  };
674
- //#endregion
675
- //#region src/auth/loginhandlers/localhostLoginHandler.ts
718
+ // src/auth/loginhandlers/localhostLoginHandler.ts
676
719
  var LocalhostLoginHandler = class {
677
720
  /**
678
721
  * @param page the Playwright page to perform the login on
@@ -683,8 +726,7 @@ var LocalhostLoginHandler = class {
683
726
  await new nl_portal_playwright_libraries.LocalLoginPage(page).loginAndCreateNewSession(account, file);
684
727
  }
685
728
  };
686
- //#endregion
687
- //#region src/auth/getLoginHandler.ts
729
+ // src/auth/getLoginHandler.ts
688
730
  /**
689
731
  * Shortcut for creating the login handler for an auth type. Creating the handler directly, e.g.
690
732
  * `new DigidLoginHandler(options)`, checks at compile time that the required options are there;
@@ -728,10 +770,18 @@ function loginOptions(authType, options) {
728
770
  loginButton: options.loginButton
729
771
  };
730
772
  }
731
- //#endregion
732
- //#region src/auth/sessionHandler.ts
773
+ // src/auth/sessionHandler.ts
733
774
  /** Default max age for `SessionManager.getOrCreateSession`. For an `ad-session`, a longer one (e.g. 24h) saves AD logins. */
734
775
  var MAX_SESSION_TIME_IN_MINUTES = 10;
776
+ /** The session in `file` with its copy of the AD cookies, which may have expired, replaced by the current ones in `adFile`. */
777
+ function withADCookies(file, adFile) {
778
+ const state = JSON.parse(node_fs.default.readFileSync(file, "utf8"));
779
+ const adCookies = JSON.parse(node_fs.default.readFileSync(adFile, "utf8")).cookies;
780
+ const key = (cookie) => `${cookie.name};${cookie.domain};${cookie.path}`;
781
+ const adKeys = new Set(adCookies.map(key));
782
+ state.cookies = [...state.cookies.filter((cookie) => !adKeys.has(key(cookie))), ...adCookies];
783
+ return state;
784
+ }
735
785
  /**
736
786
  * This class creates the correct SessionHandler
737
787
  * It will also perform the process of setting op the session
@@ -741,6 +791,10 @@ var MAX_SESSION_TIME_IN_MINUTES = 10;
741
791
  * @param loginHandler that will handle the login itself
742
792
  */
743
793
  function createSessionHandler(authType, account, loginHandler) {
794
+ const getADFile = (browser) => process.env.WITH_AD_SESSION === "true" && authType !== "ad-session" ? SessionFileHelper.getADFileName(browser, {
795
+ username: `${process.env.AD_USER}`,
796
+ password: `${process.env.AD_PASSWORD}`
797
+ }) : void 0;
744
798
  /**
745
799
  * Setup the new session
746
800
  * If needed the AD Session if used (Needed outside the firewall)
@@ -749,13 +803,9 @@ function createSessionHandler(authType, account, loginHandler) {
749
803
  * @param file
750
804
  */
751
805
  const setupSession = async (browser, file) => {
752
- const useADSession = process.env.WITH_AD_SESSION === "true";
753
806
  const page = await browser.newPage({
754
807
  ignoreHTTPSErrors: true,
755
- storageState: useADSession && authType !== "ad-session" ? SessionFileHelper.getADFileName(browser, {
756
- username: `${process.env.AD_USER}`,
757
- password: `${process.env.AD_PASSWORD}`
758
- }) : void 0
808
+ storageState: getADFile(browser)
759
809
  });
760
810
  console.log(`New session will be created: ${file}`);
761
811
  try {
@@ -784,6 +834,7 @@ function createSessionHandler(authType, account, loginHandler) {
784
834
  * This is being called from the nl-portal-base-library
785
835
  *
786
836
  * An AD session is logged in again from a clean context instead: PORTAL_BASE_URL doesn't check the Microsoft login.
837
+ * Other sessions get the cookies of the current AD session, as their own copy may have expired.
787
838
  *
788
839
  * @param browser
789
840
  * @param file
@@ -794,13 +845,21 @@ function createSessionHandler(authType, account, loginHandler) {
794
845
  await setupSession(browser, file);
795
846
  return;
796
847
  }
848
+ const adFile = getADFile(browser);
797
849
  const page = await browser.newPage({
798
850
  ignoreHTTPSErrors: true,
799
- storageState: file
851
+ storageState: adFile ? withADCookies(file, adFile) : file
800
852
  });
801
853
  console.log(`Refresh of session started for : ${file}`);
802
- await page.goto((0, nl_portal_playwright_libraries.getUrl)(nl_portal_playwright_libraries.Url.PortalBaseUrl));
854
+ const portalUrl = (0, nl_portal_playwright_libraries.getUrl)(nl_portal_playwright_libraries.Url.PortalBaseUrl);
855
+ await page.goto(portalUrl);
803
856
  await page.waitForLoadState("networkidle");
857
+ if (!page.url().match(/authn/) && !page.url().startsWith(new URL(portalUrl).origin)) {
858
+ console.log(`Session can't reach the portal (${page.url()}) and will be created again: ${file}`);
859
+ await page.close();
860
+ await setupSession(browser, file);
861
+ return;
862
+ }
804
863
  if (page.url().match(/authn/)) {
805
864
  console.log(`New session will be created as the current one is no longer valid: ${file}`);
806
865
  try {
@@ -816,8 +875,7 @@ function createSessionHandler(authType, account, loginHandler) {
816
875
  }
817
876
  };
818
877
  }
819
- //#endregion
820
- //#region src/auth/api/apiTokenHelper.ts
878
+ // src/auth/api/apiTokenHelper.ts
821
879
  /**
822
880
  * The token is often being refreshed so the easiest is to open a browser using the current session
823
881
  * The UI will automatically refresh the token and that is the token we will return
@@ -869,8 +927,7 @@ function getApiTokenFromSession(baseTest, handler) {
869
927
  }
870
928
  });
871
929
  }
872
- //#endregion
873
- //#region src/auth/getSessionHandler.ts
930
+ // src/auth/getSessionHandler.ts
874
931
  /**
875
932
  * @param testProfile the test user to log in
876
933
  * @param loginOptions the app's login options, from which the handler for `testProfile.authType` is created
@@ -891,7 +948,6 @@ function getApiTokenFromSession(baseTest, handler) {
891
948
  function getSessionHandler(testProfile, loginOptions, loginHandler) {
892
949
  return createSessionHandler(testProfile.authType, testProfile.account, loginHandler ?? getLoginHandler(testProfile.authType, loginOptions));
893
950
  }
894
- //#endregion
895
951
  exports.ADLoginHandler = ADLoginHandler;
896
952
  exports.ADLoginPage = ADLoginPage;
897
953
  exports.BaseLoginPage = BaseLoginPage;
package/dist/index.es.js CHANGED
@@ -2,11 +2,9 @@ import { BasePage, LocalLoginPage, SessionManager, Url, getUrl, isRunningOnLocal
2
2
  import { test } from "@playwright/test";
3
3
  import { TOTP } from "totp-generator";
4
4
  import fs from "node:fs";
5
- import * as path$1 from "node:path";
6
- import path from "node:path";
7
- import * as process$2 from "node:process";
8
- import process$1 from "node:process";
9
- //#region src/auth/utils/maskedFill.ts
5
+ import path, * as path$1 from "node:path";
6
+ import process$1, * as process$2 from "node:process";
7
+ // src/auth/utils/maskedFill.ts
10
8
  function isEnvValue(value) {
11
9
  return value !== "" && Object.values(process.env).includes(value);
12
10
  }
@@ -29,8 +27,7 @@ async function maskedFill(locator, value, propertyName, forceMask = false) {
29
27
  await locator.blur();
30
28
  });
31
29
  }
32
- //#endregion
33
- //#region src/auth/utils/saveSession.ts
30
+ // src/auth/utils/saveSession.ts
34
31
  /**
35
32
  * Writes the context's storage state to `file`, without the cookies in `excludeCookies`
36
33
  * (see `LoginOptions.excludeCookies`).
@@ -49,8 +46,7 @@ async function saveSession(context, file, excludeCookies = []) {
49
46
  fs.writeFileSync(tmp, JSON.stringify(state, null, 2));
50
47
  fs.renameSync(tmp, file);
51
48
  }
52
- //#endregion
53
- //#region src/auth/pages/adLoginPage.ts
49
+ // src/auth/pages/adLoginPage.ts
54
50
  var gzacUrlProd = "https://alg-zgw.denhaag.nl";
55
51
  var gzacUrlAcp = "https://alg-zgw.acc.denhaag.nl";
56
52
  var gzacUrlTest = "https://alg-zgw.test.denhaag.nl";
@@ -194,8 +190,7 @@ var ADLoginPage = class ADLoginPage extends BasePage {
194
190
  else throw new Error("Cannot find current environment for baseUrl: " + baseUrl);
195
191
  }
196
192
  };
197
- //#endregion
198
- //#region src/auth/loginhandlers/adLoginHandler.ts
193
+ // src/auth/loginhandlers/adLoginHandler.ts
199
194
  /** Logs in to AD. Past the max age the session is logged in again, not refreshed, so a longer max age (e.g. 24h) saves logins. */
200
195
  var ADLoginHandler = class {
201
196
  targetUrl;
@@ -222,8 +217,7 @@ var ADLoginHandler = class {
222
217
  await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file, this.excludeCookies);
223
218
  }
224
219
  };
225
- //#endregion
226
- //#region src/auth/utils/sessionFileHelper.ts
220
+ // src/auth/utils/sessionFileHelper.ts
227
221
  var sessionsDir = process$2.env.SESSIONS_DIR ?? path$1.resolve(process$2.cwd(), "sessions");
228
222
  var environment = process$2.env.ENV ?? "test";
229
223
  /**
@@ -259,6 +253,9 @@ var SessionFileHelper = class {
259
253
  return path$1.join(sessionsDir, `${browser.browserType().name()}-digid-gemachtigde-${environment}-${account.username}.json`);
260
254
  }
261
255
  /**
256
+ * One file per user, also for the eHerkenning vestiging and bewindvoerder files: `account.identifier` isn't part
257
+ * of the name.
258
+ *
262
259
  * @param browser the browser instance the session file name is based on
263
260
  * @param account login details, supplied by the consumer of this library; only `username` is used
264
261
  */
@@ -287,26 +284,48 @@ var SessionFileHelper = class {
287
284
  return path$1.join(sessionsDir, `${browser.browserType().name()}-ad-${environment}-${account.username}.json`);
288
285
  }
289
286
  };
290
- //#endregion
291
- //#region src/auth/pages/baseLoginPage.ts
287
+ // src/auth/pages/baseLoginPage.ts
292
288
  var BaseLoginPage = class extends BasePage {
293
289
  constructor(page) {
294
290
  super(page);
295
291
  }
296
292
  /**
293
+ * Waits until the login is back on the app (the origin of `startUrl`, or `PORTAL_BASE_URL`), so a failed login
294
+ * throws instead of saving the page it ended on.
295
+ */
296
+ async waitForApp(options) {
297
+ const appOrigin = new URL(options.startUrl ?? this.getBaseUrl()).origin;
298
+ await this.page.waitForURL((url) => url.origin === appOrigin, {
299
+ waitUntil: "commit",
300
+ timeout: 3e4
301
+ }).catch(() => {
302
+ throw new Error(`Login didn't return to ${appOrigin}, stuck on ${this.page.url()}`);
303
+ });
304
+ }
305
+ /**
297
306
  * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
298
307
  */
299
308
  async acceptCookiesForApp(options) {
300
309
  if (options.cookieButton) try {
301
310
  const cookieButton = options.cookieButton(this.page);
302
- await cookieButton.click();
311
+ await cookieButton.click({ timeout: 5e3 });
303
312
  await cookieButton.waitFor({ state: "hidden" });
304
313
  await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
305
314
  } catch (_noShowError) {}
306
315
  }
316
+ /**
317
+ * When there is already an AD session, but for another environment, a special screen asks to
318
+ * confirm the account before you can continue.
319
+ */
320
+ async handleAnySpecialADLoginScreen() {
321
+ try {
322
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
323
+ await this.page.locator(`//div[contains(@data-test-id,'${process.env.AD_USER}')]`).first().waitFor({ timeout: 1e3 });
324
+ await this.page.locator(`//div[contains(@data-test-id,'${process.env.AD_USER}')]`).first().click();
325
+ } catch (_error) {}
326
+ }
307
327
  };
308
- //#endregion
309
- //#region src/auth/pages/digidLoginPage.ts
328
+ // src/auth/pages/digidLoginPage.ts
310
329
  var DigidLoginPage = class extends BaseLoginPage {
311
330
  constructor(page) {
312
331
  super(page);
@@ -333,6 +352,7 @@ var DigidLoginPage = class extends BaseLoginPage {
333
352
  }
334
353
  if (!this.page.url().match(/authn/)) {
335
354
  await this.loginWithDigid(account);
355
+ await this.waitForApp(options);
336
356
  await this.acceptCookiesForApp(options);
337
357
  }
338
358
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -359,22 +379,12 @@ var DigidLoginPage = class extends BaseLoginPage {
359
379
  await loginButton.click();
360
380
  }
361
381
  await this.loginWithDigid(account, true);
382
+ await this.waitForApp(options);
362
383
  await this.acceptCookiesForApp(options);
363
384
  await saveSession(this.page.context(), fileName, options.excludeCookies);
364
385
  });
365
386
  }
366
387
  /**
367
- * When there is already an AD session, but for another environment, a special screen asks to
368
- * confirm the account before you can continue.
369
- */
370
- async handleAnySpecialADLoginScreen() {
371
- try {
372
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
373
- await this.page.locator(`//div[contains(@data-test-id,'${process$1.env.AD_USER}')]`).first().waitFor({ timeout: 1e3 });
374
- await this.page.locator(`//div[contains(@data-test-id,'${process$1.env.AD_USER}')]`).first().click();
375
- } catch (_error) {}
376
- }
377
- /**
378
388
  * @param account login details, supplied by the consumer of this library
379
389
  * @param gemachtigde whether to log in as an authorized representative (machtiging) instead of a regular user
380
390
  */
@@ -404,8 +414,7 @@ var DigidLoginPage = class extends BaseLoginPage {
404
414
  });
405
415
  }
406
416
  };
407
- //#endregion
408
- //#region src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
417
+ // src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
409
418
  var DigidGemachtigdeLoginHandler = class {
410
419
  options;
411
420
  /**
@@ -429,8 +438,7 @@ var DigidGemachtigdeLoginHandler = class {
429
438
  await new DigidLoginPage(page).loginAndCreateNewGemachtigdeSession(account, file, this.options);
430
439
  }
431
440
  };
432
- //#endregion
433
- //#region src/auth/pages/eHerkenningLoginPage.ts
441
+ // src/auth/pages/eHerkenningLoginPage.ts
434
442
  var EHerkenningLoginPage = class extends BaseLoginPage {
435
443
  dropdownSelectIdentityProvider;
436
444
  buttonConfirmIdentityProviderSelection;
@@ -441,6 +449,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
441
449
  continueLink;
442
450
  inputBsn;
443
451
  searchButton;
452
+ organisations;
444
453
  constructor(page) {
445
454
  super(page);
446
455
  this.dropdownSelectIdentityProvider = page.locator("#identity_provider");
@@ -452,15 +461,42 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
452
461
  this.inputBsn = page.locator("#bsn-input");
453
462
  this.searchButton = page.locator("#search-submit");
454
463
  this.continueLink = page.getByRole("link", { name: /Verder|Continue|Ga verder/ });
464
+ this.organisations = page.locator("li.select-authorization-list");
465
+ }
466
+ /**
467
+ * Picks the organisation to log in for. With one, eHerkenning asks to confirm it ("U bent gemachtigd") and
468
+ * `account.identifier`, when set, must be its exact name or KvK number; with more, it lists them and
469
+ * `account.identifier` picks one.
470
+ *
471
+ * @param account login details, supplied by the consumer of this library
472
+ */
473
+ async selectOrganisation(account) {
474
+ await this.organisations.or(this.continueButton).first().waitFor({ timeout: 1e4 }).catch(() => {});
475
+ if (await this.organisations.first().isVisible()) {
476
+ const listed = async () => (await this.organisations.allInnerTexts()).map((text) => text.replace(/\s+/g, " ").trim()).join(" | ");
477
+ if (!account.identifier) throw new Error(`${account.username} can log in for more than one organisation: set account.identifier to one of ${await listed()}`);
478
+ const organisation = /^\d+$/.test(account.identifier) ? this.organisations.filter({ hasText: new RegExp(`KvK: ${account.identifier}(?!\\d)`) }) : this.organisations.filter({ has: this.page.getByText(account.identifier, { exact: true }) });
479
+ if (await organisation.count() !== 1) throw new Error(`${account.username} can't log in for "${account.identifier}": set account.identifier to one of ${await listed()}`);
480
+ await organisation.locator("a").click();
481
+ } else if (await this.continueButton.isVisible()) {
482
+ if (account.identifier) {
483
+ const [, name, kvk] = (await this.page.locator("body").innerText()).match(/(?:voor|for) (.+?) \((\d+)\)/) ?? [];
484
+ if (account.identifier !== name && account.identifier !== kvk) throw new Error(`${account.username} logs in for ${name ? `${name} (${kvk})` : "an organisation that eHerkenning does not name"}, not "${account.identifier}"`);
485
+ }
486
+ await this.continueButton.click();
487
+ }
455
488
  }
456
489
  /**
457
490
  * @param account login details, supplied by the consumer of this library
458
491
  */
459
492
  async tryLoginWithEHerkenning(account) {
460
493
  await test.step("Fill eHerkenning credentials and submit", async () => {
461
- await this.dropdownSelectIdentityProvider.selectOption("Digidentity AD 1.13 (preproduction)");
462
- await this.page.locator("#remember").click();
463
- await this.buttonConfirmIdentityProviderSelection.click();
494
+ await this.dropdownSelectIdentityProvider.or(this.textfieldUsername).first().waitFor();
495
+ if (await this.dropdownSelectIdentityProvider.isVisible()) {
496
+ await this.dropdownSelectIdentityProvider.selectOption("Digidentity AD 1.13 (preproduction)");
497
+ await this.page.locator("#remember").click();
498
+ await this.buttonConfirmIdentityProviderSelection.click();
499
+ }
464
500
  await this.textfieldUsername.fill(account.username);
465
501
  await this.continueButton.click();
466
502
  await maskedFill(this.textfieldPassword, account.password, "password");
@@ -477,14 +513,14 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
477
513
  const loginButton = options.loginButton(this.page);
478
514
  const { startUrl } = options;
479
515
  await this.openPage(startUrl);
480
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
516
+ await this.handleAnySpecialADLoginScreen();
481
517
  try {
482
518
  await loginButton.click();
483
519
  } catch (_error) {
484
520
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
485
- await this.openPage();
486
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
487
- await this.loginButton.click();
521
+ await this.openPage(startUrl);
522
+ await this.handleAnySpecialADLoginScreen();
523
+ await loginButton.click();
488
524
  }
489
525
  await this.loginWithEHerkenning(account, options);
490
526
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -497,8 +533,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
497
533
  async loginWithEHerkenning(account, options) {
498
534
  await this.tryLoginWithEHerkenning(account);
499
535
  await test.step("Confirm eHerkenning login and accept cookies", async () => {
500
- await this.page.waitForTimeout(2e3);
501
- if (await this.continueButton.isVisible()) await this.continueButton.click();
536
+ await this.selectOrganisation(account);
537
+ await this.waitForApp(options);
502
538
  await this.acceptCookiesForApp(options);
503
539
  });
504
540
  }
@@ -512,13 +548,13 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
512
548
  const loginButton = options.loginButton(this.page);
513
549
  const { startUrl } = options;
514
550
  await this.openPage(startUrl);
515
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
551
+ await this.handleAnySpecialADLoginScreen();
516
552
  try {
517
553
  await loginButton.click();
518
554
  } catch (_error) {
519
555
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
520
- await this.openPage();
521
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
556
+ await this.openPage(startUrl);
557
+ await this.handleAnySpecialADLoginScreen();
522
558
  await loginButton.click();
523
559
  }
524
560
  await this.loginWithEHerkenningVestiging(account, options);
@@ -532,8 +568,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
532
568
  async loginWithEHerkenningVestiging(account, options) {
533
569
  await this.tryLoginWithEHerkenning(account);
534
570
  await test.step("Confirm eHerkenning vestiging login and accept cookies", async () => {
535
- await this.page.waitForTimeout(2e3);
536
- if (await this.continueButton.isVisible()) await this.continueButton.click();
571
+ await this.selectOrganisation(account);
572
+ await this.waitForApp(options);
537
573
  await this.acceptCookiesForApp(options);
538
574
  });
539
575
  }
@@ -543,28 +579,38 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
543
579
  * @param file optional path of the storage state file to write the session to
544
580
  */
545
581
  async loginAsProfessionalBewindvoerder(gemachtigde, options, file) {
546
- await test.step("Open bewindvoerder login option", async () => {
547
- const loginButton = options.loginButton(this.page);
548
- const { startUrl } = options;
582
+ const loginButton = options.loginButton(this.page);
583
+ const { startUrl } = options;
584
+ const openLogin = async () => {
549
585
  await this.openPage(startUrl);
550
- await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
586
+ await this.handleAnySpecialADLoginScreen();
551
587
  await loginButton.click();
588
+ };
589
+ await test.step("Open bewindvoerder login option", async () => {
590
+ try {
591
+ await openLogin();
592
+ } catch (_error) {
593
+ console.error(`EHerkenning bewindvoerder Loginbutton click failed with error: ${_error}`);
594
+ await openLogin();
595
+ }
552
596
  });
553
597
  await test.step("Login with eHerkenning credentials as bewindvoerder", async () => {
554
598
  try {
555
599
  await this.tryLoginWithEHerkenning(gemachtigde);
556
600
  } catch (_error) {
557
- await this.openPage();
601
+ await openLogin();
558
602
  await this.tryLoginWithEHerkenning(gemachtigde);
559
603
  }
560
604
  });
561
605
  await test.step("Search for client by BSN and accept cookies", async () => {
562
- if (gemachtigde.bsn != null) {
606
+ const bsn = gemachtigde.identifier;
607
+ if (bsn != null) {
563
608
  await this.continueLink.click();
564
- await maskedFill(this.inputBsn, gemachtigde.bsn, "bsn");
609
+ await maskedFill(this.inputBsn, bsn, "bsn");
565
610
  }
566
611
  await this.searchButton.click();
567
612
  await this.continueLink.click();
613
+ await this.waitForApp(options);
568
614
  await this.acceptCookiesForApp(options);
569
615
  });
570
616
  if (file) await test.step("Save session state", async () => {
@@ -572,8 +618,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
572
618
  });
573
619
  }
574
620
  };
575
- //#endregion
576
- //#region src/auth/loginhandlers/digidLoginHandler.ts
621
+ // src/auth/loginhandlers/digidLoginHandler.ts
577
622
  var DigidLoginHandler = class {
578
623
  options;
579
624
  /**
@@ -597,8 +642,7 @@ var DigidLoginHandler = class {
597
642
  await new DigidLoginPage(page).loginAndCreateNewSession(account, file, this.options);
598
643
  }
599
644
  };
600
- //#endregion
601
- //#region src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
645
+ // src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
602
646
  var EHerkenningBewindvoerderLoginHandler = class {
603
647
  options;
604
648
  /**
@@ -622,8 +666,7 @@ var EHerkenningBewindvoerderLoginHandler = class {
622
666
  await new EHerkenningLoginPage(page).loginAsProfessionalBewindvoerder(account, this.options, file);
623
667
  }
624
668
  };
625
- //#endregion
626
- //#region src/auth/loginhandlers/eHerkenningLoginHandler.ts
669
+ // src/auth/loginhandlers/eHerkenningLoginHandler.ts
627
670
  var EHerkenningLoginHandler = class {
628
671
  options;
629
672
  /**
@@ -647,8 +690,7 @@ var EHerkenningLoginHandler = class {
647
690
  await new EHerkenningLoginPage(page).loginWithEHerkenningVestigingAndCreateSession(file, account, this.options);
648
691
  }
649
692
  };
650
- //#endregion
651
- //#region src/auth/loginhandlers/localhostLoginHandler.ts
693
+ // src/auth/loginhandlers/localhostLoginHandler.ts
652
694
  var LocalhostLoginHandler = class {
653
695
  /**
654
696
  * @param page the Playwright page to perform the login on
@@ -659,8 +701,7 @@ var LocalhostLoginHandler = class {
659
701
  await new LocalLoginPage(page).loginAndCreateNewSession(account, file);
660
702
  }
661
703
  };
662
- //#endregion
663
- //#region src/auth/getLoginHandler.ts
704
+ // src/auth/getLoginHandler.ts
664
705
  /**
665
706
  * Shortcut for creating the login handler for an auth type. Creating the handler directly, e.g.
666
707
  * `new DigidLoginHandler(options)`, checks at compile time that the required options are there;
@@ -704,10 +745,18 @@ function loginOptions(authType, options) {
704
745
  loginButton: options.loginButton
705
746
  };
706
747
  }
707
- //#endregion
708
- //#region src/auth/sessionHandler.ts
748
+ // src/auth/sessionHandler.ts
709
749
  /** Default max age for `SessionManager.getOrCreateSession`. For an `ad-session`, a longer one (e.g. 24h) saves AD logins. */
710
750
  var MAX_SESSION_TIME_IN_MINUTES = 10;
751
+ /** The session in `file` with its copy of the AD cookies, which may have expired, replaced by the current ones in `adFile`. */
752
+ function withADCookies(file, adFile) {
753
+ const state = JSON.parse(fs.readFileSync(file, "utf8"));
754
+ const adCookies = JSON.parse(fs.readFileSync(adFile, "utf8")).cookies;
755
+ const key = (cookie) => `${cookie.name};${cookie.domain};${cookie.path}`;
756
+ const adKeys = new Set(adCookies.map(key));
757
+ state.cookies = [...state.cookies.filter((cookie) => !adKeys.has(key(cookie))), ...adCookies];
758
+ return state;
759
+ }
711
760
  /**
712
761
  * This class creates the correct SessionHandler
713
762
  * It will also perform the process of setting op the session
@@ -717,6 +766,10 @@ var MAX_SESSION_TIME_IN_MINUTES = 10;
717
766
  * @param loginHandler that will handle the login itself
718
767
  */
719
768
  function createSessionHandler(authType, account, loginHandler) {
769
+ const getADFile = (browser) => process.env.WITH_AD_SESSION === "true" && authType !== "ad-session" ? SessionFileHelper.getADFileName(browser, {
770
+ username: `${process.env.AD_USER}`,
771
+ password: `${process.env.AD_PASSWORD}`
772
+ }) : void 0;
720
773
  /**
721
774
  * Setup the new session
722
775
  * If needed the AD Session if used (Needed outside the firewall)
@@ -725,13 +778,9 @@ function createSessionHandler(authType, account, loginHandler) {
725
778
  * @param file
726
779
  */
727
780
  const setupSession = async (browser, file) => {
728
- const useADSession = process.env.WITH_AD_SESSION === "true";
729
781
  const page = await browser.newPage({
730
782
  ignoreHTTPSErrors: true,
731
- storageState: useADSession && authType !== "ad-session" ? SessionFileHelper.getADFileName(browser, {
732
- username: `${process.env.AD_USER}`,
733
- password: `${process.env.AD_PASSWORD}`
734
- }) : void 0
783
+ storageState: getADFile(browser)
735
784
  });
736
785
  console.log(`New session will be created: ${file}`);
737
786
  try {
@@ -760,6 +809,7 @@ function createSessionHandler(authType, account, loginHandler) {
760
809
  * This is being called from the nl-portal-base-library
761
810
  *
762
811
  * An AD session is logged in again from a clean context instead: PORTAL_BASE_URL doesn't check the Microsoft login.
812
+ * Other sessions get the cookies of the current AD session, as their own copy may have expired.
763
813
  *
764
814
  * @param browser
765
815
  * @param file
@@ -770,13 +820,21 @@ function createSessionHandler(authType, account, loginHandler) {
770
820
  await setupSession(browser, file);
771
821
  return;
772
822
  }
823
+ const adFile = getADFile(browser);
773
824
  const page = await browser.newPage({
774
825
  ignoreHTTPSErrors: true,
775
- storageState: file
826
+ storageState: adFile ? withADCookies(file, adFile) : file
776
827
  });
777
828
  console.log(`Refresh of session started for : ${file}`);
778
- await page.goto(getUrl(Url.PortalBaseUrl));
829
+ const portalUrl = getUrl(Url.PortalBaseUrl);
830
+ await page.goto(portalUrl);
779
831
  await page.waitForLoadState("networkidle");
832
+ if (!page.url().match(/authn/) && !page.url().startsWith(new URL(portalUrl).origin)) {
833
+ console.log(`Session can't reach the portal (${page.url()}) and will be created again: ${file}`);
834
+ await page.close();
835
+ await setupSession(browser, file);
836
+ return;
837
+ }
780
838
  if (page.url().match(/authn/)) {
781
839
  console.log(`New session will be created as the current one is no longer valid: ${file}`);
782
840
  try {
@@ -792,8 +850,7 @@ function createSessionHandler(authType, account, loginHandler) {
792
850
  }
793
851
  };
794
852
  }
795
- //#endregion
796
- //#region src/auth/api/apiTokenHelper.ts
853
+ // src/auth/api/apiTokenHelper.ts
797
854
  /**
798
855
  * The token is often being refreshed so the easiest is to open a browser using the current session
799
856
  * The UI will automatically refresh the token and that is the token we will return
@@ -845,8 +902,7 @@ function getApiTokenFromSession(baseTest, handler) {
845
902
  }
846
903
  });
847
904
  }
848
- //#endregion
849
- //#region src/auth/getSessionHandler.ts
905
+ // src/auth/getSessionHandler.ts
850
906
  /**
851
907
  * @param testProfile the test user to log in
852
908
  * @param loginOptions the app's login options, from which the handler for `testProfile.authType` is created
@@ -867,5 +923,4 @@ function getApiTokenFromSession(baseTest, handler) {
867
923
  function getSessionHandler(testProfile, loginOptions, loginHandler) {
868
924
  return createSessionHandler(testProfile.authType, testProfile.account, loginHandler ?? getLoginHandler(testProfile.authType, loginOptions));
869
925
  }
870
- //#endregion
871
926
  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.4.0",
3
+ "version": "3.0.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Gemeente-DenHaag/dh-auth-library.git"
@@ -36,16 +36,16 @@
36
36
  },
37
37
  "devDependencies": {
38
38
  "@eslint/js": "10.0.1",
39
- "@playwright/test": "^1.63.0",
40
- "@types/node": "^26.6.4",
41
- "eslint": "^10.12.0",
39
+ "@playwright/test": "^1.64.1",
40
+ "@types/node": "^26.6.5",
41
+ "eslint": "^10.13.0",
42
42
  "typescript": "^7.0.2",
43
- "typescript-eslint": "8.71.1",
44
- "vite": "^8.3.3",
43
+ "typescript-eslint": "8.72.1",
44
+ "vite": "^8.3.5",
45
45
  "vite-tsconfig-paths": "^6.1.1"
46
46
  },
47
47
  "dependencies": {
48
- "nl-portal-playwright-libraries": "^2.0.2",
48
+ "nl-portal-playwright-libraries": "^3.0.0",
49
49
  "totp-generator": "^2.0.1"
50
50
  },
51
51
  "keywords": [