@virtocommerce/test-automation-framework 0.0.0-stage → 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.biome/formatter.json +11 -0
- package/.biome/imports.json +52 -0
- package/.biome/preset.json +4 -0
- package/.biome/rules.json +45 -0
- package/.claude/agents/qa-automation-expert.md +119 -0
- package/.claude/agents/qa-coverage.md +96 -0
- package/.claude/agents/qa-explorer.md +112 -0
- package/.claude/agents/qa-healer.md +88 -0
- package/.claude/agents/qa-judge.md +102 -0
- package/.claude/agents/qa-planner.md +104 -0
- package/.claude/agents/qa-reviewer.md +121 -0
- package/.claude/checks/browser-secrets.mts +107 -0
- package/.claude/checks/contract.mts +469 -0
- package/.claude/checks/expectation-guard.mts +665 -0
- package/.claude/checks/explore-extractors.mts +4 -0
- package/.claude/checks/judge-verdict.mts +165 -0
- package/.claude/checks/project-facts.mts +491 -0
- package/.claude/checks/prove-fails.mts +770 -0
- package/.claude/checks/rank-gaps.mts +177 -0
- package/.claude/checks/readonly-shell.mts +740 -0
- package/.claude/checks/reconcile-run.mts +270 -0
- package/.claude/checks/scan-prompts.mts +351 -0
- package/.claude/checks/stand.mts +45 -0
- package/.claude/checks/test-duration.mts +134 -0
- package/.claude/checks/test-shape.mts +224 -0
- package/.claude/checks/ticket-card.mts +195 -0
- package/.claude/commands/qa-coverage.md +13 -0
- package/.claude/commands/qa-explore.md +17 -0
- package/.claude/commands/qa-heal.md +44 -0
- package/.claude/commands/qa-implement.md +60 -0
- package/.claude/commands/qa-plan.md +55 -0
- package/.claude/commands/qa-review.md +90 -0
- package/.claude/commands/qa.md +156 -0
- package/.claude/hooks/readonly-shell.mts +65 -0
- package/.claude/settings.json +15 -0
- package/.claude/skills/coverage-analysis/SKILL.md +107 -0
- package/.claude/skills/create-graphql-layer/SKILL.md +159 -0
- package/.claude/skills/create-ui-layer/SKILL.md +189 -0
- package/.claude/skills/explore-api/SKILL.md +74 -0
- package/.claude/skills/explore-frontend/SKILL.md +85 -0
- package/.claude/skills/framework-rules/SKILL.md +189 -0
- package/.claude/skills/heal-tests/SKILL.md +197 -0
- package/.claude/skills/heal-tests/guard-recipe.md +53 -0
- package/.claude/skills/judge-criteria/SKILL.md +40 -0
- package/.claude/skills/judge-criteria/coverage.md +9 -0
- package/.claude/skills/judge-criteria/expert.md +23 -0
- package/.claude/skills/judge-criteria/explorer.md +9 -0
- package/.claude/skills/judge-criteria/healer.md +13 -0
- package/.claude/skills/judge-criteria/planner.md +12 -0
- package/.claude/skills/plan-implementation/SKILL.md +82 -0
- package/.claude/skills/plan-implementation/contract-template.md +72 -0
- package/.claude/skills/plan-test-strategy/SKILL.md +100 -0
- package/.claude/skills/project-facts/SKILL.md +130 -0
- package/.claude/skills/read-change/SKILL.md +64 -0
- package/.claude/skills/read-ticket/SKILL.md +63 -0
- package/.claude/skills/read-ticket/providers.md +58 -0
- package/.claude/skills/review-pr/SKILL.md +152 -0
- package/.claude/skills/review-test-code/SKILL.md +208 -0
- package/.claude/skills/write-e2e-test/SKILL.md +175 -0
- package/.claude/skills/write-graphql-test/SKILL.md +158 -0
- package/.claude/skills/write-rest-api-test/SKILL.md +182 -0
- package/.claude/skills/write-security-test/SKILL.md +253 -0
- package/.qa/project.example.json +71 -0
- package/CHANGELOG.md +1 -0
- package/LICENSE +12 -0
- package/README.md +53 -2
- package/bin/install-qa-agents.mjs +94 -0
- package/dist/auth/credentials.d.ts +10 -0
- package/dist/auth/credentials.js +2 -0
- package/dist/auth/credentials.js.map +1 -0
- package/dist/auth/frontend-browser-sessions.d.ts +71 -0
- package/dist/auth/frontend-browser-sessions.js +130 -0
- package/dist/auth/frontend-browser-sessions.js.map +1 -0
- package/dist/auth/index.d.ts +9 -0
- package/dist/auth/index.js +5 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/platform-browser-sessions.d.ts +47 -0
- package/dist/auth/platform-browser-sessions.js +92 -0
- package/dist/auth/platform-browser-sessions.js.map +1 -0
- package/dist/auth/sign-in-lock.d.ts +14 -0
- package/dist/auth/sign-in-lock.js +70 -0
- package/dist/auth/sign-in-lock.js.map +1 -0
- package/dist/auth/storage-state.d.ts +3 -0
- package/dist/auth/storage-state.js +2 -0
- package/dist/auth/storage-state.js.map +1 -0
- package/dist/auth/token-client.d.ts +82 -0
- package/dist/auth/token-client.js +111 -0
- package/dist/auth/token-client.js.map +1 -0
- package/dist/auth/token-manager.d.ts +67 -0
- package/dist/auth/token-manager.js +138 -0
- package/dist/auth/token-manager.js.map +1 -0
- package/dist/core/default-reporters.d.ts +31 -0
- package/dist/core/default-reporters.js +36 -0
- package/dist/core/default-reporters.js.map +1 -0
- package/dist/core/default-use.d.ts +28 -0
- package/dist/core/default-use.js +25 -0
- package/dist/core/default-use.js.map +1 -0
- package/dist/core/env.d.ts +24 -0
- package/dist/core/env.js +33 -0
- package/dist/core/env.js.map +1 -0
- package/dist/core/error-message.d.ts +10 -0
- package/dist/core/error-message.js +13 -0
- package/dist/core/error-message.js.map +1 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +11 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/is-ci.d.ts +14 -0
- package/dist/core/is-ci.js +18 -0
- package/dist/core/is-ci.js.map +1 -0
- package/dist/core/parse-env.d.ts +13 -0
- package/dist/core/parse-env.js +21 -0
- package/dist/core/parse-env.js.map +1 -0
- package/dist/core/projects.d.ts +24 -0
- package/dist/core/projects.js +33 -0
- package/dist/core/projects.js.map +1 -0
- package/dist/core/run-options.d.ts +31 -0
- package/dist/core/run-options.js +43 -0
- package/dist/core/run-options.js.map +1 -0
- package/dist/core/secret.d.ts +105 -0
- package/dist/core/secret.js +167 -0
- package/dist/core/secret.js.map +1 -0
- package/dist/core/string-schemas.d.ts +39 -0
- package/dist/core/string-schemas.js +56 -0
- package/dist/core/string-schemas.js.map +1 -0
- package/dist/core/url-path.d.ts +7 -0
- package/dist/core/url-path.js +2 -0
- package/dist/core/url-path.js.map +1 -0
- package/dist/dataset/collection.d.ts +44 -0
- package/dist/dataset/collection.js +76 -0
- package/dist/dataset/collection.js.map +1 -0
- package/dist/dataset/index.d.ts +11 -0
- package/dist/dataset/index.js +6 -0
- package/dist/dataset/index.js.map +1 -0
- package/dist/dataset/load-dataset.d.ts +39 -0
- package/dist/dataset/load-dataset.js +62 -0
- package/dist/dataset/load-dataset.js.map +1 -0
- package/dist/dataset/manifest.d.ts +77 -0
- package/dist/dataset/manifest.js +10 -0
- package/dist/dataset/manifest.js.map +1 -0
- package/dist/dataset/placeholders.d.ts +66 -0
- package/dist/dataset/placeholders.js +87 -0
- package/dist/dataset/placeholders.js.map +1 -0
- package/dist/dataset/seed-collection.d.ts +53 -0
- package/dist/dataset/seed-collection.js +115 -0
- package/dist/dataset/seed-collection.js.map +1 -0
- package/dist/dataset/seed-dataset.d.ts +70 -0
- package/dist/dataset/seed-dataset.js +138 -0
- package/dist/dataset/seed-dataset.js.map +1 -0
- package/dist/dataset/seed-events.d.ts +81 -0
- package/dist/dataset/seed-events.js +2 -0
- package/dist/dataset/seed-events.js.map +1 -0
- package/dist/dataset/seed-requests.d.ts +102 -0
- package/dist/dataset/seed-requests.js +160 -0
- package/dist/dataset/seed-requests.js.map +1 -0
- package/dist/dataset/seed-scope.d.ts +39 -0
- package/dist/dataset/seed-scope.js +67 -0
- package/dist/dataset/seed-scope.js.map +1 -0
- package/dist/fixtures/default-fixtures.d.ts +93 -0
- package/dist/fixtures/default-fixtures.js +105 -0
- package/dist/fixtures/default-fixtures.js.map +1 -0
- package/dist/fixtures/index.d.ts +2 -0
- package/dist/fixtures/index.js +2 -0
- package/dist/fixtures/index.js.map +1 -0
- package/dist/graphql/graphql-client.d.ts +78 -0
- package/dist/graphql/graphql-client.js +83 -0
- package/dist/graphql/graphql-client.js.map +1 -0
- package/dist/graphql/graphql-codegen.d.ts +56 -0
- package/dist/graphql/graphql-codegen.js +42 -0
- package/dist/graphql/graphql-codegen.js.map +1 -0
- package/dist/graphql/graphql-error.d.ts +54 -0
- package/dist/graphql/graphql-error.js +74 -0
- package/dist/graphql/graphql-error.js.map +1 -0
- package/dist/graphql/index.d.ts +6 -0
- package/dist/graphql/index.js +4 -0
- package/dist/graphql/index.js.map +1 -0
- package/dist/http/authentication.d.ts +16 -0
- package/dist/http/authentication.js +2 -0
- package/dist/http/authentication.js.map +1 -0
- package/dist/http/http-client.d.ts +110 -0
- package/dist/http/http-client.js +237 -0
- package/dist/http/http-client.js.map +1 -0
- package/dist/http/http-error.d.ts +26 -0
- package/dist/http/http-error.js +34 -0
- package/dist/http/http-error.js.map +1 -0
- package/dist/http/http-method.d.ts +2 -0
- package/dist/http/http-method.js +2 -0
- package/dist/http/http-method.js.map +1 -0
- package/dist/http/http-response.d.ts +137 -0
- package/dist/http/http-response.js +166 -0
- package/dist/http/http-response.js.map +1 -0
- package/dist/http/index.d.ts +7 -0
- package/dist/http/index.js +4 -0
- package/dist/http/index.js.map +1 -0
- package/dist/http/request-options.d.ts +62 -0
- package/dist/http/request-options.js +2 -0
- package/dist/http/request-options.js.map +1 -0
- package/dist/modules/index.d.ts +2 -0
- package/dist/modules/index.js +2 -0
- package/dist/modules/index.js.map +1 -0
- package/dist/modules/installed-modules.d.ts +86 -0
- package/dist/modules/installed-modules.js +135 -0
- package/dist/modules/installed-modules.js.map +1 -0
- package/docs/README.md +43 -0
- package/docs/concepts/areas.md +38 -0
- package/docs/concepts/auth.md +92 -0
- package/docs/concepts/config.md +102 -0
- package/docs/concepts/dataset.md +183 -0
- package/docs/concepts/environment.md +54 -0
- package/docs/concepts/fixtures.md +109 -0
- package/docs/concepts/graphql.md +76 -0
- package/docs/concepts/http.md +88 -0
- package/docs/concepts/modules.md +63 -0
- package/docs/concepts/secrets.md +50 -0
- package/docs/contributing/architecture.md +67 -0
- package/docs/contributing/conventions.md +39 -0
- package/docs/contributing/documentation.md +37 -0
- package/docs/contributing/releasing.md +76 -0
- package/docs/examples/auth.ts +20 -0
- package/docs/examples/config.ts +36 -0
- package/docs/examples/dataset.ts +70 -0
- package/docs/examples/environment.ts +8 -0
- package/docs/examples/fixtures.ts +41 -0
- package/docs/examples/getting-started.ts +22 -0
- package/docs/examples/graphql-codegen.ts +9 -0
- package/docs/examples/graphql.ts +32 -0
- package/docs/examples/http.ts +18 -0
- package/docs/examples/modules.ts +19 -0
- package/docs/examples/secrets.ts +11 -0
- package/docs/examples/tsconfig.json +10 -0
- package/docs/getting-started.md +106 -0
- package/docs/guides/generating-types.md +75 -0
- package/docs/guides/qa-agents.md +66 -0
- package/package.json +156 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Copyright (c) Virto Solutions LTD. All rights reserved.
|
|
2
|
+
|
|
3
|
+
Licensed under the Virto Commerce Open Software License (the "License"); you
|
|
4
|
+
may not use this file except in compliance with the License. You may
|
|
5
|
+
obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
https://virtocommerce.com/open-source-license
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
12
|
+
implied.
|
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @virtocommerce/test-automation-framework
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A Playwright Test framework for the API and browser test suites of Virto Commerce-based solutions. It holds what is the
|
|
4
|
+
same on every Virto Commerce platform. Each solution's test suite installs it as an npm package and adds its own code
|
|
5
|
+
on top: API clients, page objects, test data and tests.
|
|
6
|
+
|
|
7
|
+
> **Status: early development.** While the version is `0.x`, any minor release may contain breaking changes. Read
|
|
8
|
+
> [CHANGELOG.md](CHANGELOG.md) before upgrading.
|
|
9
|
+
|
|
10
|
+
## Requirements
|
|
11
|
+
|
|
12
|
+
- Node.js 22.18 or newer
|
|
13
|
+
- `@playwright/test` 1.65.1 or newer and `zod` 4.0.7 or newer, installed in your repository
|
|
14
|
+
- `@types/node` in your repository, since the framework's types use Node types such as `Buffer`
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
The package is published to the public npm registry, so installing it needs no token:
|
|
18
|
+
|
|
19
|
+
```shell
|
|
20
|
+
npm install --save-dev @virtocommerce/test-automation-framework
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Every version carries an npm provenance attestation that ties it to the GitHub Actions run that published it;
|
|
24
|
+
`npm audit signatures` checks it.
|
|
25
|
+
|
|
26
|
+
## Documentation
|
|
27
|
+
|
|
28
|
+
The documentation ships with the package, in `node_modules/@virtocommerce/test-automation-framework/docs`, so it
|
|
29
|
+
always matches the installed version.
|
|
30
|
+
|
|
31
|
+
- [Getting started](docs/getting-started.md): set up a test suite and write its first test.
|
|
32
|
+
- [QA agents](docs/guides/qa-agents.md): install the Claude Code agents that generate and maintain the tests.
|
|
33
|
+
- [Documentation index](docs/README.md): concepts, terms and contributing to the framework.
|
|
34
|
+
|
|
35
|
+
## Entry points
|
|
36
|
+
|
|
37
|
+
| Entry point | Contains |
|
|
38
|
+
| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
|
39
|
+
| `@virtocommerce/test-automation-framework/core` | Secrets and masking, string schemas, the environment variables and their parsing, Playwright config helpers |
|
|
40
|
+
| `@virtocommerce/test-automation-framework/graphql` | The GraphQL client, its results and errors, and the configuration for generating typed documents |
|
|
41
|
+
| `@virtocommerce/test-automation-framework/http` | The HTTP client, its responses and its errors |
|
|
42
|
+
| `@virtocommerce/test-automation-framework/auth` | Platform sign-in: credentials, access tokens, the token client and manager, and browser sessions |
|
|
43
|
+
| `@virtocommerce/test-automation-framework/modules` | The modules installed on the platform and the module requirements of tests and dataset collections |
|
|
44
|
+
| `@virtocommerce/test-automation-framework/dataset` | Loading a dataset from JSON files and seeding it into the platform, driven by a manifest |
|
|
45
|
+
| `@virtocommerce/test-automation-framework/fixtures` | The default Playwright fixtures: clients, signed-in users, module requirements and browser sessions |
|
|
46
|
+
|
|
47
|
+
Only what an entry point exports is public API. Modules that an entry point does not export can change in any release.
|
|
48
|
+
|
|
49
|
+
## This repository
|
|
50
|
+
|
|
51
|
+
Besides the framework, the repository holds the Virto Commerce test suite in `virtocommerce/`, which uses the
|
|
52
|
+
framework like any other suite, and the QA agents for Claude Code in `.claude/`, which the package ships. See
|
|
53
|
+
[virtocommerce/README.md](virtocommerce/README.md) for running the suite, and
|
|
54
|
+
[the architecture page](docs/contributing/architecture.md) for how the repository is laid out.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname, join, relative } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
7
|
+
const AGENT_DIRS = ["agents", "commands", "skills", "checks", "hooks"];
|
|
8
|
+
const HOOK_SCRIPT = ".claude/hooks/readonly-shell.mts";
|
|
9
|
+
const GITIGNORE_LINES = [
|
|
10
|
+
".qa/contracts/",
|
|
11
|
+
".qa/runs/",
|
|
12
|
+
".qa/reports/",
|
|
13
|
+
".qa/kb/",
|
|
14
|
+
".qa/judge/",
|
|
15
|
+
".qa/*.local.env",
|
|
16
|
+
".qa/client-terms.local.txt",
|
|
17
|
+
".playwright-mcp/",
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
function copyAgentFiles(target) {
|
|
21
|
+
const copied = [];
|
|
22
|
+
for (const dir of AGENT_DIRS) {
|
|
23
|
+
const source = join(PACKAGE_ROOT, ".claude", dir);
|
|
24
|
+
if (!existsSync(source)) {
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
cpSync(source, join(target, ".claude", dir), {
|
|
28
|
+
recursive: true,
|
|
29
|
+
force: true,
|
|
30
|
+
filter: (path) => {
|
|
31
|
+
if (statSync(path).isFile()) {
|
|
32
|
+
copied.push(relative(PACKAGE_ROOT, path));
|
|
33
|
+
}
|
|
34
|
+
return true;
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return copied;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function copyIfMissing(source, destination) {
|
|
42
|
+
if (existsSync(destination)) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
46
|
+
cpSync(source, destination);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function hasHook(settingsPath) {
|
|
51
|
+
return readFileSync(settingsPath, "utf8").includes(HOOK_SCRIPT.split("/").pop());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function missingIgnores(target) {
|
|
55
|
+
const path = join(target, ".gitignore");
|
|
56
|
+
const ignored = existsSync(path) ? readFileSync(path, "utf8").split(/\r?\n/) : [];
|
|
57
|
+
return GITIGNORE_LINES.filter((line) => !ignored.includes(line));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function install(target) {
|
|
61
|
+
const lines = [];
|
|
62
|
+
const copied = copyAgentFiles(target);
|
|
63
|
+
lines.push(`Copied ${copied.length} files into .claude/ (agents, commands, skills, checks, hooks).`);
|
|
64
|
+
|
|
65
|
+
const settings = join(target, ".claude", "settings.json");
|
|
66
|
+
if (copyIfMissing(join(PACKAGE_ROOT, ".claude", "settings.json"), settings)) {
|
|
67
|
+
lines.push("Created .claude/settings.json with the read-only shell hook.");
|
|
68
|
+
} else if (!hasHook(settings)) {
|
|
69
|
+
lines.push(
|
|
70
|
+
`Kept your .claude/settings.json. Add the PreToolUse hook of the package's .claude/settings.json to it: ` +
|
|
71
|
+
`without it the read-only agents are not restricted.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (copyIfMissing(join(PACKAGE_ROOT, ".qa", "project.example.json"), join(target, ".qa", "project.json"))) {
|
|
76
|
+
lines.push("Created .qa/project.json from the example. Replace its example values with this repository's facts:");
|
|
77
|
+
lines.push("every agent reads it. node .claude/checks/project-facts.mts validates it.");
|
|
78
|
+
} else {
|
|
79
|
+
lines.push("Kept your .qa/project.json.");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const ignores = missingIgnores(target);
|
|
83
|
+
if (ignores.length > 0) {
|
|
84
|
+
lines.push(`Add to .gitignore: ${ignores.join(" ")}`);
|
|
85
|
+
}
|
|
86
|
+
if (!existsSync(join(target, "node_modules", "@babel", "parser"))) {
|
|
87
|
+
lines.push("The checks need @babel/parser: npm install --save-dev --save-exact @babel/parser");
|
|
88
|
+
}
|
|
89
|
+
return lines;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
for (const line of install(process.cwd())) {
|
|
93
|
+
process.stdout.write(`${line}\n`);
|
|
94
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Secret } from "../core/index.js";
|
|
2
|
+
/** The sign-in data of a platform or frontend user. It is safe to log, because the password is a {@link Secret}. */
|
|
3
|
+
export interface Credentials {
|
|
4
|
+
/** The user name. For a frontend user, it is usually the e-mail address. */
|
|
5
|
+
readonly username: string;
|
|
6
|
+
/** The password of the user. */
|
|
7
|
+
readonly password: Secret;
|
|
8
|
+
/** The store that a frontend user signs in to. It is omitted for platform users, such as the administrator. */
|
|
9
|
+
readonly storeId?: string;
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credentials.js","sourceRoot":"","sources":["../../src/auth/credentials.ts"],"names":[],"mappings":"","sourcesContent":["import type { Secret } from \"@/core\";\n\n/** The sign-in data of a platform or frontend user. It is safe to log, because the password is a {@link Secret}. */\nexport interface Credentials {\n /** The user name. For a frontend user, it is usually the e-mail address. */\n readonly username: string;\n /** The password of the user. */\n readonly password: Secret;\n /** The store that a frontend user signs in to. It is omitted for platform users, such as the administrator. */\n readonly storeId?: string;\n}\n"]}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { APIRequestContext } from "@playwright/test";
|
|
2
|
+
import type { Credentials } from "./credentials.ts";
|
|
3
|
+
import type { StorageState } from "./storage-state.ts";
|
|
4
|
+
/** The local storage keys where a frontend keeps its sign-in. */
|
|
5
|
+
export interface FrontendStorageKeys {
|
|
6
|
+
/** The key of the token entry. The default is `auth`, the key of the Virto Commerce frontend. */
|
|
7
|
+
readonly token?: string | undefined;
|
|
8
|
+
/** The key of an anonymous visitor's identifier. The default is `user-id`, the key of the Virto Commerce frontend. */
|
|
9
|
+
readonly anonymousUserId?: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
/** The options of {@link FrontendBrowserSessions}. */
|
|
12
|
+
export interface FrontendBrowserSessionsOptions {
|
|
13
|
+
/** Creates a request context, one for each frontend. The sessions dispose of every context they create. */
|
|
14
|
+
readonly newContext: () => Promise<APIRequestContext>;
|
|
15
|
+
/** Where the frontends keep their sign-in in local storage. The defaults are those of the Virto Commerce frontend. */
|
|
16
|
+
readonly storageKeys?: FrontendStorageKeys | undefined;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Builds the storage states that start a browser on a frontend, signed in or as an anonymous visitor, so browser tests
|
|
20
|
+
* skip the sign-in page.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* - A signed-in state holds a token in local storage, requested through the frontend's own origin. The entry is
|
|
24
|
+
* `{ expires_at, token_type, access_token, refresh_token }`, the format of the Virto Commerce frontend.
|
|
25
|
+
* - Tokens are kept for each user and frontend until {@link FrontendBrowserSessions.signOut} or
|
|
26
|
+
* {@link FrontendBrowserSessions.dispose}, which revoke them.
|
|
27
|
+
* - A storage state holds secrets in plain text, so never log it or attach it to a report.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* await context.setStorageState(await frontendSessions.signedIn(env.FRONTEND_BASE_URL, customer));
|
|
31
|
+
*/
|
|
32
|
+
export declare class FrontendBrowserSessions {
|
|
33
|
+
#private;
|
|
34
|
+
/**
|
|
35
|
+
* Creates the frontend sessions of a worker.
|
|
36
|
+
*
|
|
37
|
+
* @param options - The factory of request contexts and the storage keys.
|
|
38
|
+
*/
|
|
39
|
+
constructor(options: FrontendBrowserSessionsOptions);
|
|
40
|
+
/**
|
|
41
|
+
* Returns a storage state with a user signed in to a frontend. Concurrent calls for one user share one sign-in.
|
|
42
|
+
*
|
|
43
|
+
* @param frontendBaseUrl - The base URL of the frontend, such as `https://frontend.example.com`.
|
|
44
|
+
* @param credentials - The user, with the store of the frontend.
|
|
45
|
+
* @returns The storage state, for `setStorageState` of a browser context.
|
|
46
|
+
* @throws {HttpError} The frontend refuses the sign-in.
|
|
47
|
+
*/
|
|
48
|
+
signedIn(frontendBaseUrl: string, credentials: Credentials): Promise<StorageState>;
|
|
49
|
+
/**
|
|
50
|
+
* Returns a storage state of an anonymous visitor of a frontend. It sends no requests.
|
|
51
|
+
*
|
|
52
|
+
* @param frontendBaseUrl - The base URL of the frontend.
|
|
53
|
+
* @param anonymousUserId - The identifier of the visitor, so the test knows whose cart it works with.
|
|
54
|
+
* @returns The storage state, for `setStorageState` of a browser context.
|
|
55
|
+
*/
|
|
56
|
+
anonymous(frontendBaseUrl: string, anonymousUserId: string): StorageState;
|
|
57
|
+
/**
|
|
58
|
+
* Revokes a user's tokens on every frontend, such as before the user is deleted.
|
|
59
|
+
*
|
|
60
|
+
* @param credentials - The user.
|
|
61
|
+
* @throws {HttpError} A frontend does not confirm the revocation.
|
|
62
|
+
*/
|
|
63
|
+
signOut(credentials: Credentials): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Revokes every token and disposes of the request contexts.
|
|
66
|
+
*
|
|
67
|
+
* @throws {Error} A frontend does not confirm a revocation. Every context is disposed of first.
|
|
68
|
+
* @throws {AggregateError} Several frontends do not confirm revocations.
|
|
69
|
+
*/
|
|
70
|
+
dispose(): Promise<void>;
|
|
71
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { HttpClient } from "../http/index.js";
|
|
2
|
+
import { TokenClient } from "./token-client.js";
|
|
3
|
+
import { TokenManager } from "./token-manager.js";
|
|
4
|
+
/**
|
|
5
|
+
* Builds the storage states that start a browser on a frontend, signed in or as an anonymous visitor, so browser tests
|
|
6
|
+
* skip the sign-in page.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* - A signed-in state holds a token in local storage, requested through the frontend's own origin. The entry is
|
|
10
|
+
* `{ expires_at, token_type, access_token, refresh_token }`, the format of the Virto Commerce frontend.
|
|
11
|
+
* - Tokens are kept for each user and frontend until {@link FrontendBrowserSessions.signOut} or
|
|
12
|
+
* {@link FrontendBrowserSessions.dispose}, which revoke them.
|
|
13
|
+
* - A storage state holds secrets in plain text, so never log it or attach it to a report.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* await context.setStorageState(await frontendSessions.signedIn(env.FRONTEND_BASE_URL, customer));
|
|
17
|
+
*/
|
|
18
|
+
export class FrontendBrowserSessions {
|
|
19
|
+
#newContext;
|
|
20
|
+
#tokenKey;
|
|
21
|
+
#anonymousUserIdKey;
|
|
22
|
+
#frontends = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Creates the frontend sessions of a worker.
|
|
25
|
+
*
|
|
26
|
+
* @param options - The factory of request contexts and the storage keys.
|
|
27
|
+
*/
|
|
28
|
+
constructor(options) {
|
|
29
|
+
this.#newContext = options.newContext;
|
|
30
|
+
this.#tokenKey = options.storageKeys?.token ?? "auth";
|
|
31
|
+
this.#anonymousUserIdKey = options.storageKeys?.anonymousUserId ?? "user-id";
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Returns a storage state with a user signed in to a frontend. Concurrent calls for one user share one sign-in.
|
|
35
|
+
*
|
|
36
|
+
* @param frontendBaseUrl - The base URL of the frontend, such as `https://frontend.example.com`.
|
|
37
|
+
* @param credentials - The user, with the store of the frontend.
|
|
38
|
+
* @returns The storage state, for `setStorageState` of a browser context.
|
|
39
|
+
* @throws {HttpError} The frontend refuses the sign-in.
|
|
40
|
+
*/
|
|
41
|
+
async signedIn(frontendBaseUrl, credentials) {
|
|
42
|
+
const { tokens } = await this.#frontendTokens(frontendBaseUrl);
|
|
43
|
+
return localStorageState(frontendBaseUrl, this.#tokenKey, tokenEntry(await tokens.token(credentials)));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Returns a storage state of an anonymous visitor of a frontend. It sends no requests.
|
|
47
|
+
*
|
|
48
|
+
* @param frontendBaseUrl - The base URL of the frontend.
|
|
49
|
+
* @param anonymousUserId - The identifier of the visitor, so the test knows whose cart it works with.
|
|
50
|
+
* @returns The storage state, for `setStorageState` of a browser context.
|
|
51
|
+
*/
|
|
52
|
+
anonymous(frontendBaseUrl, anonymousUserId) {
|
|
53
|
+
return localStorageState(frontendBaseUrl, this.#anonymousUserIdKey, anonymousUserId);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Revokes a user's tokens on every frontend, such as before the user is deleted.
|
|
57
|
+
*
|
|
58
|
+
* @param credentials - The user.
|
|
59
|
+
* @throws {HttpError} A frontend does not confirm the revocation.
|
|
60
|
+
*/
|
|
61
|
+
async signOut(credentials) {
|
|
62
|
+
for (const frontend of this.#frontends.values()) {
|
|
63
|
+
await (await frontend).tokens.signOut(credentials);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Revokes every token and disposes of the request contexts.
|
|
68
|
+
*
|
|
69
|
+
* @throws {Error} A frontend does not confirm a revocation. Every context is disposed of first.
|
|
70
|
+
* @throws {AggregateError} Several frontends do not confirm revocations.
|
|
71
|
+
*/
|
|
72
|
+
async dispose() {
|
|
73
|
+
const frontends = [...this.#frontends.values()];
|
|
74
|
+
this.#frontends.clear();
|
|
75
|
+
const errors = [];
|
|
76
|
+
for (const frontend of frontends) {
|
|
77
|
+
try {
|
|
78
|
+
const { context, tokens } = await frontend;
|
|
79
|
+
try {
|
|
80
|
+
await tokens.signOutAll();
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
await context.dispose();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
errors.push(error);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (errors.length === 1) {
|
|
91
|
+
throw errors[0];
|
|
92
|
+
}
|
|
93
|
+
if (errors.length > 1) {
|
|
94
|
+
throw new AggregateError(errors, `${errors.length} frontends did not confirm the sign-out`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
#frontendTokens(frontendBaseUrl) {
|
|
98
|
+
const origin = new URL(frontendBaseUrl).origin;
|
|
99
|
+
const existing = this.#frontends.get(origin);
|
|
100
|
+
if (existing !== undefined) {
|
|
101
|
+
return existing;
|
|
102
|
+
}
|
|
103
|
+
const created = this.#newContext().then((context) => ({
|
|
104
|
+
context,
|
|
105
|
+
tokens: new TokenManager(new TokenClient(new HttpClient(context, origin))),
|
|
106
|
+
}));
|
|
107
|
+
this.#frontends.set(origin, created);
|
|
108
|
+
created.catch(() => {
|
|
109
|
+
if (this.#frontends.get(origin) === created) {
|
|
110
|
+
this.#frontends.delete(origin);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
return created;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function tokenEntry(token) {
|
|
117
|
+
return JSON.stringify({
|
|
118
|
+
expires_at: new Date(token.expiresAt).toISOString(),
|
|
119
|
+
token_type: token.tokenType,
|
|
120
|
+
access_token: token.accessToken.reveal(),
|
|
121
|
+
refresh_token: token.refreshToken?.reveal(),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function localStorageState(frontendBaseUrl, name, value) {
|
|
125
|
+
return {
|
|
126
|
+
cookies: [],
|
|
127
|
+
origins: [{ origin: new URL(frontendBaseUrl).origin, localStorage: [{ name, value }] }],
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
//# sourceMappingURL=frontend-browser-sessions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"frontend-browser-sessions.js","sourceRoot":"","sources":["../../src/auth/frontend-browser-sessions.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAuBlD;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,uBAAuB;IACzB,WAAW,CAAmC;IAC9C,SAAS,CAAS;IAClB,mBAAmB,CAAS;IAC5B,UAAU,GAAG,IAAI,GAAG,EAAmC,CAAC;IAEjE;;;;OAIG;IACH,YAAY,OAAuC;QACjD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;QACtC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,WAAW,EAAE,KAAK,IAAI,MAAM,CAAC;QACtD,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,eAAe,IAAI,SAAS,CAAC;IAC/E,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,QAAQ,CAAC,eAAuB,EAAE,WAAwB;QAC9D,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;QAC/D,OAAO,iBAAiB,CAAC,eAAe,EAAE,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;IACzG,CAAC;IAED;;;;;;OAMG;IACH,SAAS,CAAC,eAAuB,EAAE,eAAuB;QACxD,OAAO,iBAAiB,CAAC,eAAe,EAAE,IAAI,CAAC,mBAAmB,EAAE,eAAe,CAAC,CAAC;IACvF,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,OAAO,CAAC,WAAwB;QACpC,KAAK,MAAM,QAAQ,IA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sourcesContent":["import type { APIRequestContext } from \"@playwright/test\";\nimport type { Credentials } from \"./credentials.ts\";\nimport type { StorageState } from \"./storage-state.ts\";\nimport type { AuthToken } from \"./token-client.ts\";\n\nimport { HttpClient } from \"@/http\";\n\nimport { TokenClient } from \"./token-client.ts\";\nimport { TokenManager } from \"./token-manager.ts\";\n\n/** The local storage keys where a frontend keeps its sign-in. */\nexport interface FrontendStorageKeys {\n /** The key of the token entry. The default is `auth`, the key of the Virto Commerce frontend. */\n readonly token?: string | undefined;\n /** The key of an anonymous visitor's identifier. The default is `user-id`, the key of the Virto Commerce frontend. */\n readonly anonymousUserId?: string | undefined;\n}\n\n/** The options of {@link FrontendBrowserSessions}. */\nexport interface FrontendBrowserSessionsOptions {\n /** Creates a request context, one for each frontend. The sessions dispose of every context they create. */\n readonly newContext: () => Promise<APIRequestContext>;\n /** Where the frontends keep their sign-in in local storage. The defaults are those of the Virto Commerce frontend. */\n readonly storageKeys?: FrontendStorageKeys | undefined;\n}\n\ninterface FrontendTokens {\n readonly context: APIRequestContext;\n readonly tokens: TokenManager;\n}\n\n/**\n * Builds the storage states that start a browser on a frontend, signed in or as an anonymous visitor, so browser tests\n * skip the sign-in page.\n *\n * @remarks\n * - A signed-in state holds a token in local storage, requested through the frontend's own origin. The entry is\n * `{ expires_at, token_type, access_token, refresh_token }`, the format of the Virto Commerce frontend.\n * - Tokens are kept for each user and frontend until {@link FrontendBrowserSessions.signOut} or\n * {@link FrontendBrowserSessions.dispose}, which revoke them.\n * - A storage state holds secrets in plain text, so never log it or attach it to a report.\n *\n * @example\n * await context.setStorageState(await frontendSessions.signedIn(env.FRONTEND_BASE_URL, customer));\n */\nexport class FrontendBrowserSessions {\n readonly #newContext: () => Promise<APIRequestContext>;\n readonly #tokenKey: string;\n readonly #anonymousUserIdKey: string;\n readonly #frontends = new Map<string, Promise<FrontendTokens>>();\n\n /**\n * Creates the frontend sessions of a worker.\n *\n * @param options - The factory of request contexts and the storage keys.\n */\n constructor(options: FrontendBrowserSessionsOptions) {\n this.#newContext = options.newContext;\n this.#tokenKey = options.storageKeys?.token ?? \"auth\";\n this.#anonymousUserIdKey = options.storageKeys?.anonymousUserId ?? \"user-id\";\n }\n\n /**\n * Returns a storage state with a user signed in to a frontend. Concurrent calls for one user share one sign-in.\n *\n * @param frontendBaseUrl - The base URL of the frontend, such as `https://frontend.example.com`.\n * @param credentials - The user, with the store of the frontend.\n * @returns The storage state, for `setStorageState` of a browser context.\n * @throws {HttpError} The frontend refuses the sign-in.\n */\n async signedIn(frontendBaseUrl: string, credentials: Credentials): Promise<StorageState> {\n const { tokens } = await this.#frontendTokens(frontendBaseUrl);\n return localStorageState(frontendBaseUrl, this.#tokenKey, tokenEntry(await tokens.token(credentials)));\n }\n\n /**\n * Returns a storage state of an anonymous visitor of a frontend. It sends no requests.\n *\n * @param frontendBaseUrl - The base URL of the frontend.\n * @param anonymousUserId - The identifier of the visitor, so the test knows whose cart it works with.\n * @returns The storage state, for `setStorageState` of a browser context.\n */\n anonymous(frontendBaseUrl: string, anonymousUserId: string): StorageState {\n return localStorageState(frontendBaseUrl, this.#anonymousUserIdKey, anonymousUserId);\n }\n\n /**\n * Revokes a user's tokens on every frontend, such as before the user is deleted.\n *\n * @param credentials - The user.\n * @throws {HttpError} A frontend does not confirm the revocation.\n */\n async signOut(credentials: Credentials): Promise<void> {\n for (const frontend of this.#frontends.values()) {\n await (await frontend).tokens.signOut(credentials);\n }\n }\n\n /**\n * Revokes every token and disposes of the request contexts.\n *\n * @throws {Error} A frontend does not confirm a revocation. Every context is disposed of first.\n * @throws {AggregateError} Several frontends do not confirm revocations.\n */\n async dispose(): Promise<void> {\n const frontends = [...this.#frontends.values()];\n this.#frontends.clear();\n const errors: unknown[] = [];\n for (const frontend of frontends) {\n try {\n const { context, tokens } = await frontend;\n try {\n await tokens.signOutAll();\n } finally {\n await context.dispose();\n }\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw new AggregateError(errors, `${errors.length} frontends did not confirm the sign-out`);\n }\n }\n\n #frontendTokens(frontendBaseUrl: string): Promise<FrontendTokens> {\n const origin = new URL(frontendBaseUrl).origin;\n const existing = this.#frontends.get(origin);\n if (existing !== undefined) {\n return existing;\n }\n const created = this.#newContext().then((context) => ({\n context,\n tokens: new TokenManager(new TokenClient(new HttpClient(context, origin))),\n }));\n this.#frontends.set(origin, created);\n created.catch(() => {\n if (this.#frontends.get(origin) === created) {\n this.#frontends.delete(origin);\n }\n });\n return created;\n }\n}\n\nfunction tokenEntry(token: AuthToken): string {\n return JSON.stringify({\n expires_at: new Date(token.expiresAt).toISOString(),\n token_type: token.tokenType,\n access_token: token.accessToken.reveal(),\n refresh_token: token.refreshToken?.reveal(),\n });\n}\n\nfunction localStorageState(frontendBaseUrl: string, name: string, value: string): StorageState {\n return {\n cookies: [],\n origins: [{ origin: new URL(frontendBaseUrl).origin, localStorage: [{ name, value }] }],\n };\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type { Credentials } from "./credentials.ts";
|
|
2
|
+
export type { FrontendBrowserSessionsOptions, FrontendStorageKeys } from "./frontend-browser-sessions.ts";
|
|
3
|
+
export type { PlatformBrowserSessionsOptions } from "./platform-browser-sessions.ts";
|
|
4
|
+
export type { StorageState } from "./storage-state.ts";
|
|
5
|
+
export type { AuthToken } from "./token-client.ts";
|
|
6
|
+
export { FrontendBrowserSessions } from "./frontend-browser-sessions.ts";
|
|
7
|
+
export { PlatformBrowserSessions } from "./platform-browser-sessions.ts";
|
|
8
|
+
export { authHeader, TokenClient } from "./token-client.ts";
|
|
9
|
+
export { TokenManager } from "./token-manager.ts";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { FrontendBrowserSessions } from "./frontend-browser-sessions.js";
|
|
2
|
+
export { PlatformBrowserSessions } from "./platform-browser-sessions.js";
|
|
3
|
+
export { authHeader, TokenClient } from "./token-client.js";
|
|
4
|
+
export { TokenManager } from "./token-manager.js";
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export type { Credentials } from \"./credentials.ts\";\nexport type { FrontendBrowserSessionsOptions, FrontendStorageKeys } from \"./frontend-browser-sessions.ts\";\nexport type { PlatformBrowserSessionsOptions } from \"./platform-browser-sessions.ts\";\nexport type { StorageState } from \"./storage-state.ts\";\nexport type { AuthToken } from \"./token-client.ts\";\n\nexport { FrontendBrowserSessions } from \"./frontend-browser-sessions.ts\";\nexport { PlatformBrowserSessions } from \"./platform-browser-sessions.ts\";\nexport { authHeader, TokenClient } from \"./token-client.ts\";\nexport { TokenManager } from \"./token-manager.ts\";\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { APIRequestContext } from "@playwright/test";
|
|
2
|
+
import type { Credentials } from "./credentials.ts";
|
|
3
|
+
import type { StorageState } from "./storage-state.ts";
|
|
4
|
+
/** The options of {@link PlatformBrowserSessions}. */
|
|
5
|
+
export interface PlatformBrowserSessionsOptions {
|
|
6
|
+
/** The base URL of the platform, whose admin UI the sessions sign in to. */
|
|
7
|
+
readonly platformBaseUrl: string;
|
|
8
|
+
/** Creates a request context for one sign-in. The sessions dispose of it once the sign-in is done. */
|
|
9
|
+
readonly newContext: () => Promise<APIRequestContext>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Builds the storage states that start a browser signed in to the admin UI of the platform, so browser tests skip the
|
|
13
|
+
* sign-in page.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* - A state holds the sign-in cookie of `POST /api/platform/security/login`, kept for each user. A different password
|
|
17
|
+
* signs in again.
|
|
18
|
+
* - The cookie session expires, but the platform cannot revoke it, so there is nothing to sign out of or dispose of.
|
|
19
|
+
* - A storage state holds secrets in plain text, so never log it or attach it to a report.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* await context.setStorageState(await platformSessions.signedIn(administrator));
|
|
23
|
+
*/
|
|
24
|
+
export declare class PlatformBrowserSessions {
|
|
25
|
+
#private;
|
|
26
|
+
/**
|
|
27
|
+
* Creates the admin UI sessions of a worker.
|
|
28
|
+
*
|
|
29
|
+
* @param options - The platform base URL and the factory of request contexts.
|
|
30
|
+
*/
|
|
31
|
+
constructor(options: PlatformBrowserSessionsOptions);
|
|
32
|
+
/**
|
|
33
|
+
* Returns a storage state with a user signed in to the admin UI. Concurrent calls for one user share one sign-in.
|
|
34
|
+
*
|
|
35
|
+
* @param credentials - The platform user.
|
|
36
|
+
* @returns The storage state, for `setStorageState` of a browser context.
|
|
37
|
+
* @throws {Error} The platform refuses the sign-in. The message names the user and the reason.
|
|
38
|
+
* @throws {HttpError} The sign-in request fails.
|
|
39
|
+
*/
|
|
40
|
+
signedIn(credentials: Credentials): Promise<StorageState>;
|
|
41
|
+
/**
|
|
42
|
+
* Forgets a user's storage state, such as before the user is deleted. The cookie stays valid until it expires.
|
|
43
|
+
*
|
|
44
|
+
* @param credentials - The user.
|
|
45
|
+
*/
|
|
46
|
+
forget(credentials: Credentials): void;
|
|
47
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { boolean, looseObject } from "zod";
|
|
2
|
+
import { HttpClient } from "../http/index.js";
|
|
3
|
+
const LOGIN_PATH = "/api/platform/security/login";
|
|
4
|
+
const signInResultSchema = looseObject({
|
|
5
|
+
succeeded: boolean().nullish(),
|
|
6
|
+
isLockedOut: boolean().nullish(),
|
|
7
|
+
isNotAllowed: boolean().nullish(),
|
|
8
|
+
requiresTwoFactor: boolean().nullish(),
|
|
9
|
+
});
|
|
10
|
+
/**
|
|
11
|
+
* Builds the storage states that start a browser signed in to the admin UI of the platform, so browser tests skip the
|
|
12
|
+
* sign-in page.
|
|
13
|
+
*
|
|
14
|
+
* @remarks
|
|
15
|
+
* - A state holds the sign-in cookie of `POST /api/platform/security/login`, kept for each user. A different password
|
|
16
|
+
* signs in again.
|
|
17
|
+
* - The cookie session expires, but the platform cannot revoke it, so there is nothing to sign out of or dispose of.
|
|
18
|
+
* - A storage state holds secrets in plain text, so never log it or attach it to a report.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* await context.setStorageState(await platformSessions.signedIn(administrator));
|
|
22
|
+
*/
|
|
23
|
+
export class PlatformBrowserSessions {
|
|
24
|
+
#options;
|
|
25
|
+
#sessions = new Map();
|
|
26
|
+
/**
|
|
27
|
+
* Creates the admin UI sessions of a worker.
|
|
28
|
+
*
|
|
29
|
+
* @param options - The platform base URL and the factory of request contexts.
|
|
30
|
+
*/
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.#options = options;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Returns a storage state with a user signed in to the admin UI. Concurrent calls for one user share one sign-in.
|
|
36
|
+
*
|
|
37
|
+
* @param credentials - The platform user.
|
|
38
|
+
* @returns The storage state, for `setStorageState` of a browser context.
|
|
39
|
+
* @throws {Error} The platform refuses the sign-in. The message names the user and the reason.
|
|
40
|
+
* @throws {HttpError} The sign-in request fails.
|
|
41
|
+
*/
|
|
42
|
+
signedIn(credentials) {
|
|
43
|
+
const { username } = credentials;
|
|
44
|
+
const session = this.#sessions.get(username);
|
|
45
|
+
if (session?.credentials.password.equals(credentials.password)) {
|
|
46
|
+
return session.state;
|
|
47
|
+
}
|
|
48
|
+
const state = this.#signIn(credentials);
|
|
49
|
+
this.#sessions.set(username, { credentials, state });
|
|
50
|
+
state.catch(() => {
|
|
51
|
+
if (this.#sessions.get(username)?.state === state) {
|
|
52
|
+
this.#sessions.delete(username);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
return state;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Forgets a user's storage state, such as before the user is deleted. The cookie stays valid until it expires.
|
|
59
|
+
*
|
|
60
|
+
* @param credentials - The user.
|
|
61
|
+
*/
|
|
62
|
+
forget(credentials) {
|
|
63
|
+
this.#sessions.delete(credentials.username);
|
|
64
|
+
}
|
|
65
|
+
async #signIn({ username, password }) {
|
|
66
|
+
const context = await this.#options.newContext();
|
|
67
|
+
try {
|
|
68
|
+
const httpClient = new HttpClient(context, this.#options.platformBaseUrl);
|
|
69
|
+
const result = (await httpClient.post(LOGIN_PATH, { json: { userName: username, password } })).parse(signInResultSchema);
|
|
70
|
+
if (result.succeeded !== true) {
|
|
71
|
+
throw new Error(`Signing in to the platform as ${username} failed: ${rejectionReason(result)}`);
|
|
72
|
+
}
|
|
73
|
+
return await context.storageState();
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await context.dispose();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function rejectionReason(result) {
|
|
81
|
+
if (result.isLockedOut === true) {
|
|
82
|
+
return "the user is locked out";
|
|
83
|
+
}
|
|
84
|
+
if (result.isNotAllowed === true) {
|
|
85
|
+
return "the user is not allowed to sign in, for example because the email address is not confirmed";
|
|
86
|
+
}
|
|
87
|
+
if (result.requiresTwoFactor === true) {
|
|
88
|
+
return "the user needs two-factor authentication";
|
|
89
|
+
}
|
|
90
|
+
return "the user name or password is wrong";
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=platform-browser-sessions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform-browser-sessions.js","sourceRoot":"","sources":["../../src/auth/platform-browser-sessions.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,KAAK,CAAC;AAE3C,OAAO,EA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;IACD,OAAO,oCAAoC,CAAC;AAC9C,CAAC","sourcesContent":["import type { APIRequestContext } from \"@playwright/test\";\nimport type { Credentials } from \"./credentials.ts\";\nimport type { StorageState } from \"./storage-state.ts\";\n\nimport { boolean, looseObject } from \"zod\";\n\nimport { HttpClient } from \"@/http\";\n\n/** The options of {@link PlatformBrowserSessions}. */\nexport interface PlatformBrowserSessionsOptions {\n /** The base URL of the platform, whose admin UI the sessions sign in to. */\n readonly platformBaseUrl: string;\n /** Creates a request context for one sign-in. The sessions dispose of it once the sign-in is done. */\n readonly newContext: () => Promise<APIRequestContext>;\n}\n\ninterface PlatformSession {\n readonly credentials: Credentials;\n readonly state: Promise<StorageState>;\n}\n\nconst LOGIN_PATH = \"/api/platform/security/login\";\n\nconst signInResultSchema = looseObject({\n succeeded: boolean().nullish(),\n isLockedOut: boolean().nullish(),\n isNotAllowed: boolean().nullish(),\n requiresTwoFactor: boolean().nullish(),\n});\n\n/**\n * Builds the storage states that start a browser signed in to the admin UI of the platform, so browser tests skip the\n * sign-in page.\n *\n * @remarks\n * - A state holds the sign-in cookie of `POST /api/platform/security/login`, kept for each user. A different password\n * signs in again.\n * - The cookie session expires, but the platform cannot revoke it, so there is nothing to sign out of or dispose of.\n * - A storage state holds secrets in plain text, so never log it or attach it to a report.\n *\n * @example\n * await context.setStorageState(await platformSessions.signedIn(administrator));\n */\nexport class PlatformBrowserSessions {\n readonly #options: PlatformBrowserSessionsOptions;\n readonly #sessions = new Map<string, PlatformSession>();\n\n /**\n * Creates the admin UI sessions of a worker.\n *\n * @param options - The platform base URL and the factory of request contexts.\n */\n constructor(options: PlatformBrowserSessionsOptions) {\n this.#options = options;\n }\n\n /**\n * Returns a storage state with a user signed in to the admin UI. Concurrent calls for one user share one sign-in.\n *\n * @param credentials - The platform user.\n * @returns The storage state, for `setStorageState` of a browser context.\n * @throws {Error} The platform refuses the sign-in. The message names the user and the reason.\n * @throws {HttpError} The sign-in request fails.\n */\n signedIn(credentials: Credentials): Promise<StorageState> {\n const { username } = credentials;\n const session = this.#sessions.get(username);\n if (session?.credentials.password.equals(credentials.password)) {\n return session.state;\n }\n const state = this.#signIn(credentials);\n this.#sessions.set(username, { credentials, state });\n state.catch(() => {\n if (this.#sessions.get(username)?.state === state) {\n this.#sessions.delete(username);\n }\n });\n return state;\n }\n\n /**\n * Forgets a user's storage state, such as before the user is deleted. The cookie stays valid until it expires.\n *\n * @param credentials - The user.\n */\n forget(credentials: Credentials): void {\n this.#sessions.delete(credentials.username);\n }\n\n async #signIn({ username, password }: Credentials): Promise<StorageState> {\n const context = await this.#options.newContext();\n try {\n const httpClient = new HttpClient(context, this.#options.platformBaseUrl);\n const result = (await httpClient.post(LOGIN_PATH, { json: { userName: username, password } })).parse(\n signInResultSchema,\n );\n if (result.succeeded !== true) {\n throw new Error(`Signing in to the platform as ${username} failed: ${rejectionReason(result)}`);\n }\n return await context.storageState();\n } finally {\n await context.dispose();\n }\n }\n}\n\nfunction rejectionReason(result: {\n readonly isLockedOut?: boolean | null | undefined;\n readonly isNotAllowed?: boolean | null | undefined;\n readonly requiresTwoFactor?: boolean | null | undefined;\n}): string {\n if (result.isLockedOut === true) {\n return \"the user is locked out\";\n }\n if (result.isNotAllowed === true) {\n return \"the user is not allowed to sign in, for example because the email address is not confirmed\";\n }\n if (result.requiresTwoFactor === true) {\n return \"the user needs two-factor authentication\";\n }\n return \"the user name or password is wrong\";\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Credentials } from "./credentials.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Runs a sign-in while no other process on the machine signs in the same user in the same store.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* - The platform returns a 500 status when the same user signs in concurrently, and Playwright workers are separate
|
|
7
|
+
* processes. A lock directory in the temporary directory of the system serializes their sign-ins.
|
|
8
|
+
* - A lock older than a minute is taken over, because its process ended without releasing it.
|
|
9
|
+
*
|
|
10
|
+
* @param credentials - The user who signs in. The user name and store identify the lock.
|
|
11
|
+
* @param signIn - The sign-in.
|
|
12
|
+
* @returns The result of the sign-in.
|
|
13
|
+
*/
|
|
14
|
+
export declare function withSignInLock<T>(credentials: Credentials, signIn: () => Promise<T>): Promise<T>;
|