dh-auth-library 2.3.0 → 3.0.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.
@@ -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";
@@ -156,7 +153,9 @@ var ADLoginPage = class ADLoginPage extends nl_portal_playwright_libraries.BaseP
156
153
  await adLoginPage.usernameInput.waitFor();
157
154
  await adLoginPage.usernameInput.fill(account.username);
158
155
  await adLoginPage.nextInput.click();
159
- await this.page.getByText("Uw wachtwoord gebruiken").click();
156
+ const usePasswordLink = this.page.getByText("Uw wachtwoord gebruiken");
157
+ await usePasswordLink.or(adLoginPage.passwordInput).filter({ visible: true }).first().waitFor();
158
+ if (await usePasswordLink.isVisible()) await usePasswordLink.click();
160
159
  }
161
160
  });
162
161
  let sessionWasStale = false;
@@ -216,8 +215,7 @@ var ADLoginPage = class ADLoginPage extends nl_portal_playwright_libraries.BaseP
216
215
  else throw new Error("Cannot find current environment for baseUrl: " + baseUrl);
217
216
  }
218
217
  };
219
- //#endregion
220
- //#region src/auth/loginhandlers/adLoginHandler.ts
218
+ // src/auth/loginhandlers/adLoginHandler.ts
221
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. */
222
220
  var ADLoginHandler = class {
223
221
  targetUrl;
@@ -244,8 +242,7 @@ var ADLoginHandler = class {
244
242
  await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file, this.excludeCookies);
245
243
  }
246
244
  };
247
- //#endregion
248
- //#region src/auth/utils/sessionFileHelper.ts
245
+ // src/auth/utils/sessionFileHelper.ts
249
246
  var sessionsDir = node_process.env.SESSIONS_DIR ?? node_path.resolve(node_process.cwd(), "sessions");
250
247
  var environment = node_process.env.ENV ?? "test";
251
248
  /**
@@ -281,6 +278,9 @@ var SessionFileHelper = class {
281
278
  return node_path.join(sessionsDir, `${browser.browserType().name()}-digid-gemachtigde-${environment}-${account.username}.json`);
282
279
  }
283
280
  /**
281
+ * One file per user, also for the eHerkenning vestiging and bewindvoerder files: `account.identifier` isn't part
282
+ * of the name.
283
+ *
284
284
  * @param browser the browser instance the session file name is based on
285
285
  * @param account login details, supplied by the consumer of this library; only `username` is used
286
286
  */
@@ -309,26 +309,48 @@ var SessionFileHelper = class {
309
309
  return node_path.join(sessionsDir, `${browser.browserType().name()}-ad-${environment}-${account.username}.json`);
310
310
  }
311
311
  };
312
- //#endregion
313
- //#region src/auth/pages/baseLoginPage.ts
312
+ // src/auth/pages/baseLoginPage.ts
314
313
  var BaseLoginPage = class extends nl_portal_playwright_libraries.BasePage {
315
314
  constructor(page) {
316
315
  super(page);
317
316
  }
318
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
+ /**
319
331
  * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
320
332
  */
321
333
  async acceptCookiesForApp(options) {
322
334
  if (options.cookieButton) try {
323
335
  const cookieButton = options.cookieButton(this.page);
324
- await cookieButton.click();
336
+ await cookieButton.click({ timeout: 5e3 });
325
337
  await cookieButton.waitFor({ state: "hidden" });
326
338
  await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
327
339
  } catch (_noShowError) {}
328
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
+ }
329
352
  };
