@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
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
6
|
+
const LOCK_DIRECTORY = join(tmpdir(), "vc-test-automation-framework", "sign-in-locks");
|
|
7
|
+
const POLL_INTERVAL_MS = 50;
|
|
8
|
+
const STALE_AFTER_MS = 60_000;
|
|
9
|
+
/**
|
|
10
|
+
* Runs a sign-in while no other process on the machine signs in the same user in the same store.
|
|
11
|
+
*
|
|
12
|
+
* @remarks
|
|
13
|
+
* - The platform returns a 500 status when the same user signs in concurrently, and Playwright workers are separate
|
|
14
|
+
* processes. A lock directory in the temporary directory of the system serializes their sign-ins.
|
|
15
|
+
* - A lock older than a minute is taken over, because its process ended without releasing it.
|
|
16
|
+
*
|
|
17
|
+
* @param credentials - The user who signs in. The user name and store identify the lock.
|
|
18
|
+
* @param signIn - The sign-in.
|
|
19
|
+
* @returns The result of the sign-in.
|
|
20
|
+
*/
|
|
21
|
+
export async function withSignInLock(credentials, signIn) {
|
|
22
|
+
const lock = join(LOCK_DIRECTORY, lockName(credentials));
|
|
23
|
+
await acquire(lock);
|
|
24
|
+
try {
|
|
25
|
+
return await signIn();
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await rm(lock, { recursive: true, force: true });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async function acquire(lock) {
|
|
32
|
+
await mkdir(LOCK_DIRECTORY, { recursive: true });
|
|
33
|
+
for (;;) {
|
|
34
|
+
try {
|
|
35
|
+
await mkdir(lock);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (!hasCode(error, "EEXIST")) {
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (await isStale(lock)) {
|
|
44
|
+
await rm(lock, { recursive: true, force: true });
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
await sleep(POLL_INTERVAL_MS);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function isStale(lock) {
|
|
52
|
+
try {
|
|
53
|
+
return Date.now() - (await stat(lock)).mtimeMs > STALE_AFTER_MS;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (hasCode(error, "ENOENT")) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function lockName({ username, storeId }) {
|
|
63
|
+
return createHash("sha256")
|
|
64
|
+
.update(`${storeId ?? ""}\n${username.toLowerCase()}`)
|
|
65
|
+
.digest("hex");
|
|
66
|
+
}
|
|
67
|
+
function hasCode(error, code) {
|
|
68
|
+
return error instanceof Error && "code" in error && error.code === code;
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=sign-in-lock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-in-lock.js","sourceRoot":"","sources":["../../src/auth/sign-in-lock.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAA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;QACnD,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,CAAC,gBAAgB,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;AACH,CAAC;AAED,KAAK,UAAU,OAAO,CAAC,IAAY;IACjC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,GAAG,cAAc,CAAC;IAClE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAC7B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAe;IAClD,OAAO,UAAU,CAAC,QAAQ,CAAC;SACxB,MAAM,CAAC,GAAG,OAAO,IAAI,EAAE,KAAK,QAAQ,CAAC,WAAW,EAAE,EAAE,CAAC;SACrD,MAAM,CAAC,KAAK,CAAC,CAAC;AACnB,CAAC;AAED,SAAS,OAAO,CAAC,KAAc,EAAE,IAAY;IAC3C,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AAC1E,CAAC","sourcesContent":["import type { Credentials } from \"./credentials.ts\";\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, rm, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nconst LOCK_DIRECTORY = join(tmpdir(), \"vc-test-automation-framework\", \"sign-in-locks\");\nconst POLL_INTERVAL_MS = 50;\nconst STALE_AFTER_MS = 60_000;\n\n/**\n * Runs a sign-in while no other process on the machine signs in the same user in the same store.\n *\n * @remarks\n * - The platform returns a 500 status when the same user signs in concurrently, and Playwright workers are separate\n * processes. A lock directory in the temporary directory of the system serializes their sign-ins.\n * - A lock older than a minute is taken over, because its process ended without releasing it.\n *\n * @param credentials - The user who signs in. The user name and store identify the lock.\n * @param signIn - The sign-in.\n * @returns The result of the sign-in.\n */\nexport async function withSignInLock<T>(credentials: Credentials, signIn: () => Promise<T>): Promise<T> {\n const lock = join(LOCK_DIRECTORY, lockName(credentials));\n await acquire(lock);\n try {\n return await signIn();\n } finally {\n await rm(lock, { recursive: true, force: true });\n }\n}\n\nasync function acquire(lock: string): Promise<void> {\n await mkdir(LOCK_DIRECTORY, { recursive: true });\n for (;;) {\n try {\n await mkdir(lock);\n return;\n } catch (error) {\n if (!hasCode(error, \"EEXIST\")) {\n throw error;\n }\n }\n if (await isStale(lock)) {\n await rm(lock, { recursive: true, force: true });\n } else {\n await sleep(POLL_INTERVAL_MS);\n }\n }\n}\n\nasync function isStale(lock: string): Promise<boolean> {\n try {\n return Date.now() - (await stat(lock)).mtimeMs > STALE_AFTER_MS;\n } catch (error) {\n if (hasCode(error, \"ENOENT\")) {\n return false;\n }\n throw error;\n }\n}\n\nfunction lockName({ username, storeId }: Credentials): string {\n return createHash(\"sha256\")\n .update(`${storeId ?? \"\"}\\n${username.toLowerCase()}`)\n .digest(\"hex\");\n}\n\nfunction hasCode(error: unknown, code: string): boolean {\n return error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage-state.js","sourceRoot":"","sources":["../../src/auth/storage-state.ts"],"names":[],"mappings":"","sourcesContent":["import type { APIRequestContext } from \"@playwright/test\";\n\n/** Cookies and local storage, in the shape of Playwright's `storageState` option and `setStorageState`. */\nexport type StorageState = Awaited<ReturnType<APIRequestContext[\"storageState\"]>>;\n"]}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { Secret } from "../core/index.js";
|
|
2
|
+
import type { HttpClient, HttpResponse } from "../http/index.js";
|
|
3
|
+
import type { Credentials } from "./credentials.ts";
|
|
4
|
+
/** A platform access token, with the data needed to send, renew and revoke it. */
|
|
5
|
+
export interface AuthToken {
|
|
6
|
+
/** The access token. */
|
|
7
|
+
readonly accessToken: Secret;
|
|
8
|
+
/** The type of the token, such as `Bearer`. */
|
|
9
|
+
readonly tokenType: string;
|
|
10
|
+
/**
|
|
11
|
+
* The expiry time in milliseconds since the Unix epoch. It is counted from the time of the request, so it is slightly
|
|
12
|
+
* earlier than the actual expiry.
|
|
13
|
+
*/
|
|
14
|
+
readonly expiresAt: number;
|
|
15
|
+
/** The refresh token, or `undefined` when the platform did not issue one. */
|
|
16
|
+
readonly refreshToken: Secret | undefined;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Represents a client for the platform token endpoints: password sign-in, token refresh and token revocation.
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* - The client sends each request once and does not retry a failure.
|
|
23
|
+
* - Sign-ins of the same user in the same store wait for each other, also across the processes of a machine, such as
|
|
24
|
+
* Playwright workers, because the platform returns a 500 status for concurrent ones. `requestPasswordGrant` does
|
|
25
|
+
* not wait, so sign-in tests send exactly the requests they mean to.
|
|
26
|
+
*/
|
|
27
|
+
export declare class TokenClient {
|
|
28
|
+
#private;
|
|
29
|
+
/**
|
|
30
|
+
* Creates a token client.
|
|
31
|
+
*
|
|
32
|
+
* @param httpClient - The client that sends requests to the platform.
|
|
33
|
+
*/
|
|
34
|
+
constructor(httpClient: HttpClient);
|
|
35
|
+
/**
|
|
36
|
+
* Signs in a user with a password.
|
|
37
|
+
*
|
|
38
|
+
* @param credentials - The sign-in data of the user.
|
|
39
|
+
* @returns The access token of the user.
|
|
40
|
+
* @throws {HttpError} The platform rejects the sign-in or returns another error status, or the response is not a
|
|
41
|
+
* token.
|
|
42
|
+
*/
|
|
43
|
+
signIn(credentials: Credentials): Promise<AuthToken>;
|
|
44
|
+
/**
|
|
45
|
+
* Sends a password sign-in request and returns the response, whatever its status. Use it in tests of the sign-in
|
|
46
|
+
* itself.
|
|
47
|
+
*
|
|
48
|
+
* @param credentials - The sign-in data of the user.
|
|
49
|
+
* @param extra - Additional form fields, such as `organization_id`. They replace standard fields of the same name.
|
|
50
|
+
* @returns The response.
|
|
51
|
+
*/
|
|
52
|
+
requestPasswordGrant(credentials: Credentials, extra?: Readonly<Record<string, string>>): Promise<HttpResponse>;
|
|
53
|
+
/**
|
|
54
|
+
* Renews an access token with a refresh token.
|
|
55
|
+
*
|
|
56
|
+
* @param refreshToken - The refresh token.
|
|
57
|
+
* @returns The new access token, or `undefined` when the platform rejects the refresh token with a 400 status,
|
|
58
|
+
* because it has expired or has been revoked.
|
|
59
|
+
* @throws {HttpError} The platform returns another error status, or the response is not a token.
|
|
60
|
+
*/
|
|
61
|
+
refresh(refreshToken: Secret): Promise<AuthToken | undefined>;
|
|
62
|
+
/**
|
|
63
|
+
* Revokes the refresh token of an access token.
|
|
64
|
+
*
|
|
65
|
+
* @remarks
|
|
66
|
+
* The access token itself stays valid until it expires.
|
|
67
|
+
*
|
|
68
|
+
* @param token - The access token whose refresh token is revoked.
|
|
69
|
+
* @throws {HttpError} The platform does not confirm the revocation.
|
|
70
|
+
*/
|
|
71
|
+
revoke(token: AuthToken): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Returns the `Authorization` header for an access token.
|
|
75
|
+
*
|
|
76
|
+
* @param token - The access token.
|
|
77
|
+
* @returns The header, with its value as a {@link Secret} that is revealed only when the request is sent.
|
|
78
|
+
*/
|
|
79
|
+
export declare function authHeader(token: AuthToken): {
|
|
80
|
+
/** The value of the header, such as `Bearer` followed by the token. */
|
|
81
|
+
readonly authorization: Secret;
|
|
82
|
+
};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { number, object } from "zod";
|
|
2
|
+
import { nonBlankString, secretString } from "../core/index.js";
|
|
3
|
+
import { withSignInLock } from "./sign-in-lock.js";
|
|
4
|
+
const TOKEN_PATH = "/connect/token";
|
|
5
|
+
const REVOKE_PATH = "/revoke/token";
|
|
6
|
+
const tokenResponseSchema = object({
|
|
7
|
+
access_token: secretString,
|
|
8
|
+
token_type: nonBlankString,
|
|
9
|
+
expires_in: number().int().positive(),
|
|
10
|
+
refresh_token: secretString.optional(),
|
|
11
|
+
});
|
|
12
|
+
/**
|
|
13
|
+
* Represents a client for the platform token endpoints: password sign-in, token refresh and token revocation.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* - The client sends each request once and does not retry a failure.
|
|
17
|
+
* - Sign-ins of the same user in the same store wait for each other, also across the processes of a machine, such as
|
|
18
|
+
* Playwright workers, because the platform returns a 500 status for concurrent ones. `requestPasswordGrant` does
|
|
19
|
+
* not wait, so sign-in tests send exactly the requests they mean to.
|
|
20
|
+
*/
|
|
21
|
+
export class TokenClient {
|
|
22
|
+
#httpClient;
|
|
23
|
+
/**
|
|
24
|
+
* Creates a token client.
|
|
25
|
+
*
|
|
26
|
+
* @param httpClient - The client that sends requests to the platform.
|
|
27
|
+
*/
|
|
28
|
+
constructor(httpClient) {
|
|
29
|
+
this.#httpClient = httpClient;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Signs in a user with a password.
|
|
33
|
+
*
|
|
34
|
+
* @param credentials - The sign-in data of the user.
|
|
35
|
+
* @returns The access token of the user.
|
|
36
|
+
* @throws {HttpError} The platform rejects the sign-in or returns another error status, or the response is not a
|
|
37
|
+
* token.
|
|
38
|
+
*/
|
|
39
|
+
async signIn(credentials) {
|
|
40
|
+
return withSignInLock(credentials, async () => {
|
|
41
|
+
const requestedAt = Date.now();
|
|
42
|
+
return toAuthToken(await this.requestPasswordGrant(credentials), requestedAt);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Sends a password sign-in request and returns the response, whatever its status. Use it in tests of the sign-in
|
|
47
|
+
* itself.
|
|
48
|
+
*
|
|
49
|
+
* @param credentials - The sign-in data of the user.
|
|
50
|
+
* @param extra - Additional form fields, such as `organization_id`. They replace standard fields of the same name.
|
|
51
|
+
* @returns The response.
|
|
52
|
+
*/
|
|
53
|
+
requestPasswordGrant(credentials, extra = {}) {
|
|
54
|
+
return this.#httpClient.post(TOKEN_PATH, { form: { ...passwordGrant(credentials), ...extra } });
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Renews an access token with a refresh token.
|
|
58
|
+
*
|
|
59
|
+
* @param refreshToken - The refresh token.
|
|
60
|
+
* @returns The new access token, or `undefined` when the platform rejects the refresh token with a 400 status,
|
|
61
|
+
* because it has expired or has been revoked.
|
|
62
|
+
* @throws {HttpError} The platform returns another error status, or the response is not a token.
|
|
63
|
+
*/
|
|
64
|
+
async refresh(refreshToken) {
|
|
65
|
+
const requestedAt = Date.now();
|
|
66
|
+
const response = await this.#httpClient.post(TOKEN_PATH, {
|
|
67
|
+
form: { grant_type: "refresh_token", refresh_token: refreshToken },
|
|
68
|
+
});
|
|
69
|
+
return response.status === 400 ? undefined : toAuthToken(response, requestedAt);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Revokes the refresh token of an access token.
|
|
73
|
+
*
|
|
74
|
+
* @remarks
|
|
75
|
+
* The access token itself stays valid until it expires.
|
|
76
|
+
*
|
|
77
|
+
* @param token - The access token whose refresh token is revoked.
|
|
78
|
+
* @throws {HttpError} The platform does not confirm the revocation.
|
|
79
|
+
*/
|
|
80
|
+
async revoke(token) {
|
|
81
|
+
(await this.#httpClient.post(REVOKE_PATH, { headers: authHeader(token) })).expectOk();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Returns the `Authorization` header for an access token.
|
|
86
|
+
*
|
|
87
|
+
* @param token - The access token.
|
|
88
|
+
* @returns The header, with its value as a {@link Secret} that is revealed only when the request is sent.
|
|
89
|
+
*/
|
|
90
|
+
export function authHeader(token) {
|
|
91
|
+
return { authorization: token.accessToken.withPrefix(`${token.tokenType} `) };
|
|
92
|
+
}
|
|
93
|
+
function passwordGrant({ username, password, storeId }) {
|
|
94
|
+
return {
|
|
95
|
+
grant_type: "password",
|
|
96
|
+
username,
|
|
97
|
+
password,
|
|
98
|
+
scope: "offline_access",
|
|
99
|
+
...(storeId === undefined ? {} : { storeId }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function toAuthToken(response, requestedAt) {
|
|
103
|
+
const body = response.parse(tokenResponseSchema);
|
|
104
|
+
return {
|
|
105
|
+
accessToken: body.access_token,
|
|
106
|
+
tokenType: body.token_type,
|
|
107
|
+
expiresAt: requestedAt + body.expires_in * 1_000,
|
|
108
|
+
refreshToken: body.refresh_token,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
//# sourceMappingURL=token-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"token-client.js","sourceRoot":"","sources":["../../src/auth/token-client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAErC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,MAAM,UAAU,GAAG,gBAAgB,CAAC;AACpC,MAAM,WAAW,GAAG,eAAe,CAAC;AAEpC,MAAM,mBAAmB,GAAG,MAAM,CAAC;IACjC,YAAY,EAAE,YAAY;IAC1B,UAAU,EAAE,cAAc;IAC1B,UAAU,EAAE,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IACrC,aAAa,EAAE,YAAY,CAAC,QAAQ,EAAE;CACvC,CAAC,CAAC;AAiBH;;;;;;;;GAQG;AACH,MAAM,OAAO,WAAW;IACb,WAAW,CAAa;IAEjC;;;;OAIG;IACH,YAAY,UAAsB;QAChC,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;IAChC,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,MAAM,CAAC,WAAwB;QACnC,OAAO,cAAc,CAAC,WAAW,EAAE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G,CAAC,EAAE,CAAC;AAChF,CAAC;AAID,SAAS,aAAa,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAe;IACjE,OAAO;QACL,UAAU,EAAE,UAAU;QACtB,QAAQ;QACR,QAAQ;QACR,KAAK,EAAE,gBAAgB;QACvB,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC;KAC9C,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,QAAsB,EAAE,WAAmB;IAC9D,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACjD,OAAO;QACL,WAAW,EAAE,IAAI,CAAC,YAAY;QAC9B,SAAS,EAAE,IAAI,CAAC,UAAU;QAC1B,SAAS,EAAE,WAAW,GAAG,IAAI,CAAC,UAAU,GAAG,KAAK;QAChD,YAAY,EAAE,IAAI,CAAC,aAAa;KACjC,CAAC;AACJ,CAAC","sourcesContent":["import type { Secret } from \"@/core\";\nimport type { HttpClient, HttpResponse } from \"@/http\";\nimport type { Credentials } from \"./credentials.ts\";\n\nimport { number, object } from \"zod\";\n\nimport { nonBlankString, secretString } from \"@/core\";\n\nimport { withSignInLock } from \"./sign-in-lock.ts\";\n\nconst TOKEN_PATH = \"/connect/token\";\nconst REVOKE_PATH = \"/revoke/token\";\n\nconst tokenResponseSchema = object({\n access_token: secretString,\n token_type: nonBlankString,\n expires_in: number().int().positive(),\n refresh_token: secretString.optional(),\n});\n\n/** A platform access token, with the data needed to send, renew and revoke it. */\nexport interface AuthToken {\n /** The access token. */\n readonly accessToken: Secret;\n /** The type of the token, such as `Bearer`. */\n readonly tokenType: string;\n /**\n * The expiry time in milliseconds since the Unix epoch. It is counted from the time of the request, so it is slightly\n * earlier than the actual expiry.\n */\n readonly expiresAt: number;\n /** The refresh token, or `undefined` when the platform did not issue one. */\n readonly refreshToken: Secret | undefined;\n}\n\n/**\n * Represents a client for the platform token endpoints: password sign-in, token refresh and token revocation.\n *\n * @remarks\n * - The client sends each request once and does not retry a failure.\n * - Sign-ins of the same user in the same store wait for each other, also across the processes of a machine, such as\n * Playwright workers, because the platform returns a 500 status for concurrent ones. `requestPasswordGrant` does\n * not wait, so sign-in tests send exactly the requests they mean to.\n */\nexport class TokenClient {\n readonly #httpClient: HttpClient;\n\n /**\n * Creates a token client.\n *\n * @param httpClient - The client that sends requests to the platform.\n */\n constructor(httpClient: HttpClient) {\n this.#httpClient = httpClient;\n }\n\n /**\n * Signs in a user with a password.\n *\n * @param credentials - The sign-in data of the user.\n * @returns The access token of the user.\n * @throws {HttpError} The platform rejects the sign-in or returns another error status, or the response is not a\n * token.\n */\n async signIn(credentials: Credentials): Promise<AuthToken> {\n return withSignInLock(credentials, async () => {\n const requestedAt = Date.now();\n return toAuthToken(await this.requestPasswordGrant(credentials), requestedAt);\n });\n }\n\n /**\n * Sends a password sign-in request and returns the response, whatever its status. Use it in tests of the sign-in\n * itself.\n *\n * @param credentials - The sign-in data of the user.\n * @param extra - Additional form fields, such as `organization_id`. They replace standard fields of the same name.\n * @returns The response.\n */\n requestPasswordGrant(credentials: Credentials, extra: Readonly<Record<string, string>> = {}): Promise<HttpResponse> {\n return this.#httpClient.post(TOKEN_PATH, { form: { ...passwordGrant(credentials), ...extra } });\n }\n\n /**\n * Renews an access token with a refresh token.\n *\n * @param refreshToken - The refresh token.\n * @returns The new access token, or `undefined` when the platform rejects the refresh token with a 400 status,\n * because it has expired or has been revoked.\n * @throws {HttpError} The platform returns another error status, or the response is not a token.\n */\n async refresh(refreshToken: Secret): Promise<AuthToken | undefined> {\n const requestedAt = Date.now();\n const response = await this.#httpClient.post(TOKEN_PATH, {\n form: { grant_type: \"refresh_token\", refresh_token: refreshToken },\n });\n return response.status === 400 ? undefined : toAuthToken(response, requestedAt);\n }\n\n /**\n * Revokes the refresh token of an access token.\n *\n * @remarks\n * The access token itself stays valid until it expires.\n *\n * @param token - The access token whose refresh token is revoked.\n * @throws {HttpError} The platform does not confirm the revocation.\n */\n async revoke(token: AuthToken): Promise<void> {\n (await this.#httpClient.post(REVOKE_PATH, { headers: authHeader(token) })).expectOk();\n }\n}\n\n/**\n * Returns the `Authorization` header for an access token.\n *\n * @param token - The access token.\n * @returns The header, with its value as a {@link Secret} that is revealed only when the request is sent.\n */\nexport function authHeader(token: AuthToken): {\n /** The value of the header, such as `Bearer` followed by the token. */\n readonly authorization: Secret;\n} {\n return { authorization: token.accessToken.withPrefix(`${token.tokenType} `) };\n}\n\ntype TokenForm = Readonly<Record<string, string | Secret>>;\n\nfunction passwordGrant({ username, password, storeId }: Credentials): TokenForm {\n return {\n grant_type: \"password\",\n username,\n password,\n scope: \"offline_access\",\n ...(storeId === undefined ? {} : { storeId }),\n };\n}\n\nfunction toAuthToken(response: HttpResponse, requestedAt: number): AuthToken {\n const body = response.parse(tokenResponseSchema);\n return {\n accessToken: body.access_token,\n tokenType: body.token_type,\n expiresAt: requestedAt + body.expires_in * 1_000,\n refreshToken: body.refresh_token,\n };\n}\n"]}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { HttpClient } from "../http/index.js";
|
|
2
|
+
import type { Credentials } from "./credentials.ts";
|
|
3
|
+
import type { AuthToken, TokenClient } from "./token-client.ts";
|
|
4
|
+
/**
|
|
5
|
+
* Represents a cache of platform access tokens, with one token for each user in each store.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* - Concurrent requests for the same user share one sign-in or renewal. A failed sign-in or renewal is not cached.
|
|
9
|
+
* - A token that expires within a minute is renewed with its refresh token. When the platform rejects the refresh
|
|
10
|
+
* token, the user signs in again.
|
|
11
|
+
* - A token that the platform rejects with a 401 status is forgotten, so the next request signs in again.
|
|
12
|
+
* - A different password for a cached user starts a new sign-in.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const tokens = new TokenManager(new TokenClient(anonymous));
|
|
16
|
+
* const admin = await tokens.signIn(anonymous, { username: env.ADMIN_USERNAME, password: env.ADMIN_PASSWORD });
|
|
17
|
+
* await admin.get("/api/platform/security/currentuser");
|
|
18
|
+
* await tokens.signOutAll();
|
|
19
|
+
*/
|
|
20
|
+
export declare class TokenManager {
|
|
21
|
+
#private;
|
|
22
|
+
/**
|
|
23
|
+
* Creates a token cache.
|
|
24
|
+
*
|
|
25
|
+
* @param tokenClient - The client that signs users in and renews and revokes their tokens.
|
|
26
|
+
*/
|
|
27
|
+
constructor(tokenClient: TokenClient);
|
|
28
|
+
/**
|
|
29
|
+
* Signs a user in and returns a client that sends the user's current token with each request.
|
|
30
|
+
*
|
|
31
|
+
* @remarks
|
|
32
|
+
* The user signs in before this method returns, so wrong credentials fail here rather than on the first request.
|
|
33
|
+
* Pass a client for the same platform as the token client, because the client receives the tokens that the token
|
|
34
|
+
* client gets.
|
|
35
|
+
*
|
|
36
|
+
* @param httpClient - The client to derive the signed-in client from. It does not change.
|
|
37
|
+
* @param credentials - The sign-in data of the user.
|
|
38
|
+
* @returns A new client that signs in to each request as the user.
|
|
39
|
+
* @throws {HttpError} The sign-in fails.
|
|
40
|
+
*/
|
|
41
|
+
signIn(httpClient: HttpClient, credentials: Credentials): Promise<HttpClient>;
|
|
42
|
+
/**
|
|
43
|
+
* Returns a token for a user that is valid for at least another minute.
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* The token is the cached one, a renewed one or one from a new sign-in.
|
|
47
|
+
*
|
|
48
|
+
* @param credentials - The sign-in data of the user.
|
|
49
|
+
* @returns The token.
|
|
50
|
+
* @throws {HttpError} The sign-in or the renewal fails.
|
|
51
|
+
*/
|
|
52
|
+
token(credentials: Credentials): Promise<AuthToken>;
|
|
53
|
+
/**
|
|
54
|
+
* Forgets the token of a user and revokes it. Does nothing when the user is not signed in.
|
|
55
|
+
*
|
|
56
|
+
* @param credentials - The sign-in data of the user. The user name and store identify the token.
|
|
57
|
+
* @throws {HttpError} The platform does not confirm the revocation. The token is forgotten anyway.
|
|
58
|
+
*/
|
|
59
|
+
signOut(credentials: Credentials): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Signs out every user.
|
|
62
|
+
*
|
|
63
|
+
* @throws {HttpError} The platform does not confirm a revocation. The first error is thrown after every user has
|
|
64
|
+
* been signed out.
|
|
65
|
+
*/
|
|
66
|
+
signOutAll(): Promise<void>;
|
|
67
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { Secret } from "../core/index.js";
|
|
2
|
+
import { authHeader } from "./token-client.js";
|
|
3
|
+
const EXPIRY_MARGIN_MS = 60_000;
|
|
4
|
+
/**
|
|
5
|
+
* Represents a cache of platform access tokens, with one token for each user in each store.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* - Concurrent requests for the same user share one sign-in or renewal. A failed sign-in or renewal is not cached.
|
|
9
|
+
* - A token that expires within a minute is renewed with its refresh token. When the platform rejects the refresh
|
|
10
|
+
* token, the user signs in again.
|
|
11
|
+
* - A token that the platform rejects with a 401 status is forgotten, so the next request signs in again.
|
|
12
|
+
* - A different password for a cached user starts a new sign-in.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const tokens = new TokenManager(new TokenClient(anonymous));
|
|
16
|
+
* const admin = await tokens.signIn(anonymous, { username: env.ADMIN_USERNAME, password: env.ADMIN_PASSWORD });
|
|
17
|
+
* await admin.get("/api/platform/security/currentuser");
|
|
18
|
+
* await tokens.signOutAll();
|
|
19
|
+
*/
|
|
20
|
+
export class TokenManager {
|
|
21
|
+
#tokenClient;
|
|
22
|
+
#sessions = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Creates a token cache.
|
|
25
|
+
*
|
|
26
|
+
* @param tokenClient - The client that signs users in and renews and revokes their tokens.
|
|
27
|
+
*/
|
|
28
|
+
constructor(tokenClient) {
|
|
29
|
+
this.#tokenClient = tokenClient;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Signs a user in and returns a client that sends the user's current token with each request.
|
|
33
|
+
*
|
|
34
|
+
* @remarks
|
|
35
|
+
* The user signs in before this method returns, so wrong credentials fail here rather than on the first request.
|
|
36
|
+
* Pass a client for the same platform as the token client, because the client receives the tokens that the token
|
|
37
|
+
* client gets.
|
|
38
|
+
*
|
|
39
|
+
* @param httpClient - The client to derive the signed-in client from. It does not change.
|
|
40
|
+
* @param credentials - The sign-in data of the user.
|
|
41
|
+
* @returns A new client that signs in to each request as the user.
|
|
42
|
+
* @throws {HttpError} The sign-in fails.
|
|
43
|
+
*/
|
|
44
|
+
async signIn(httpClient, credentials) {
|
|
45
|
+
await this.token(credentials);
|
|
46
|
+
return httpClient.withAuthentication({
|
|
47
|
+
headers: async () => authHeader(await this.token(credentials)),
|
|
48
|
+
renew: (rejected) => this.#forgetRejected(credentials, rejected),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Returns a token for a user that is valid for at least another minute.
|
|
53
|
+
*
|
|
54
|
+
* @remarks
|
|
55
|
+
* The token is the cached one, a renewed one or one from a new sign-in.
|
|
56
|
+
*
|
|
57
|
+
* @param credentials - The sign-in data of the user.
|
|
58
|
+
* @returns The token.
|
|
59
|
+
* @throws {HttpError} The sign-in or the renewal fails.
|
|
60
|
+
*/
|
|
61
|
+
token(credentials) {
|
|
62
|
+
const key = sessionKey(credentials);
|
|
63
|
+
const session = this.#sessions.get(key);
|
|
64
|
+
const token = session?.password.equals(credentials.password)
|
|
65
|
+
? this.#current(session.token, credentials)
|
|
66
|
+
: this.#tokenClient.signIn(credentials);
|
|
67
|
+
this.#sessions.set(key, { password: credentials.password, token });
|
|
68
|
+
token.catch(() => this.#forget(key, token));
|
|
69
|
+
return token;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Forgets the token of a user and revokes it. Does nothing when the user is not signed in.
|
|
73
|
+
*
|
|
74
|
+
* @param credentials - The sign-in data of the user. The user name and store identify the token.
|
|
75
|
+
* @throws {HttpError} The platform does not confirm the revocation. The token is forgotten anyway.
|
|
76
|
+
*/
|
|
77
|
+
signOut(credentials) {
|
|
78
|
+
return this.#signOut(sessionKey(credentials));
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Signs out every user.
|
|
82
|
+
*
|
|
83
|
+
* @throws {HttpError} The platform does not confirm a revocation. The first error is thrown after every user has
|
|
84
|
+
* been signed out.
|
|
85
|
+
*/
|
|
86
|
+
async signOutAll() {
|
|
87
|
+
const results = await Promise.allSettled([...this.#sessions.keys()].map((key) => this.#signOut(key)));
|
|
88
|
+
const failure = results.find((result) => result.status === "rejected");
|
|
89
|
+
if (failure !== undefined) {
|
|
90
|
+
throw failure.reason;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async #signOut(key) {
|
|
94
|
+
const session = this.#sessions.get(key);
|
|
95
|
+
if (session === undefined) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
this.#sessions.delete(key);
|
|
99
|
+
const token = await session.token.catch(() => undefined);
|
|
100
|
+
if (token !== undefined && token.expiresAt > Date.now()) {
|
|
101
|
+
await this.#tokenClient.revoke(token);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async #current(previous, credentials) {
|
|
105
|
+
const token = await previous;
|
|
106
|
+
if (token.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
|
|
107
|
+
return token;
|
|
108
|
+
}
|
|
109
|
+
if (token.refreshToken !== undefined) {
|
|
110
|
+
const refreshed = await this.#tokenClient.refresh(token.refreshToken);
|
|
111
|
+
if (refreshed !== undefined) {
|
|
112
|
+
return refreshed;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return this.#tokenClient.signIn(credentials);
|
|
116
|
+
}
|
|
117
|
+
async #forgetRejected(credentials, rejected) {
|
|
118
|
+
const key = sessionKey(credentials);
|
|
119
|
+
const session = this.#sessions.get(key);
|
|
120
|
+
const current = await session?.token.catch(() => undefined);
|
|
121
|
+
const sent = rejected["authorization"];
|
|
122
|
+
if (session !== undefined &&
|
|
123
|
+
current !== undefined &&
|
|
124
|
+
sent instanceof Secret &&
|
|
125
|
+
sent.equals(authHeader(current).authorization)) {
|
|
126
|
+
this.#forget(key, session.token);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
#forget(key, token) {
|
|
130
|
+
if (this.#sessions.get(key)?.token === token) {
|
|
131
|
+
this.#sessions.delete(key);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function sessionKey({ storeId, username }) {
|
|
136
|
+
return `${storeId ?? ""}\n${username}`;
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=token-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"token-manager.js","sourceRoot":"","sources":["../../src/auth/token-manager.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAOhC;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,YAAY;IACd,YAAY,CAAc;IAC1B,SAAS,GAAG,IAAI,GAAG,EAAmB,CAAC;IAEhD;;;;OAIG;IACH,YAAY,WAAwB;QAClC,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;IAClC,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,KAAK,CAAC,MAAM,CAAC,UAAsB,EAAE,WAAwB;QAC3D,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAC9B,OAAO,UAAU,CAAC,kBAAkB,CAAC;YACnC,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,UAAU,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;YAC9D,KAAK,EAAE,CAAC,QAAwB,EAAE,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,QAAQ,CAAC;SACjF,CA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AC,CAAC;QACpC,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACxC,MAAM,OAAO,GAAG,MAAM,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5D,MAAM,IAAI,GAAG,QAAQ,CAAC,eAAe,CAAC,CAAC;QACvC,IACE,OAAO,KAAK,SAAS;YACrB,OAAO,KAAK,SAAS;YACrB,IAAI,YAAY,MAAM;YACtB,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,aAAa,CAAC,EAC9C,CAAC;YACD,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;QACnC,CAAC;IACH,CAAC;IAED,OAAO,CAAC,GAAW,EAAE,KAAyB;QAC5C,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,KAAK,KAAK,KAAK,EAAE,CAAC;YAC7C,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;CACF;AAED,SAAS,UAAU,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAe;IACpD,OAAO,GAAG,OAAO,IAAI,EAAE,KAAK,QAAQ,EAAE,CAAC;AACzC,CAAC","sourcesContent":["import type { HttpClient, RequestHeaders } from \"@/http\";\nimport type { Credentials } from \"./credentials.ts\";\nimport type { AuthToken, TokenClient } from \"./token-client.ts\";\n\nimport { Secret } from \"@/core\";\n\nimport { authHeader } from \"./token-client.ts\";\n\nconst EXPIRY_MARGIN_MS = 60_000;\n\ninterface Session {\n readonly password: Secret;\n readonly token: Promise<AuthToken>;\n}\n\n/**\n * Represents a cache of platform access tokens, with one token for each user in each store.\n *\n * @remarks\n * - Concurrent requests for the same user share one sign-in or renewal. A failed sign-in or renewal is not cached.\n * - A token that expires within a minute is renewed with its refresh token. When the platform rejects the refresh\n * token, the user signs in again.\n * - A token that the platform rejects with a 401 status is forgotten, so the next request signs in again.\n * - A different password for a cached user starts a new sign-in.\n *\n * @example\n * const tokens = new TokenManager(new TokenClient(anonymous));\n * const admin = await tokens.signIn(anonymous, { username: env.ADMIN_USERNAME, password: env.ADMIN_PASSWORD });\n * await admin.get(\"/api/platform/security/currentuser\");\n * await tokens.signOutAll();\n */\nexport class TokenManager {\n readonly #tokenClient: TokenClient;\n readonly #sessions = new Map<string, Session>();\n\n /**\n * Creates a token cache.\n *\n * @param tokenClient - The client that signs users in and renews and revokes their tokens.\n */\n constructor(tokenClient: TokenClient) {\n this.#tokenClient = tokenClient;\n }\n\n /**\n * Signs a user in and returns a client that sends the user's current token with each request.\n *\n * @remarks\n * The user signs in before this method returns, so wrong credentials fail here rather than on the first request.\n * Pass a client for the same platform as the token client, because the client receives the tokens that the token\n * client gets.\n *\n * @param httpClient - The client to derive the signed-in client from. It does not change.\n * @param credentials - The sign-in data of the user.\n * @returns A new client that signs in to each request as the user.\n * @throws {HttpError} The sign-in fails.\n */\n async signIn(httpClient: HttpClient, credentials: Credentials): Promise<HttpClient> {\n await this.token(credentials);\n return httpClient.withAuthentication({\n headers: async () => authHeader(await this.token(credentials)),\n renew: (rejected: RequestHeaders) => this.#forgetRejected(credentials, rejected),\n });\n }\n\n /**\n * Returns a token for a user that is valid for at least another minute.\n *\n * @remarks\n * The token is the cached one, a renewed one or one from a new sign-in.\n *\n * @param credentials - The sign-in data of the user.\n * @returns The token.\n * @throws {HttpError} The sign-in or the renewal fails.\n */\n token(credentials: Credentials): Promise<AuthToken> {\n const key = sessionKey(credentials);\n const session = this.#sessions.get(key);\n const token = session?.password.equals(credentials.password)\n ? this.#current(session.token, credentials)\n : this.#tokenClient.signIn(credentials);\n this.#sessions.set(key, { password: credentials.password, token });\n token.catch(() => this.#forget(key, token));\n return token;\n }\n\n /**\n * Forgets the token of a user and revokes it. Does nothing when the user is not signed in.\n *\n * @param credentials - The sign-in data of the user. The user name and store identify the token.\n * @throws {HttpError} The platform does not confirm the revocation. The token is forgotten anyway.\n */\n signOut(credentials: Credentials): Promise<void> {\n return this.#signOut(sessionKey(credentials));\n }\n\n /**\n * Signs out every user.\n *\n * @throws {HttpError} The platform does not confirm a revocation. The first error is thrown after every user has\n * been signed out.\n */\n async signOutAll(): Promise<void> {\n const results = await Promise.allSettled([...this.#sessions.keys()].map((key: string) => this.#signOut(key)));\n const failure = results.find((result: PromiseSettledResult<void>) => result.status === \"rejected\");\n if (failure !== undefined) {\n throw failure.reason;\n }\n }\n\n async #signOut(key: string): Promise<void> {\n const session = this.#sessions.get(key);\n if (session === undefined) {\n return;\n }\n this.#sessions.delete(key);\n const token = await session.token.catch(() => undefined);\n if (token !== undefined && token.expiresAt > Date.now()) {\n await this.#tokenClient.revoke(token);\n }\n }\n\n async #current(previous: Promise<AuthToken>, credentials: Credentials): Promise<AuthToken> {\n const token = await previous;\n if (token.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {\n return token;\n }\n if (token.refreshToken !== undefined) {\n const refreshed = await this.#tokenClient.refresh(token.refreshToken);\n if (refreshed !== undefined) {\n return refreshed;\n }\n }\n return this.#tokenClient.signIn(credentials);\n }\n\n async #forgetRejected(credentials: Credentials, rejected: RequestHeaders): Promise<void> {\n const key = sessionKey(credentials);\n const session = this.#sessions.get(key);\n const current = await session?.token.catch(() => undefined);\n const sent = rejected[\"authorization\"];\n if (\n session !== undefined &&\n current !== undefined &&\n sent instanceof Secret &&\n sent.equals(authHeader(current).authorization)\n ) {\n this.#forget(key, session.token);\n }\n }\n\n #forget(key: string, token: Promise<AuthToken>): void {\n if (this.#sessions.get(key)?.token === token) {\n this.#sessions.delete(key);\n }\n }\n}\n\nfunction sessionKey({ storeId, username }: Credentials): string {\n return `${storeId ?? \"\"}\\n${username}`;\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ReporterDescription } from "@playwright/test";
|
|
2
|
+
/** The options of {@link defaultReporters}. */
|
|
3
|
+
export interface DefaultReporterOptions {
|
|
4
|
+
/** The directory that the reporters write to, each in its own subdirectory, such as `reports` next to the config. */
|
|
5
|
+
readonly outputDir: string;
|
|
6
|
+
/**
|
|
7
|
+
* The environment of the run, shown in the report, such as the platform URL and the store. Registered secrets in the
|
|
8
|
+
* values are masked.
|
|
9
|
+
*/
|
|
10
|
+
readonly environment?: Readonly<Record<string, string>> | undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Returns the default reporters of a test suite: a line for each test on the console, and results to generate a
|
|
14
|
+
* report from.
|
|
15
|
+
*
|
|
16
|
+
* @remarks
|
|
17
|
+
* The report is an Allure report: the results are written to `allure-results` in `outputDir`, and need
|
|
18
|
+
* `allure-playwright`, an optional peer dependency that the test suite installs. Playwright loads it by name when the
|
|
19
|
+
* run starts, so the framework does not depend on it. A test suite that reports in another way sets its own
|
|
20
|
+
* `reporter`, or adds its reporters to these.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* reporter: defaultReporters({
|
|
24
|
+
* outputDir: fileURLToPath(new URL("reports", import.meta.url)),
|
|
25
|
+
* environment: { backend: env.BACKEND_BASE_URL },
|
|
26
|
+
* }),
|
|
27
|
+
*
|
|
28
|
+
* @param options - The output directory and the environment of the run.
|
|
29
|
+
* @returns The reporters, for the `reporter` option of the Playwright config.
|
|
30
|
+
*/
|
|
31
|
+
export declare function defaultReporters(options: DefaultReporterOptions): ReporterDescription[];
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { maskSecrets } from "./secret.js";
|
|
3
|
+
/**
|
|
4
|
+
* Returns the default reporters of a test suite: a line for each test on the console, and results to generate a
|
|
5
|
+
* report from.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* The report is an Allure report: the results are written to `allure-results` in `outputDir`, and need
|
|
9
|
+
* `allure-playwright`, an optional peer dependency that the test suite installs. Playwright loads it by name when the
|
|
10
|
+
* run starts, so the framework does not depend on it. A test suite that reports in another way sets its own
|
|
11
|
+
* `reporter`, or adds its reporters to these.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* reporter: defaultReporters({
|
|
15
|
+
* outputDir: fileURLToPath(new URL("reports", import.meta.url)),
|
|
16
|
+
* environment: { backend: env.BACKEND_BASE_URL },
|
|
17
|
+
* }),
|
|
18
|
+
*
|
|
19
|
+
* @param options - The output directory and the environment of the run.
|
|
20
|
+
* @returns The reporters, for the `reporter` option of the Playwright config.
|
|
21
|
+
*/
|
|
22
|
+
export function defaultReporters(options) {
|
|
23
|
+
const envEntries = Object.entries(options.environment ?? {});
|
|
24
|
+
const environment = envEntries.map(([key, value]) => [key, maskSecrets(value)]);
|
|
25
|
+
return [
|
|
26
|
+
["list"],
|
|
27
|
+
[
|
|
28
|
+
"allure-playwright",
|
|
29
|
+
{
|
|
30
|
+
resultsDir: join(options.outputDir, "allure-results"),
|
|
31
|
+
environmentInfo: Object.fromEntries(environment),
|
|
32
|
+
},
|
|
33
|
+
],
|
|
34
|
+
];
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=default-reporters.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"default-reporters.js","sourceRoot":"","sources":["../../src/core/default-reporters.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAa1C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAA+B;IAC9D,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IAC7D,MAAM,WAAW,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAChF,OAAO;QACL,CAAC,MAAM,CAAC;QACR;YACE,mBAAmB;YACnB;gBACE,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,gBAAgB,CAAC;gBACrD,eAAe,EAAE,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC;aACjD;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ReporterDescription } from \"@playwright/test\";\n\nimport { join } from \"node:path\";\n\nimport { maskSecrets } from \"./secret.ts\";\n\n/** The options of {@link defaultReporters}. */\nexport interface DefaultReporterOptions {\n /** The directory that the reporters write to, each in its own subdirectory, such as `reports` next to the config. */\n readonly outputDir: string;\n /**\n * The environment of the run, shown in the report, such as the platform URL and the store. Registered secrets in the\n * values are masked.\n */\n readonly environment?: Readonly<Record<string, string>> | undefined;\n}\n\n/**\n * Returns the default reporters of a test suite: a line for each test on the console, and results to generate a\n * report from.\n *\n * @remarks\n * The report is an Allure report: the results are written to `allure-results` in `outputDir`, and need\n * `allure-playwright`, an optional peer dependency that the test suite installs. Playwright loads it by name when the\n * run starts, so the framework does not depend on it. A test suite that reports in another way sets its own\n * `reporter`, or adds its reporters to these.\n *\n * @example\n * reporter: defaultReporters({\n * outputDir: fileURLToPath(new URL(\"reports\", import.meta.url)),\n * environment: { backend: env.BACKEND_BASE_URL },\n * }),\n *\n * @param options - The output directory and the environment of the run.\n * @returns The reporters, for the `reporter` option of the Playwright config.\n */\nexport function defaultReporters(options: DefaultReporterOptions): ReporterDescription[] {\n const envEntries = Object.entries(options.environment ?? {});\n const environment = envEntries.map(([key, value]) => [key, maskSecrets(value)]);\n return [\n [\"list\"],\n [\n \"allure-playwright\",\n {\n resultsDir: join(options.outputDir, \"allure-results\"),\n environmentInfo: Object.fromEntries(environment),\n },\n ],\n ];\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { PlaywrightTestOptions, PlaywrightWorkerOptions } from "@playwright/test";
|
|
2
|
+
import type { Env } from "./env.ts";
|
|
3
|
+
/** The options of {@link defaultUse}. */
|
|
4
|
+
export interface DefaultUseOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The attribute that `getByTestId` reads. The default is `data-test-id`, the attribute of the Virto Commerce
|
|
7
|
+
* frontend.
|
|
8
|
+
*/
|
|
9
|
+
readonly testIdAttribute?: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
/** The base `use` options of a test suite, as {@link defaultUse} returns them. */
|
|
12
|
+
export type DefaultUse = Pick<PlaywrightTestOptions & PlaywrightWorkerOptions, "ignoreHTTPSErrors" | "trace" | "screenshot" | "video" | "testIdAttribute">;
|
|
13
|
+
/**
|
|
14
|
+
* Returns the base `use` options of a test suite: the certificate check from the environment, and the evidence of
|
|
15
|
+
* failed tests.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* A failed test keeps its trace, a screenshot and a video; a passed test keeps none. Screenshots and videos apply only
|
|
19
|
+
* to tests that use a browser.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* use: { ...defaultUse(env), baseURL: env.FRONTEND_BASE_URL },
|
|
23
|
+
*
|
|
24
|
+
* @param env - The parsed environment variables.
|
|
25
|
+
* @param options - The test id attribute.
|
|
26
|
+
* @returns The options, for the `use` option of the Playwright config or of a project.
|
|
27
|
+
*/
|
|
28
|
+
export declare function defaultUse(env: Env, options?: DefaultUseOptions): DefaultUse;
|