API reference
Imports, parameters, return values, and limits for Playwright helpers and fixtures
Look up the helpers and fixtures exported by the versioned MSW and domain entry points of @octopus-energy/playwright. This reference covers signatures, defaults, and runtime limits. See getting started for setup and the fixture guides for test composition.
Choose the entry point matching your installed MSW major version:
@octopus-energy/playwright/msw/v2 for MSW 2, or
@octopus-energy/playwright/msw/v3 for MSW 3. The MSW 3 entry point also requires
graphql. See Getting Started for installation
and migration from the removed root API entry point.
The versioned entry points export only createPlaywrightHelpers and MSW,
GraphQL, and factory-specific types. Import these types from the same entry point
as your factory. Shared Global Config and Flags helpers are not exported from
/msw/v2 or /msw/v3. Import them from the domain entry points shown below.
They compose with either factory, with unchanged signatures and behavior.
The version tabs share your selection with the setup and fixture guides.
createPlaywrightHelpers
createPlaywrightHelpers(options?) returns Playwright’s test and expect, with Mock Service Worker (MSW) request mocking and GraphQL response waiting. Import the factory from its domain entry point:
The defaultHandlers option accepts handlers from the selected MSW major. Both factories provide the same fixture names:
import {
createPlaywrightHelpers,
type CreatePlaywrightHelpersOptions,
type PlaywrightHelpers,
} from "@octopus-energy/playwright/msw/v2";
const { test: base, expect } = createPlaywrightHelpers();createPlaywrightHelpersProp
Type
Omit options to start without default request handlers:
CreatePlaywrightHelpersOptionsProp
Type
The returned expect is Playwright’s standard assertion helper. The returned test supports test.extend(...) and retains Next.js test-mode fixtures and Playwright’s built-in fixtures:
PlaywrightHelpersProp
Type
Its additional fixtures are:
HelperFixturesProp
Type
Both entry points also export MswFixture, GraphQLPredicate, and WaitForGraphQLResponseFixture. Import them from the same entry point as your factory.
The msw fixture exposes the native http and graphql factories for the selected MSW major, preserving their signatures and options. You can construct handlers with msw.http and msw.graphql, or import the factories directly from the matching MSW version, then register handlers with msw.use(...). Direct imports also let you construct handlers outside a running fixture, such as defaultHandlers.
msw.use(...handlers) registers per-test handlers ahead of defaultHandlers. Mocked browser fetch and XMLHttpRequest (XHR) responses preserve Set-Cookie headers through route.fulfill, with multiple values separated by newlines. The browser applies its normal cookie rules; the helper does not call context.addCookies(...). Handler exceptions propagate; only an undefined handler result falls through. See the MSW fixture guide for handler and cookie examples.
Both versions use Next.js's lower-level test proxy, not its MSW-specific fixture. The bridges mock HTTP and GraphQL, not WebSocket, SSE, or streaming connections. They capture handlers when a request starts; later overrides affect subsequent requests. Generator handlers restart in the next test.
Teardown fails promptly if resolvers outlive cancellation. Await mocked requests or handle request.signal. Cleanup errors override test.fail() so Playwright recycles the worker.
Request Cookie headers pass through unchanged; browser-context cookies are not injected into server-side fetches. Forward any required request cookies explicitly. Server-side mocked responses retain Set-Cookie headers without changing browser cookies. The application must explicitly forward those cookies to its browser response, including from Server Actions.
waitForGraphQLResponse
waitForGraphQLResponse(operation, action?) waits for a matching browser GraphQL response. Request it from the test returned by createPlaywrightHelpers, not as a separately imported function.
WaitForGraphQLResponseFixtureProp
Type
Matching follows these constraints:
- In MSW 2, a string or regular expression matches query operation names, not mutation names; use a named mutation document for mutations
- MSW 3 supports query and mutation selectors, including operation names
- A named GraphQL
DocumentNodecan select a query or mutation. Unnamed documents are invalid. actionis optional and runs after the response listener starts when supplied- MSW 2 matches browser
POSTresponses; MSW 3 matches browserGETandPOSTresponses - Both versions require HTTP status
200, including responses with GraphQL errors; server-side fetches don’t match
The helper returns Playwright’s Response and uses page.waitForResponse timeout behavior. If you omit action, trigger the browser request after starting the wait. See the GraphQL waiting example for usage.
withGlobalConfig
withGlobalConfig(defaultConfig?) creates a globalConfig fixture for values read through @vercel/global-config. Import the factory from its domain entry point:
import { withGlobalConfig } from "@octopus-energy/playwright/global-config";The optional defaults infer the fixture’s value shape. They must satisfy GlobalConfigItems from the @vercel/global-config software development kit (SDK):
withGlobalConfigProp
Type
The factory returns fixtures for test.extend(...). Each test starts with its own defaults. Call globalConfig.use(data) to change subsequent mocked reads without updating the real configuration store. See the Global Config fixture guide for composition.
All configuration and flag fixtures expose their current values and a synchronous use(data) method. The method shallow-merges overrides. Later calls replace matching keys while unspecified keys keep their values:
FixtureWithUseProp
Type
Nested values replace rather than deep-merge. use accepts additional keys and doesn’t validate values at runtime.
withGlobalConfigFlags
withGlobalConfigFlags(defaultFlags?, options?) creates a globalConfigFlags fixture for the @octopus-energy/flags Global Config adapter. Import the factory from its domain entry point:
import { withGlobalConfigFlags } from "@octopus-energy/playwright/flags/global-config";Defaults infer the fixture’s value shape. Pass JavaScript Object Notation (JSON) flag values, not provider-specific flag definitions:
withGlobalConfigFlagsProp
Type
The item key must match the application’s adapter configuration:
WithGlobalConfigFlagsOptionsProp
Type
The fixture chooses the first configured key in this order:
options.keyOE_FLAGS_GLOBAL_CONFIG_KEYin the Playwright process"flags"
import type { WithGlobalConfigFlagsOptions } from "@octopus-energy/playwright/flags/global-config";
const options: WithGlobalConfigFlagsOptions = { key: "checkout-flags" };
const test = base.extend(withGlobalConfigFlags({ checkoutRedesign: false }, options));Setting OE_FLAGS_GLOBAL_CONFIG_KEY only in webServer.env configures the application server, not the Playwright fixture. Set it in the Playwright process too, or pass options.key.
The factory returns fixtures for test.extend(...). globalConfigFlags.use(data) uses the configuration override method. See the Global Config flags guide for adapter setup.
withVercelFlags
withVercelFlags(defaultFlags?) creates a vercelFlags fixture for flags evaluated by @flags-sdk/vercel. Import the factory from its domain entry point:
import { withVercelFlags } from "@octopus-energy/playwright/flags/vercel";Defaults infer the fixture’s value shape. Pass JSON flag values, not provider-specific flag definitions:
withVercelFlagsProp
Type
The factory returns fixtures for test.extend(...). vercelFlags.use(data) uses the configuration override method.
See the Vercel flags guide for setup.
composeGlobalSetup
Import composeGlobalSetup(...setups) and its Cleanup and Setup types from @octopus-energy/playwright/setup:
import { composeGlobalSetup, type Cleanup, type Setup } from "@octopus-energy/playwright/setup";composeGlobalSetupProp
Type
Each Setup receives Playwright’s FullConfig and may return a Cleanup, synchronously or asynchronously. A Cleanup takes no arguments and returns void or Promise<void>:
import type { FullConfig } from "@playwright/test";
type Cleanup = () => void | Promise<void>;
type Setup = (config: FullConfig) => void | Cleanup | Promise<void | Cleanup>;The returned global setup runs setups sequentially with the same config, then returns memoized asynchronous cleanup. Cleanup runs in reverse order and attempts every registered cleanup, even if one fails; repeated calls share the same promise. Cleanup failures are reported in an AggregateError.
If a setup fails, completed setups roll back in reverse order. The failing setup must clean up its own partially initialized resources because it has not returned a cleanup yet. If rollback also fails, the error aggregates the setup and cleanup failures. See the OAuth redirect recipe for composition.
withBlueprintAuth
withBlueprintAuth(config: BlueprintAuthConfig, options?: { defaultIssuer?: string }) creates a blueprintAuth fixture for signed Blueprint test tokens, session cookies, OAuth and GraphQL authentication mocks, and public key mocking. The adapter owns and exports BlueprintAuthConfig: pass a plain test object or a resolved application config if it is safe to import in Playwright. SDK MockAuthConfig, a test-side createAuthConfig call, and manual runner environment configuration are not required. The worker restores a narrow SDK MockTokenSigner with createMockTokenSigner({ keys: blueprintAuthKeys }). The SDK owns signing, session composition, protocol validation, organization-cache keys, and encryption; the adapter binds defaults and endpoints, registers handlers, and owns browser cookies and resource lifecycle.
Import authentication APIs from the subpath:
import {
withBlueprintAuth,
type BlueprintAuthConfig,
} from "@octopus-energy/playwright/blueprint-auth";The exported config has this structural shape; it does not configure the signer:
interface BlueprintAuthConfig {
krakenConfig: {
authEndpoint: string;
graphqlAuthEndpoint: string;
oauthClientId: string;
};
encryption?: { key: string };
}Extend the MSW-enabled helpers and configure createSigningKeysSetup() as Playwright’s globalSetup for a shared app. Alternatively, supply worker-owned keys and an isolated app through the worker fixtures. The factory returns fixtures for test.extend(...). Requesting blueprintAuth registers the public JSON Web Key Set (JWKS) mock for that test; no authorize server starts automatically.
withBlueprintAuthProp
Type
WithBlueprintAuthOptionsProp
Type
The first argument requires config.krakenConfig.authEndpoint, config.krakenConfig.graphqlAuthEndpoint, and config.krakenConfig.oauthClientId (the OAuth audience); config.encryption.key is optional. These fields belong to the application-facing adapter; SDK signing and key generation need no app config. withBlueprintAuth rejects a missing or empty krakenConfig.authEndpoint immediately. The GraphQL auth endpoint serves the upstream auth mocks and is independent of the JWKS endpoint and access-token issuer. The only second-argument option is defaultIssuer?: string.
A nonempty config.encryption.key enables a globalConfig dependency even for token-only tests: compose .extend(withGlobalConfig()).extend(withBlueprintAuth(testAuthConfig)) once, in that order. The auth fixture reuses the existing globalConfig; no per-call fixture argument is needed. Configs without a key remain independent of globalConfig, but cannot use organization auth. Define test values inline in the fixture’s config object and map its fields into the app’s webServer.env; the app keeps its normal createAuthConfig integration. See the organization authentication recipe.
The worker fixture blueprintAuthEndpoint defaults to config.krakenConfig.authEndpoint. An override changes adapter-bound endpoint settings without mutating the supplied config or configuring the signer. The adapter supplies the resolved issuer on each SDK call and calls createMockJwksHandler({ signer, authEndpoint: blueprintAuthEndpoint }). The SDK resolves the descriptor’s .url as new URL(".well-known/jwks.json", blueprintAuthEndpoint).href. Use an absolute root auth URL in these examples: https://auth.example.test/ serves mocked JWKS at https://auth.example.test/.well-known/jwks.json. JWKS keeps relative URL resolution; OAuth handlers resolve /token/ at the auth origin.
The endpoint controls JWKS and server-backed token-exchange URLs, the adapter’s session ID-token issuer default, and its auto-derived access-token issuer. Non-loopback .test endpoints remain valid for seeded sessions and intercepted JWKS; only server-backed OAuth exchange requires a live loopback authorization service. The auto-derived issuer tracks blueprintAuthEndpoint overrides; a custom factory defaultIssuer remains fixed. The application’s trusted access-token issuers must be configured separately.
Two public worker fixtures can be overridden through .extend(...):
| Fixture | Default |
|---|---|
blueprintAuthKeys | Shared keys from createSigningKeysSetup() |
blueprintAuthEndpoint | config.krakenConfig.authEndpoint; used for the test’s JWKS mock |
blueprintAuthKeys is typed unknown: it accepts serialized input in the SDK’s supported key format, not crypto key objects. SDK exportKeys() returns MockAuthKeys: { version: 1; privateKey: JWK; publicKey: JWK }. To supply worker-owned keys instead of using the shared setup, create a signer with const signer = await createMockTokenSigner(), then override the fixture with await signer.exportKeys(). All test keys are exportable by default.
The test-scoped blueprintAuth exposes these methods:
| Method | Resolved return value | Cookies |
|---|---|---|
createAccessToken(options) | string | None |
setAccessToken(options, cookieOptions?) | string | Access token |
createOAuthIdToken(options) | string | None |
setRefreshToken(value?, cookieOptions?) | string | Refresh token |
login({ authMethod?: "oauth", ... }, cookieOptions?) | BlueprintAuthTokens | OAuth session |
login({ authMethod: "email", ... }, cookieOptions?) | BlueprintAuthEmailTokens | Email session |
login({ authMethod: "mobile-web-view", ... }, cookieOptions?) | BlueprintAuthEmailTokens | Mobile web-view session |
mock.email.login(options) | BlueprintAuthEmailTokens on success; void on error | None |
mock.email.refresh(options) | void | None |
mock.oauth.login(options) | BlueprintAuthTokens on success; void on error | None |
mock.oauth.refresh(options) | void | None |
mock.scoped.login(options) | { accessToken: string } on success; void on error | None |
mock.masquerade.login(options) | { accessToken: string } on success; void on error | None |
mock.organization(options) | string | None |
logout(cookieOptions?) | void | Clears auth cookies |
All methods are asynchronous. Known-success logins return the session directly, not a descriptor or { session } wrapper. Known-error logins return Promise<void>; unresolved success/error option unions return Promise<Session | undefined>. Both refresh methods always return Promise<void> and create no initial session.
Every signing helper accepts an optional issuer: top-level for raw token helpers, login, and mock.organization; inside session for successful protocol calls under mock.email, mock.oauth, mock.scoped, and mock.masquerade. The adapter defaults it to new URL("token/", blueprintAuthEndpoint).href using the current worker endpoint. The optional second argument { defaultIssuer?: string } replaces this default; an explicit per-call issuer takes precedence over either default. The adapter never selects an issuer from validation.accessTokenIssuers.
createAccessToken and setAccessToken use the SDK’s MockAuthAccessTokenOptions with this issuer defaulting and return Promise<string>. The resolved issuer becomes the access token’s iss claim. Factory and per-call issuer strings are preserved exactly without URL normalization, including any trailing slash, and must match an issuer trusted by the application.
This example uses the MSW 2 factory and imports the basic test config, which omits encryption. The adapter’s token-URL default is a test convention, not an SDK or universal OpenID Connect default. Production issuers are provider-defined and need not be token endpoint URLs:
import { createPlaywrightHelpers } from "@octopus-energy/playwright/msw/v2";
import { withBlueprintAuth } from "@octopus-energy/playwright/blueprint-auth";
import { testAuthConfig } from "@/lib/playwright/auth-config";
const { test: base } = createPlaywrightHelpers();
const test = base.extend(withBlueprintAuth(testAuthConfig));
test("uses a default issuer or overrides it", async ({ blueprintAuth }) => {
await blueprintAuth.createAccessToken({ authMethod: "email", subject: "alice" });
await blueprintAuth.createAccessToken({
issuer: "https://other-api.kraken.test/graphql/",
authMethod: "email",
subject: "alice",
});
});createAccessToken(options) only returns the signed token. It has no cookie parameter, sets no cookies, and needs no target origin or baseURL.
setAccessToken(tokenOptions, cookieOptions?) also adds an accessToken cookie to the browser context and returns the original signed token. The adapter forwards an explicit cookieOptions.domain unchanged, otherwise the bare hostname from baseURL, or undefined if neither is available. A bare hostname gives host-only Playwright scope, not a Blueprint Domain default; use ".example.test" explicitly for subdomains. Cookie setters need valid Playwright scope; Playwright reports invalid scope.
createOAuthIdToken(options) delegates to signer.createOAuthIdToken and returns Promise<string> without changing cookies. It uses MockOAuthIdTokenOptions with required subject and optional issuer resolved by the adapter, plus optional audience (falling back to config.krakenConfig.oauthClientId), claims, and dates. This raw helper uses the adapter’s bound default, including a custom factory defaultIssuer, unless its own issuer overrides it. For a Blueprint callback response, the expected ID-token issuer is the worker’s token endpoint URL; ID-token validation remains separate from access-token validation.
login(options, cookieOptions?) signs an OAuth, email, or mobile web-view session offline and seeds browser cookies. Its exported BlueprintAuthLoginOptions is the union of these exported option types; all require subject:
| Option type | SDK basis and adapter defaults | authMethod | Return type |
|---|---|---|---|
BlueprintAuthOAuthSessionOptions | MockOAuthSessionOptions with issuer, audience, and idTokenIssuer optional | "oauth" or omitted | Promise<BlueprintAuthTokens> |
BlueprintAuthEmailSessionOptions | MockEmailSessionOptions with issuer optional | "email" (required) | Promise<BlueprintAuthEmailTokens> |
BlueprintAuthMobileWebViewSessionOptions | MockEmailSessionOptions with issuer optional | "mobile-web-view" (required) | Promise<BlueprintAuthEmailTokens> |
Omitted or explicit authMethod: "oauth" retains the existing return type: BlueprintAuthTokens remains an alias of SDK MockOAuthSession, containing { accessToken, refreshToken, idToken }. Email and mobile web-view return SDK MockEmailSession through the BlueprintAuthEmailTokens alias, containing only { accessToken, refreshToken }. An unresolved BlueprintAuthLoginOptions union returns Promise<MockOAuthSession | MockEmailSession>.
OAuth calls createMockOAuthSession(signer, ...) with the resolved issuer, audience, and ID-token issuer; audience falls back to config.krakenConfig.oauthClientId. Use separate accessTokenClaims and idTokenClaims, not additionalClaims; claims are not copied between tokens. The ID-token issuer defaults to new URL("token/", blueprintAuthEndpoint).href, independently of the access-token default, and can be overridden with idTokenIssuer. Both JWTs share subject and dates. Email and mobile web-view use SDK MockEmailSessionOptions with additionalClaims, not accessTokenClaims; neither accepts OAuth audience, ID-token options, or credentials.
All modes use the access-token issuer defaults described above and SDK Date options issuedAt/expiresAt, with a one-hour lifetime by default. Omit refreshToken for a random UUID or supply a custom value. OAuth adds accessToken, refreshToken, and oAuthIdToken cookies together; email adds only accessToken and refreshToken and removes an existing oAuthIdToken only in the same cookie domain/path, preserving unrelated cookies and other scopes. Mobile web-view signs an email-style access token and sets MWAuthToken and MWRefreshToken instead of the email cookie names, with the same scoped oAuthIdToken removal. Its returned fields remain accessToken and refreshToken. All cookies set by each mode share the selected scope, flags, and expiry. Cookie scope is passed to Playwright as for setAccessToken; Playwright owns scope validation.
No mode installs login or refresh mocks, makes network requests, or navigates, so seeding does not exercise a login flow. Register mock.email.refresh or mock.oauth.refresh independently when needed; no session settings are inherited. The individual token setters remain independent and do not seed a joint session.
logout(cookieOptions?) returns Promise<void> and accepts only Pick<BlueprintAuthCookieOptions, "domain" | "path">. It passes an auth-cookie-name regular expression and available domain/path filters to Playwright’s clearCookies, matching only these seven SDK auth cookies: accessToken, refreshToken, oAuthIdToken, pkceVerifier, oauthNextPage, MWAuthToken, and MWRefreshToken. The domain filter uses an explicit domain or the baseURL hostname when available; otherwise it is undefined. Neither baseURL nor a domain is required for clearing. Other cookies are preserved, and it does not navigate.
mock.email.login and mock.email.refresh
mock.email.login(options) calls SDK createMockEmailAuth.loginHandler; mock.email.refresh(options) calls createMockEmailAuth.refreshHandler. Both register the returned descriptor automatically as http.post(handler.url, handler.handle). They set no cookies and do not navigate. Signer and endpoint are fixture-bound and are not public options.
| Exported option type | Required top-level match fields | Outcome |
|---|---|---|
BlueprintAuthEmailLoginOptions | credentials: { email: string; password: string } | session or errorCode |
BlueprintAuthEmailRefreshOptions | refreshToken: string | session or errorCode |
A success requires nested session.subject. Optional session.issuer uses the adapter default; issuedAt, expiresAt, and additionalClaims also belong inside session. Login additionally accepts session.refreshToken, generated when omitted. A known-success login returns Promise<BlueprintAuthEmailTokens> directly; BlueprintAuthEmailTokens aliases SDK MockEmailSession, containing { accessToken, refreshToken }.
For a failure, supply only errorCode as the outcome, without session or signer, retaining the required match fields. Use Kraken wire codes (MappedKrakenErrorCode), such as "KT-CT-1138", not symbolic names. Known-error logins return Promise<void>; unresolved success/error options return Promise<BlueprintAuthEmailTokens | undefined>.
Refresh is independent and always returns Promise<void> with no initial session. Its top-level refreshToken is only a credential matcher; it is not allowed inside session, and the response retains the matched value. No refresh handler is installed by login, and no subject, issuer, claims, or dates are inherited from login. Successful refresh signs a replacement on each matching request, defaulting to the signer's current clock and a one-hour lifetime; explicit dates describe the replacement. See the session refresh recipe.
mock.oauth.login and mock.oauth.refresh
mock.oauth.login(options) calls SDK createMockOAuth.loginHandler for authorization-code exchange; mock.oauth.refresh(options) calls createMockOAuth.refreshHandler. Both register automatically as http.post(handler.url, handler.handle), set no cookies, and do not navigate. authEndpoint and signer remain fixture-bound.
| Exported option type | Required top-level match fields | Optional top-level field | Outcome |
|---|---|---|---|
BlueprintAuthOAuthLoginOptions | redirectUri: string | clientId: string | session or errorCode |
BlueprintAuthOAuthRefreshOptions | refreshToken: string | clientId: string | session or errorCode |
clientId defaults to config.krakenConfig.oauthClientId and controls both matching and ID-token audience. There is no handler audience option. Login's redirectUri is top-level and must match the callback URL exactly. Successful exchange requires a loopback startMockAuthorizationServer; configured failures and offline refresh do not. The SDK owns one-use codes, PKCE, client/redirect checks, and redemption. See the OAuth redirect recipe.
A success requires nested session.subject; optional session.issuer uses the adapter default. Optional issuedAt, expiresAt, accessTokenClaims, idTokenClaims, and idTokenIssuer also belong inside session. The ID-token issuer defaults to new URL("/token/", blueprintAuthEndpoint).href, independently of the access-token issuer. Login additionally accepts session.refreshToken, generated when omitted. A known-success login returns Promise<BlueprintAuthTokens> directly, containing { accessToken, refreshToken, idToken }.
For a failure, retain the match fields and replace session with errorCode: "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", "unsupported_grant_type", or "invalid_scope". No session or signer is accepted. Responses use OAuth's { error: errorCode }, not GraphQL errors. Known-error logins return Promise<void>; unresolved success/error options return Promise<BlueprintAuthTokens | undefined>.
Refresh must be registered independently and always returns Promise<void> with no initial session. Its required top-level refreshToken matches the credential and is retained in responses; session.refreshToken is not allowed. Successful refresh signs replacement access/ID tokens per matching request. No login settings are inherited; refresh defaults to the signer's current clock and a one-hour lifetime unless explicit dates are supplied. The combined mock helpers and their old option types are removed without compatibility aliases.
Upstream authentication mocks
These helpers select their own auth method, set no cookies, and do not navigate. Unlike the protocol methods under mock.email, mock.oauth, mock.scoped, and mock.masquerade, mock.organization(options) is directly callable: it has no .login or .refresh methods and accepts no session or errorCode fields. Organization token settings, including optional issuer, stay top-level.
| Method | Exported option type | Required top-level match fields | Successful return |
|---|---|---|---|
mock.scoped.login(options) | BlueprintAuthScopedLoginOptions | preSignedKey: string | Promise<{ accessToken: string }> |
mock.masquerade.login(options) | BlueprintAuthMasqueradeLoginOptions | userId: string, masqueradeToken: string | Promise<{ accessToken: string }> |
mock.organization(options) | BlueprintAuthOrganizationOptions | None; requires configured encryption and globalConfig | Promise<string> |
Scoped and masquerade successes require nested session with subject; optional issuer, SDK issuedAt/expiresAt dates, and additionalClaims also belong inside session. userId is matching data, not the token subject. For failures, retain the match fields and supply errorCode (a Kraken wire code) instead of session; no session or signer is accepted. Known-error logins return Promise<void>; unresolved success/error option unions return Promise<{ accessToken: string } | undefined>. Neither method provides refresh.
The adapter calls SDK createMockScopedAuth.loginHandler and createMockMasqueradeAuth.loginHandler, binding the signer and GraphQL endpoint. The SDK owns protocol validation and matching of the exact endpoint, operation, and credentials. The protocol authentication descriptors, including email and GraphQL exchanges, are registered through HTTP POST; .operationName metadata does not require MSW GraphQL registration. JWKS remains standalone and uses the single-object createMockJwksHandler({ signer, authEndpoint }) factory.
The protocol-handler SDK factories create descriptors, not interception or listening services. The adapter registers them automatically without request/response translation. Equivalent direct registration is:
msw.use(
msw.http.get(publicKeys.url, publicKeys.handle),
msw.http.post(emailLogin.url, emailLogin.handle),
msw.http.post(emailRefresh.url, emailRefresh.handle),
msw.http.post(scoped.url, scoped.handle),
msw.http.post(masquerade.url, masquerade.handle),
msw.http.post(exchange.url, exchange.handle),
msw.http.post(oauthRefresh.url, oauthRefresh.handle),
);Here each value is the corresponding SDK descriptor. Successful SDK login descriptors expose .session; fixture login calls return that session directly. Error and refresh descriptors expose no session. A non-MSW caller invokes descriptor.handle({ request }) and receives a native Response | undefined. Matching inspects cloned request bodies before signing replacements or consuming codes. Only undefined falls through; exceptions propagate, including through the browser cookie interceptor.
Multiple credential-specific mocks coexist; wrong credentials, other endpoints, and unrelated operations fall through rather than receiving a token. Overlapping selectors follow interceptor precedence: OAuth logins with the same endpoint, client ID, and redirect URI are not distinct scenarios. The upstream handlers do not replace application routes. Navigate to app-owned appRoutes.anon or appRoutes.masquerade URLs with parameters matching configured extractors to exercise real token validation and cookie handling. Mock application-data requests separately.
mock.organization(options) requires a nonempty config.encryption.key and composition with withGlobalConfig() before withBlueprintAuth(...). It calls the unchanged SDK factory createMockOrganizationAuth(signer, { graphqlAuthEndpoint, encryption, ... }) with fixture-bound endpoint/encryption and resolved token options. The SDK returns { accessToken, cacheKey, encryptedAccessToken }; the fixture merges { [cacheKey]: encryptedAccessToken } through the existing composed globalConfig.use and returns that exact signed API-key accessToken as Promise<string>, preserving other mocked configuration. Responses use the existing Global Config HTTP handler, not a new protocol-handler registration. Do not pass globalConfig, endpoint metadata, or encryption options per call. No real Global Config writes occur, and it does not authenticate the browser as a user. The application reads the cached token using the same config encryption key. See the organization authentication recipe for an example.
The public BlueprintAuthOrganizationOptions type is exported from @octopus-energy/playwright/blueprint-auth:
BlueprintAuthOrganizationOptionsProp
Type
Cookie options
BlueprintAuthCookieOptions is an interface exported from @octopus-energy/playwright/blueprint-auth. login and the token setters use these six optional native Playwright fields; expires is Unix seconds, not a Date:
| Option | Type | Default |
|---|---|---|
domain | string | Hostname from baseURL, or undefined; explicit values forwarded unchanged |
path | string | "/" |
httpOnly | boolean | true |
secure | boolean | true, even on HTTP |
sameSite | "Strict" | "Lax" | "None" | "Lax" |
expires | number | JWT expiry for login/setAccessToken; -1 (session) for setRefreshToken |
For expired-JWT tests, keep the cookie alive with { expires: Math.floor(Date.now() / 1000) + 60 } or { expires: -1 }. Overrides affect only the cookie, not the returned token.
setRefreshToken(value?, cookieOptions?) sets a refreshToken cookie and returns its value. Omit value to generate a random UUID, or supply a fixed value for your refresh-endpoint mock. It uses the same cookie options and scope as setAccessToken, but defaults to a session cookie (expires: -1). It does not sign refresh tokens or mock refresh requests.
const refreshToken = await blueprintAuth.setRefreshToken();
await blueprintAuth.setRefreshToken("test-refresh-token", { expires: -1 });setAccessToken does not add a refresh or ID-token cookie automatically. None of these methods mocks application data. See the signed-in Blueprint guide for session seeding versus redirect-flow tests.
Token options
Access-token claims and dates use SDK MockAuthAccessTokenOptions, with issuer made optional by the adapter. Raw SDK token functions require issuer; the adapter resolves the per-call value, custom factory default, or current worker token URL and supplies it on each call. The SDK owns signing and token claims. The table shows the adapter’s options:
MockAuthAccessTokenOptionsProp
Type
Raw OAuth ID-token options use SDK MockOAuthIdTokenOptions, with issuer and the signer’s required audience made optional by the adapter:
MockOAuthIdTokenOptionsProp
Type
Token helpers sign locally without a separate signing service or Playwright wire schema. Token options use SDK issuedAt/expiresAt dates; cookie expires uses Unix seconds.
createSigningKeysSetup
Configure createSigningKeysSetup() as Playwright’s globalSetup to generate fresh RS256 signing keys shared by all workers:
import { createSigningKeysSetup } from "@octopus-energy/playwright/blueprint-auth";
export default createSigningKeysSetup();createSigningKeysSetupProp
Type
Workers inherit the keys through the internal __OE_PLAYWRIGHT_AUTH_KEYS environment variable; no manual configuration is needed. Cleanup restores the previous environment state without overwriting newer values. For worker-owned keys, override blueprintAuthKeys.
The app verifies tokens using mocked public JWKS and does not need the private signing keys. Configure issuer settings separately.
The internal environment variable contains private test key JSON. Do not log it or include it in environment dumps. Traces may contain tokens and cookies; restrict artifact access and never use test keys in production.
SDK authorize server
Import startMockAuthorizationServer({ port? }) from @krakentech/blueprint-auth/testing. It returns Promise<{ origin: string; close(): Promise<void> }>. port defaults to 0, letting the OS allocate an available loopback port; origin reports the actual bound origin. The server takes no app config, signing keys, or fixed code. It owns unique, expiring, one-use authorization codes and their private consumption route, with PKCE binding and atomic redemption. It exposes no token or JWKS routes. Await close() during teardown.
For a shared app, use a fixed port because its environment must know the auth endpoint before startup. Return close, not the server object, from global setup:
import { startMockAuthorizationServer } from "@krakentech/blueprint-auth/testing";
import { composeGlobalSetup } from "@octopus-energy/playwright/setup";
import { createSigningKeysSetup } from "@octopus-energy/playwright/blueprint-auth";
import { authServerPort } from "./auth-config";
export default composeGlobalSetup(createSigningKeysSetup(), async () => {
const { close } = await startMockAuthorizationServer({ port: authServerPort });
return close;
});Export authServerPort = 4100 from the test config module and use it in the loopback testAuthConfig.krakenConfig.authEndpoint URL (http://127.0.0.1:4100/). Map that field to the app’s webServer.env.KRAKEN_AUTH_ENDPOINT. Pass the object to withBlueprintAuth(testAuthConfig). The server is opt-in and handles authorization and private code consumption only; its origin must match the app’s auth endpoint for this flow. Request blueprintAuth for JWKS and call mock.oauth.login({ redirectUri, session: { subject: "alice" } }) for token exchange and SDK-owned PKCE validation.
Worker fixtures can use const server = await startMockAuthorizationServer({ port: 0 }), supply server.origin as blueprintAuthEndpoint, and await server.close() in finally. Each worker needs an isolated app configured with that actual endpoint. The consumer supplies isolated app startup; these helpers do not launch apps. See the worker fixtures for override settings.
Deprecated compatibility fixtures
withEdgeConfig and withBlueprintFlags remain exported for existing integrations. Use withGlobalConfig and withGlobalConfigFlags, respectively, for the replacement integrations. Import compatibility helpers from their domain entry points:
import { withEdgeConfig } from "@octopus-energy/playwright/edge-config";
import {
withBlueprintFlags,
type WithBlueprintFlagsOptions,
} from "@octopus-energy/playwright/flags/blueprint";
const options: WithBlueprintFlagsOptions = { key: "blueprint-flags" };
const test = base
.extend(withEdgeConfig({ maintenanceMode: false }))
.extend(withBlueprintFlags({ darkMode: true }, options));withEdgeConfig
withEdgeConfig(defaultConfig?) returns fixtures for test.extend(...), with an edgeConfig fixture. Its optional defaults use the SDK’s EdgeConfigItems type:
withEdgeConfigProp
Type
edgeConfig.use(data) uses the configuration override method. The replacement fixture is named globalConfig.
withBlueprintFlags
withBlueprintFlags(defaultFlags?, options?) returns fixtures for test.extend(...), with a flags fixture for @krakentech/blueprint-utils/feature-flags. It converts flag values into that integration’s flag definitions:
withBlueprintFlagsProp
Type
WithBlueprintFlagsOptionsProp
Type
flags.use(data) uses the configuration override method. Match options.key to the application’s edgeConfigStoreKey. The default key is "flags". When withBlueprintFlags and withGlobalConfigFlags use the same key, their flags share one item. The replacement fixture is named globalConfigFlags.