330
- //#endregion
331
- //#region src/auth/pages/digidLoginPage.ts
353
+ // src/auth/pages/digidLoginPage.ts
332
354
  var DigidLoginPage = class extends BaseLoginPage {
333
355
  constructor(page) {
334
356
  super(page);
@@ -355,6 +377,7 @@ var DigidLoginPage = class extends BaseLoginPage {
355
377
  }
356
378
  if (!this.page.url().match(/authn/)) {
357
379
  await this.loginWithDigid(account);
380
+ await this.waitForApp(options);
358
381
  await this.acceptCookiesForApp(options);
359
382
  }
360
383
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -372,7 +395,7 @@ var DigidLoginPage = class extends BaseLoginPage {
372
395
  await _playwright_test.test.step("Login with DigiD as gemachtigde and create session", async () => {
373
396
  await this.openPage(startUrl);
374
397
  await this.handleAnySpecialADLoginScreen();
375
- this.page.waitForLoadState("networkidle");
398
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
376
399
  try {
377
400
  await loginButton.click();
378
401
  } catch (_error) {
@@ -381,22 +404,12 @@ var DigidLoginPage = class extends BaseLoginPage {
381
404
  await loginButton.click();
382
405
  }
383
406
  await this.loginWithDigid(account, true);
407
+ await this.waitForApp(options);
384
408
  await this.acceptCookiesForApp(options);
385
409
  await saveSession(this.page.context(), fileName, options.excludeCookies);
386
410
  });
387
411
  }
388
412
  /**
389
- * When there is already an AD session, but for another environment, a special screen asks to
390
- * confirm the account before you can continue.
391
- */
392
- async handleAnySpecialADLoginScreen() {
393
- try {
394
- this.page.waitForLoadState("networkidle");
395
- await this.page.locator(`//div[contains(@data-test-id,'${node_process.default.env.AD_USER}')]`).first().waitFor({ timeout: 1e3 });
396
- await this.page.locator(`//div[contains(@data-test-id,'${node_process.default.env.AD_USER}')]`).first().click();
397
- } catch (_error) {}
398
- }
399
- /**
400
413
  * @param account login details, supplied by the consumer of this library
401
414
  * @param gemachtigde whether to log in as an authorized representative (machtiging) instead of a regular user
402
415
  */
@@ -426,8 +439,7 @@ var DigidLoginPage = class extends BaseLoginPage {
426
439
  });
427
440
  }
428
441
  };
429
- //#endregion
430
- //#region src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
442
+ // src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
431
443
  var DigidGemachtigdeLoginHandler = class {
432
444
  options;
433
445
  /**
@@ -451,8 +463,7 @@ var DigidGemachtigdeLoginHandler = class {
451
463
  await new DigidLoginPage(page).loginAndCreateNewGemachtigdeSession(account, file, this.options);
452
464
  }
453
465
  };
454
- //#endregion
455
- //#region src/auth/pages/eHerkenningLoginPage.ts
466
+ // src/auth/pages/eHerkenningLoginPage.ts
456
467
  var EHerkenningLoginPage = class extends BaseLoginPage {
457
468
  dropdownSelectIdentityProvider;
458
469
  buttonConfirmIdentityProviderSelection;
@@ -463,6 +474,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
463
474
  continueLink;
464
475
  inputBsn;
465
476
  searchButton;
477
+ organisations;
466
478
  constructor(page) {
467
479
  super(page);
468
480
  this.dropdownSelectIdentityProvider = page.locator("#identity_provider");
@@ -474,15 +486,42 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
474
486
  this.inputBsn = page.locator("#bsn-input");
475
487
  this.searchButton = page.locator("#search-submit");
476
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
+ }
477
513
  }
478
514
  /**
479
515
  * @param account login details, supplied by the consumer of this library
480
516
  */
481
517
  async tryLoginWithEHerkenning(account) {
482
518
  await _playwright_test.test.step("Fill eHerkenning credentials and submit", async () => {
483
- await this.dropdownSelectIdentityProvider.selectOption("Digidentity AD 1.13 (preproduction)");
484
- await this.page.locator("#remember").click();
485
- 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
+ }
486
525
  await this.textfieldUsername.fill(account.username);
487
526
  await this.continueButton.click();
488
527
  await maskedFill(this.textfieldPassword, account.password, "password");
@@ -499,14 +538,14 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
499
538
  const loginButton = options.loginButton(this.page);
500
539
  const { startUrl } = options;
501
540
  await this.openPage(startUrl);
502
- this.page.waitForLoadState("networkidle");
541
+ await this.handleAnySpecialADLoginScreen();
503
542
  try {
504
543
  await loginButton.click();
505
544
  } catch (_error) {
506
545
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
507
- await this.openPage();
508
- this.page.waitForLoadState("networkidle");
509
- await this.loginButton.click();
546
+ await this.openPage(startUrl);
547
+ await this.handleAnySpecialADLoginScreen();
548
+ await loginButton.click();
510
549
  }
511
550
  await this.loginWithEHerkenning(account, options);
512
551
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -519,8 +558,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
519
558
  async loginWithEHerkenning(account, options) {
520
559
  await this.tryLoginWithEHerkenning(account);
521
560
  await _playwright_test.test.step("Confirm eHerkenning login and accept cookies", async () => {
522
- await this.page.waitForTimeout(2e3);
523
- if (await this.continueButton.isVisible()) await this.continueButton.click();
561
+ await this.selectOrganisation(account);
562
+ await this.waitForApp(options);
524
563
  await this.acceptCookiesForApp(options);
525
564
  });
526
565
  }
@@ -534,13 +573,13 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
534
573
  const loginButton = options.loginButton(this.page);
535
574
  const { startUrl } = options;
536
575
  await this.openPage(startUrl);
537
- this.page.waitForLoadState("networkidle");
576
+ await this.handleAnySpecialADLoginScreen();
538
577
  try {
539
578
  await loginButton.click();
540
579
  } catch (_error) {
541
580
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
542
- await this.openPage();
543
- this.page.waitForLoadState("networkidle");
581
+ await this.openPage(startUrl);
582
+ await this.handleAnySpecialADLoginScreen();
544
583
  await loginButton.click();
545
584
  }
546
585
  await this.loginWithEHerkenningVestiging(account, options);
@@ -554,8 +593,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
554
593
  async loginWithEHerkenningVestiging(account, options) {
555
594
  await this.tryLoginWithEHerkenning(account);
556
595
  await _playwright_test.test.step("Confirm eHerkenning vestiging login and accept cookies", async () => {
557
- await this.page.waitForTimeout(2e3);
558
- if (await this.continueButton.isVisible()) await this.continueButton.click();
596
+ await this.selectOrganisation(account);
597
+ await this.waitForApp(options);
559
598
  await this.acceptCookiesForApp(options);
560
599
  });
561
600
  }
@@ -565,28 +604,38 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
565
604
  * @param file optional path of the storage state file to write the session to
566
605
  */
567
606
  async loginAsProfessionalBewindvoerder(gemachtigde, options, file) {
568
- await _playwright_test.test.step("Open bewindvoerder login option", async () => {
569
- const loginButton = options.loginButton(this.page);
570
- const { startUrl } = options;
607
+ const loginButton = options.loginButton(this.page);
608
+ const { startUrl } = options;
609
+ const openLogin = async () => {
571
610
  await this.openPage(startUrl);
572
- this.page.waitForLoadState("networkidle");
611
+ await this.handleAnySpecialADLoginScreen();
573
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
+ }
574
621
  });
575
622
  await _playwright_test.test.step("Login with eHerkenning credentials as bewindvoerder", async () => {
576
623
  try {
577
624
  await this.tryLoginWithEHerkenning(gemachtigde);
578
625
  } catch (_error) {
579
- await this.openPage();
626
+ await openLogin();
580
627
  await this.tryLoginWithEHerkenning(gemachtigde);
581
628
  }
582
629
  });
583
630
  await _playwright_test.test.step("Search for client by BSN and accept cookies", async () => {
584
- if (gemachtigde.bsn != null) {
631
+ const bsn = gemachtigde.identifier;
632
+ if (bsn != null) {
585
633
  await this.continueLink.click();
586
- await maskedFill(this.inputBsn, gemachtigde.bsn, "bsn");
634
+ await maskedFill(this.inputBsn, bsn, "bsn");
587
635
  }
588
636
  await this.searchButton.click();
589
637
  await this.continueLink.click();
638
+ await this.waitForApp(options);
590
639
  await this.acceptCookiesForApp(options);
591
640
  });
592
641
  if (file) await _playwright_test.test.step("Save session state", async () => {
@@ -594,8 +643,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
594
643
  });
595
644
  }
596
645
  };
597
- //#endregion
598
- //#region src/auth/loginhandlers/digidLoginHandler.ts
646
+ // src/auth/loginhandlers/digidLoginHandler.ts
599
647
  var DigidLoginHandler = class {
600
648
  options;
601
649
  /**
@@ -619,8 +667,7 @@ var DigidLoginHandler = class {
619
667
  await new DigidLoginPage(page).loginAndCreateNewSession(account, file, this.options);
620
668
  }
621
669
  };
622
- //#endregion
623
- //#region src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
670
+ // src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
624
671
  var EHerkenningBewindvoerderLoginHandler = class {
625
672
  options;
626
673
  /**
@@ -644,8 +691,7 @@ var EHerkenningBewindvoerderLoginHandler = class {
644
691
  await new EHerkenningLoginPage(page).loginAsProfessionalBewindvoerder(account, this.options, file);
645
692
  }
646
693
  };
647
- //#endregion
648
- //#region src/auth/loginhandlers/eHerkenningLoginHandler.ts
694
+ // src/auth/loginhandlers/eHerkenningLoginHandler.ts
649
695
  var EHerkenningLoginHandler = class {
650
696
  options;
651
697
  /**
@@ -669,8 +715,7 @@ var EHerkenningLoginHandler = class {
669
715
  await new EHerkenningLoginPage(page).loginWithEHerkenningVestigingAndCreateSession(file, account, this.options);
670
716
  }
671
717
  };
672
- //#endregion
673
- //#region src/auth/loginhandlers/localhostLoginHandler.ts
718
+ // src/auth/loginhandlers/localhostLoginHandler.ts
674
719
  var LocalhostLoginHandler = class {
675
720
  /**
676
721
  * @param page the Playwright page to perform the login on
@@ -681,8 +726,7 @@ var LocalhostLoginHandler = class {
681
726
  await new nl_portal_playwright_libraries.LocalLoginPage(page).loginAndCreateNewSession(account, file);
682
727
  }
683
728
  };
684
- //#endregion
685
- //#region src/auth/getLoginHandler.ts
729
+ // src/auth/getLoginHandler.ts
686
730
  /**
687
731
  * Shortcut for creating the login handler for an auth type. Creating the handler directly, e.g.
688
732
  * `new DigidLoginHandler(options)`, checks at compile time that the required options are there;
@@ -726,10 +770,18 @@ function loginOptions(authType, options) {
726
770
  loginButton: options.loginButton
727
771
  };
728
772
  }
729
- //#endregion
730
- //#region src/auth/sessionHandler.ts
773
+ // src/auth/sessionHandler.ts
731
774
  /** Default max age for `SessionManager.getOrCreateSession`. For an `ad-session`, a longer one (e.g. 24h) saves AD logins. */
732
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
+ }
733
785
  /**
734
786
  * This class creates the correct SessionHandler
735
787
  * It will also perform the process of setting op the session
@@ -739,6 +791,10 @@ var MAX_SESSION_TIME_IN_MINUTES = 10;
739
791
  * @param loginHandler that will handle the login itself
740
792
  */
741
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;
742
798
  /**
743
799
  * Setup the new session
744
800
  * If needed the AD Session if used (Needed outside the firewall)
@@ -747,13 +803,9 @@ function createSessionHandler(authType, account, loginHandler) {
747
803
  * @param file
748
804
  */
749
805
  const setupSession = async (browser, file) => {
750
- const useADSession = process.env.WITH_AD_SESSION === "true";
751
806
  const page = await browser.newPage({
752
807
  ignoreHTTPSErrors: true,
753
- storageState: useADSession && authType !== "ad-session" ? SessionFileHelper.getADFileName(browser, {
754
- username: `${process.env.AD_USER}`,
755
- password: `${process.env.AD_PASSWORD}`
756
- }) : void 0
808
+ storageState: getADFile(browser)
757
809
  });
758
810
  console.log(`New session will be created: ${file}`);
759
811
  try {
@@ -782,6 +834,7 @@ function createSessionHandler(authType, account, loginHandler) {
782
834
  * This is being called from the nl-portal-base-library
783
835
  *
784
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.
785
838
  *
786
839
  * @param browser
787
840
  * @param file
@@ -792,13 +845,21 @@ function createSessionHandler(authType, account, loginHandler) {
792
845
  await setupSession(browser, file);
793
846
  return;
794
847
  }
848
+ const adFile = getADFile(browser);
795
849
  const page = await browser.newPage({
796
850
  ignoreHTTPSErrors: true,
797
- storageState: file
851
+ storageState: adFile ? withADCookies(file, adFile) : file
798
852
  });
799
853
  console.log(`Refresh of session started for : ${file}`);
800
- 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);
801
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
+ }
802
863
  if (page.url().match(/authn/)) {
803
864
  console.log(`New session will be created as the current one is no longer valid: ${file}`);
804
865
  try {
@@ -814,8 +875,7 @@ function createSessionHandler(authType, account, loginHandler) {
814
875
  }
815
876
  };
816
877
  }
817
- //#endregion
818
- //#region src/auth/api/apiTokenHelper.ts
878
+ // src/auth/api/apiTokenHelper.ts
819
879
  /**
820
880
  * The token is often being refreshed so the easiest is to open a browser using the current session
821
881
  * The UI will automatically refresh the token and that is the token we will return
@@ -867,8 +927,7 @@ function getApiTokenFromSession(baseTest, handler) {
867
927
  }
868
928
  });
869
929
  }
870
- //#endregion
871
- //#region src/auth/getSessionHandler.ts
930
+ // src/auth/getSessionHandler.ts
872
931
  /**
873
932
  * @param testProfile the test user to log in
874
933
  * @param loginOptions the app's login options, from which the handler for `testProfile.authType` is created
@@ -889,7 +948,6 @@ function getApiTokenFromSession(baseTest, handler) {
889
948
  function getSessionHandler(testProfile, loginOptions, loginHandler) {
890
949
  return createSessionHandler(testProfile.authType, testProfile.account, loginHandler ?? getLoginHandler(testProfile.authType, loginOptions));
891
950
  }
892
- //#endregion
893
951
  exports.ADLoginHandler = ADLoginHandler;
894
952
  exports.ADLoginPage = ADLoginPage;
895
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";
@@ -132,7 +128,9 @@ var ADLoginPage = class ADLoginPage extends BasePage {
132
128
  await adLoginPage.usernameInput.waitFor();
133
129
  await adLoginPage.usernameInput.fill(account.username);
134
130
  await adLoginPage.nextInput.click();
135
- await this.page.getByText("Uw wachtwoord gebruiken").click();
131
+ const usePasswordLink = this.page.getByText("Uw wachtwoord gebruiken");
132
+ await usePasswordLink.or(adLoginPage.passwordInput).filter({ visible: true }).first().waitFor();
133
+ if (await usePasswordLink.isVisible()) await usePasswordLink.click();
136
134
  }
137
135
  });
138
136
  let sessionWasStale = false;
@@ -192,8 +190,7 @@ var ADLoginPage = class ADLoginPage extends BasePage {
192
190
  else throw new Error("Cannot find current environment for baseUrl: " + baseUrl);
193
191
  }
194
192
  };
195
- //#endregion
196
- //#region src/auth/loginhandlers/adLoginHandler.ts
193
+ // src/auth/loginhandlers/adLoginHandler.ts
197
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. */
198
195
  var ADLoginHandler = class {
199
196
  targetUrl;
@@ -220,8 +217,7 @@ var ADLoginHandler = class {
220
217
  await new ADLoginPage(page).loginWithADAccountAndCreateSession(account, this.targetUrl, file, this.excludeCookies);
221
218
  }
222
219
  };
223
- //#endregion
224
- //#region src/auth/utils/sessionFileHelper.ts
220
+ // src/auth/utils/sessionFileHelper.ts
225
221
  var sessionsDir = process$2.env.SESSIONS_DIR ?? path$1.resolve(process$2.cwd(), "sessions");
226
222
  var environment = process$2.env.ENV ?? "test";
227
223
  /**
@@ -257,6 +253,9 @@ var SessionFileHelper = class {
257
253
  return path$1.join(sessionsDir, `${browser.browserType().name()}-digid-gemachtigde-${environment}-${account.username}.json`);
258
254
  }
259
255
  /**
256
+ * One file per user, also for the eHerkenning vestiging and bewindvoerder files: `account.identifier` isn't part
257
+ * of the name.
258
+ *
260
259
  * @param browser the browser instance the session file name is based on
261
260
  * @param account login details, supplied by the consumer of this library; only `username` is used
262
261
  */
@@ -285,26 +284,48 @@ var SessionFileHelper = class {
285
284
  return path$1.join(sessionsDir, `${browser.browserType().name()}-ad-${environment}-${account.username}.json`);
286
285
  }
287
286
  };
288
- //#endregion
289
- //#region src/auth/pages/baseLoginPage.ts
287
+ // src/auth/pages/baseLoginPage.ts
290
288
  var BaseLoginPage = class extends BasePage {
291
289
  constructor(page) {
292
290
  super(page);
293
291
  }
294
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
+ /**
295
306
  * Accepts the app's cookie banner when the consumer supplied one, so the consent is in the saved session.
296
307
  */
297
308
  async acceptCookiesForApp(options) {
298
309
  if (options.cookieButton) try {
299
310
  const cookieButton = options.cookieButton(this.page);
300
- await cookieButton.click();
311
+ await cookieButton.click({ timeout: 5e3 });
301
312
  await cookieButton.waitFor({ state: "hidden" });
302
313
  await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
303
314
  } catch (_noShowError) {}
304
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
+ }
305
327
  };
306
- //#endregion
307
- //#region src/auth/pages/digidLoginPage.ts
328
+ // src/auth/pages/digidLoginPage.ts
308
329
  var DigidLoginPage = class extends BaseLoginPage {
309
330
  constructor(page) {
310
331
  super(page);
@@ -331,6 +352,7 @@ var DigidLoginPage = class extends BaseLoginPage {
331
352
  }
332
353
  if (!this.page.url().match(/authn/)) {
333
354
  await this.loginWithDigid(account);
355
+ await this.waitForApp(options);
334
356
  await this.acceptCookiesForApp(options);
335
357
  }
336
358
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -348,7 +370,7 @@ var DigidLoginPage = class extends BaseLoginPage {
348
370
  await test.step("Login with DigiD as gemachtigde and create session", async () => {
349
371
  await this.openPage(startUrl);
350
372
  await this.handleAnySpecialADLoginScreen();
351
- this.page.waitForLoadState("networkidle");
373
+ await this.page.waitForLoadState("networkidle", { timeout: 1e4 }).catch(() => {});
352
374
  try {
353
375
  await loginButton.click();
354
376
  } catch (_error) {
@@ -357,22 +379,12 @@ var DigidLoginPage = class extends BaseLoginPage {
357
379
  await loginButton.click();
358
380
  }
359
381
  await this.loginWithDigid(account, true);
382
+ await this.waitForApp(options);
360
383
  await this.acceptCookiesForApp(options);
361
384
  await saveSession(this.page.context(), fileName, options.excludeCookies);
362
385
  });
363
386
  }
364
387
  /**
365
- * When there is already an AD session, but for another environment, a special screen asks to
366
- * confirm the account before you can continue.
367
- */
368
- async handleAnySpecialADLoginScreen() {
369
- try {
370
- this.page.waitForLoadState("networkidle");
371
- await this.page.locator(`//div[contains(@data-test-id,'${process$1.env.AD_USER}')]`).first().waitFor({ timeout: 1e3 });
372
- await this.page.locator(`//div[contains(@data-test-id,'${process$1.env.AD_USER}')]`).first().click();
373
- } catch (_error) {}
374
- }
375
- /**
376
388
  * @param account login details, supplied by the consumer of this library
377
389
  * @param gemachtigde whether to log in as an authorized representative (machtiging) instead of a regular user
378
390
  */
@@ -402,8 +414,7 @@ var DigidLoginPage = class extends BaseLoginPage {
402
414
  });
403
415
  }
404
416
  };
405
- //#endregion
406
- //#region src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
417
+ // src/auth/loginhandlers/digidGemachtigdeLoginHandler.ts
407
418
  var DigidGemachtigdeLoginHandler = class {
408
419
  options;
409
420
  /**
@@ -427,8 +438,7 @@ var DigidGemachtigdeLoginHandler = class {
427
438
  await new DigidLoginPage(page).loginAndCreateNewGemachtigdeSession(account, file, this.options);
428
439
  }
429
440
  };
430
- //#endregion
431
- //#region src/auth/pages/eHerkenningLoginPage.ts
441
+ // src/auth/pages/eHerkenningLoginPage.ts
432
442
  var EHerkenningLoginPage = class extends BaseLoginPage {
433
443
  dropdownSelectIdentityProvider;
434
444
  buttonConfirmIdentityProviderSelection;
@@ -439,6 +449,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
439
449
  continueLink;
440
450
  inputBsn;
441
451
  searchButton;
452
+ organisations;
442
453
  constructor(page) {
443
454
  super(page);
444
455
  this.dropdownSelectIdentityProvider = page.locator("#identity_provider");
@@ -450,15 +461,42 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
450
461
  this.inputBsn = page.locator("#bsn-input");
451
462
  this.searchButton = page.locator("#search-submit");
452
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
+ }
453
488
  }
454
489
  /**
455
490
  * @param account login details, supplied by the consumer of this library
456
491
  */
457
492
  async tryLoginWithEHerkenning(account) {
458
493
  await test.step("Fill eHerkenning credentials and submit", async () => {
459
- await this.dropdownSelectIdentityProvider.selectOption("Digidentity AD 1.13 (preproduction)");
460
- await this.page.locator("#remember").click();
461
- 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
+ }
462
500
  await this.textfieldUsername.fill(account.username);
463
501
  await this.continueButton.click();
464
502
  await maskedFill(this.textfieldPassword, account.password, "password");
@@ -475,14 +513,14 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
475
513
  const loginButton = options.loginButton(this.page);
476
514
  const { startUrl } = options;
477
515
  await this.openPage(startUrl);
478
- this.page.waitForLoadState("networkidle");
516
+ await this.handleAnySpecialADLoginScreen();
479
517
  try {
480
518
  await loginButton.click();
481
519
  } catch (_error) {
482
520
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
483
- await this.openPage();
484
- this.page.waitForLoadState("networkidle");
485
- await this.loginButton.click();
521
+ await this.openPage(startUrl);
522
+ await this.handleAnySpecialADLoginScreen();
523
+ await loginButton.click();
486
524
  }
487
525
  await this.loginWithEHerkenning(account, options);
488
526
  await saveSession(this.page.context(), fileName, options.excludeCookies);
@@ -495,8 +533,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
495
533
  async loginWithEHerkenning(account, options) {
496
534
  await this.tryLoginWithEHerkenning(account);
497
535
  await test.step("Confirm eHerkenning login and accept cookies", async () => {
498
- await this.page.waitForTimeout(2e3);
499
- if (await this.continueButton.isVisible()) await this.continueButton.click();
536
+ await this.selectOrganisation(account);
537
+ await this.waitForApp(options);
500
538
  await this.acceptCookiesForApp(options);
501
539
  });
502
540
  }
@@ -510,13 +548,13 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
510
548
  const loginButton = options.loginButton(this.page);
511
549
  const { startUrl } = options;
512
550
  await this.openPage(startUrl);
513
- this.page.waitForLoadState("networkidle");
551
+ await this.handleAnySpecialADLoginScreen();
514
552
  try {
515
553
  await loginButton.click();
516
554
  } catch (_error) {
517
555
  console.error(`EHerkenning Loginbutton click failed with error: ${_error}`);
518
- await this.openPage();
519
- this.page.waitForLoadState("networkidle");
556
+ await this.openPage(startUrl);
557
+ await this.handleAnySpecialADLoginScreen();
520
558
  await loginButton.click();
521
559
  }
522
560
  await this.loginWithEHerkenningVestiging(account, options);
@@ -530,8 +568,8 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
530
568
  async loginWithEHerkenningVestiging(account, options) {
531
569
  await this.tryLoginWithEHerkenning(account);
532
570
  await test.step("Confirm eHerkenning vestiging login and accept cookies", async () => {
533
- await this.page.waitForTimeout(2e3);
534
- if (await this.continueButton.isVisible()) await this.continueButton.click();
571
+ await this.selectOrganisation(account);
572
+ await this.waitForApp(options);
535
573
  await this.acceptCookiesForApp(options);
536
574
  });
537
575
  }
@@ -541,28 +579,38 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
541
579
  * @param file optional path of the storage state file to write the session to
542
580
  */
543
581
  async loginAsProfessionalBewindvoerder(gemachtigde, options, file) {
544
- await test.step("Open bewindvoerder login option", async () => {
545
- const loginButton = options.loginButton(this.page);
546
- const { startUrl } = options;
582
+ const loginButton = options.loginButton(this.page);
583
+ const { startUrl } = options;
584
+ const openLogin = async () => {
547
585
  await this.openPage(startUrl);
548
- this.page.waitForLoadState("networkidle");
586
+ await this.handleAnySpecialADLoginScreen();
549
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
+ }
550
596
  });
551
597
  await test.step("Login with eHerkenning credentials as bewindvoerder", async () => {
552
598
  try {
553
599
  await this.tryLoginWithEHerkenning(gemachtigde);
554
600
  } catch (_error) {
555
- await this.openPage();
601
+ await openLogin();
556
602
  await this.tryLoginWithEHerkenning(gemachtigde);
557
603
  }
558
604
  });
559
605
  await test.step("Search for client by BSN and accept cookies", async () => {
560
- if (gemachtigde.bsn != null) {
606
+ const bsn = gemachtigde.identifier;
607
+ if (bsn != null) {
561
608
  await this.continueLink.click();
562
- await maskedFill(this.inputBsn, gemachtigde.bsn, "bsn");
609
+ await maskedFill(this.inputBsn, bsn, "bsn");
563
610
  }
564
611
  await this.searchButton.click();
565
612
  await this.continueLink.click();
613
+ await this.waitForApp(options);
566
614
  await this.acceptCookiesForApp(options);
567
615
  });
568
616
  if (file) await test.step("Save session state", async () => {
@@ -570,8 +618,7 @@ var EHerkenningLoginPage = class extends BaseLoginPage {
570
618
  });
571
619
  }
572
620
  };
573
- //#endregion
574
- //#region src/auth/loginhandlers/digidLoginHandler.ts
621
+ // src/auth/loginhandlers/digidLoginHandler.ts
575
622
  var DigidLoginHandler = class {
576
623
  options;
577
624
  /**
@@ -595,8 +642,7 @@ var DigidLoginHandler = class {
595
642
  await new DigidLoginPage(page).loginAndCreateNewSession(account, file, this.options);
596
643
  }
597
644
  };
598
- //#endregion
599
- //#region src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
645
+ // src/auth/loginhandlers/eHerkenningBewindvoerderLoginHandler.ts
600
646
  var EHerkenningBewindvoerderLoginHandler = class {
601
647
  options;
602
648
  /**
@@ -620,8 +666,7 @@ var EHerkenningBewindvoerderLoginHandler = class {
620
666
  await new EHerkenningLoginPage(page).loginAsProfessionalBewindvoerder(account, this.options, file);
621
667
  }
622
668
  };
623
- //#endregion
624
- //#region src/auth/loginhandlers/eHerkenningLoginHandler.ts
669
+ // src/auth/loginhandlers/eHerkenningLoginHandler.ts
625
670
  var EHerkenningLoginHandler = class {
626
671
  options;
627
672
  /**
@@ -645,8 +690,7 @@ var EHerkenningLoginHandler = class {
645
690
  await new EHerkenningLoginPage(page).loginWithEHerkenningVestigingAndCreateSession(file, account, this.options);
646
691
  }
647
692
  };
648
- //#endregion
649
- //#region src/auth/loginhandlers/localhostLoginHandler.ts
693
+ // src/auth/loginhandlers/localhostLoginHandler.ts
650
694
  var LocalhostLoginHandler = class {
651
695
  /**
652
696
  * @param page the Playwright page to perform the login on
@@ -657,8 +701,7 @@ var LocalhostLoginHandler = class {
657
701
  await new LocalLoginPage(page).loginAndCreateNewSession(account, file);
658
702
  }
659
703
  };
660
- //#endregion
661
- //#region src/auth/getLoginHandler.ts
704
+ // src/auth/getLoginHandler.ts
662
705
  /**
663
706
  * Shortcut for creating the login handler for an auth type. Creating the handler directly, e.g.
664
707
  * `new DigidLoginHandler(options)`, checks at compile time that the required options are there;
@@ -702,10 +745,18 @@ function loginOptions(authType, options) {
702
745
  loginButton: options.loginButton
703
746
  };
704
747
  }
705
- //#endregion
706
- //#region src/auth/sessionHandler.ts
748
+ // src/auth/sessionHandler.ts
707
749
  /** Default max age for `SessionManager.getOrCreateSession`. For an `ad-session`, a longer one (e.g. 24h) saves AD logins. */
708
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
+ }
709
760
  /**
710
761
  * This class creates the correct SessionHandler
711
762
  * It will also perform the process of setting op the session
@@ -715,6 +766,10 @@ var MAX_SESSION_TIME_IN_MINUTES = 10;
715
766
  * @param loginHandler that will handle the login itself
716
767
  */
717
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;
718
773
  /**
719
774
  * Setup the new session
720
775
  * If needed the AD Session if used (Needed outside the firewall)
@@ -723,13 +778,9 @@ function createSessionHandler(authType, account, loginHandler) {
723
778
  * @param file
724
779
  */
725
780
  const setupSession = async (browser, file) => {
726
- const useADSession = process.env.WITH_AD_SESSION === "true";
727
781
  const page = await browser.newPage({
728
782
  ignoreHTTPSErrors: true,
729
- storageState: useADSession && authType !== "ad-session" ? SessionFileHelper.getADFileName(browser, {
730
- username: `${process.env.AD_USER}`,
731
- password: `${process.env.AD_PASSWORD}`
732
- }) : void 0
783
+ storageState: getADFile(browser)
733
784
  });
734
785
  console.log(`New session will be created: ${file}`);
735
786
  try {
@@ -758,6 +809,7 @@ function createSessionHandler(authType, account, loginHandler) {
758
809
  * This is being called from the nl-portal-base-library
759
810
  *
760
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.
761
813
  *
762
814
  * @param browser
763
815
  * @param file
@@ -768,13 +820,21 @@ function createSessionHandler(authType, account, loginHandler) {
768
820
  await setupSession(browser, file);
769
821
  return;
770
822
  }
823
+ const adFile = getADFile(browser);
771
824
  const page = await browser.newPage({
772
825
  ignoreHTTPSErrors: true,
773
- storageState: file
826
+ storageState: adFile ? withADCookies(file, adFile) : file
774
827
  });
775
828
  console.log(`Refresh of session started for : ${file}`);
776
- await page.goto(getUrl(Url.PortalBaseUrl));
829
+ const portalUrl = getUrl(Url.PortalBaseUrl);
830
+ await page.goto(portalUrl);
777
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
+ }
778
838
  if (page.url().match(/authn/)) {
779
839
  console.log(`New session will be created as the current one is no longer valid: ${file}`);
780
840
  try {
@@ -790,8 +850,7 @@ function createSessionHandler(authType, account, loginHandler) {
790
850
  }
791
851
  };
792
852
  }
793
- //#endregion
794
- //#region src/auth/api/apiTokenHelper.ts
853
+ // src/auth/api/apiTokenHelper.ts
795
854
  /**
796
855
  * The token is often being refreshed so the easiest is to open a browser using the current session
797
856
  * The UI will automatically refresh the token and that is the token we will return
@@ -843,8 +902,7 @@ function getApiTokenFromSession(baseTest, handler) {
843
902
  }
844
903
  });
845
904
  }
846
- //#endregion
847
- //#region src/auth/getSessionHandler.ts
905
+ // src/auth/getSessionHandler.ts
848
906
  /**
849
907
  * @param testProfile the test user to log in
850
908
  * @param loginOptions the app's login options, from which the handler for `testProfile.authType` is created
@@ -865,5 +923,4 @@ function getApiTokenFromSession(baseTest, handler) {
865
923
  function getSessionHandler(testProfile, loginOptions, loginHandler) {
866
924
  return createSessionHandler(testProfile.authType, testProfile.account, loginHandler ?? getLoginHandler(testProfile.authType, loginOptions));
867
925
  }
868
- //#endregion
869
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.3.0",
3
+ "version": "3.0.1",
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": [