Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,8 @@ wp plugin activate wp-pattern-library
add_filter( 'pattern_library_namespaces', fn () => [ 'my-theme/' ] );
```

```bash
# 3. Create an account for the generator. Prints an application password once.
wp pattern-library setup --login=pattern-library-bot
```

```js
// 4. pattern-library.config.js, in your project root.
// 3. pattern-library.config.js, in your project root.
export default {
title: 'My Theme Pattern Library',
namespaces: [ 'my-theme/' ],
Expand All @@ -57,10 +52,8 @@ export default {
```

```bash
# 5. Credentials come from the environment, never the config file.
# 4. Point it at the site. A local environment needs no credentials.
export PATTERN_LIBRARY_SITE="http://localhost:8888"
export PATTERN_LIBRARY_WP_USER="pattern-library-bot"
export PATTERN_LIBRARY_WP_APP_PASSWORD="xxxx xxxx xxxx xxxx"

npx @humanmade/wp-pattern-library build --dry-run # Look first.
npx @humanmade/wp-pattern-library build # Then capture.
Expand Down
5 changes: 3 additions & 2 deletions bin/pattern-library.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
* pattern-library generate Markdown only, from existing screenshots.
*
* Credentials come from PATTERN_LIBRARY_WP_USER and
* PATTERN_LIBRARY_WP_APP_PASSWORD; the site from --site or PATTERN_LIBRARY_SITE.
* PATTERN_LIBRARY_WP_APP_PASSWORD, and are optional against a site whose
* environment type is `local`; the site from --site or PATTERN_LIBRARY_SITE.
*/

import { loadConfig, requireConfig } from '../src/config.mjs';
Expand Down Expand Up @@ -69,7 +70,7 @@ async function main() {
const { site, dryRun, ...overrides } = options;
const config = await loadConfig( process.cwd(), { ...overrides, siteUrl: site } );

requireConfig( config, [ 'siteUrl', 'username', 'appPassword' ] );
requireConfig( config, [ 'siteUrl' ] );

const manifest = await fetchManifest( config );
const { patterns, skipped } = filterPatterns( manifest, config );
Expand Down
40 changes: 7 additions & 33 deletions docs/02-getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,33 +36,7 @@ add_filter( 'pattern_library_namespaces', fn () => [ 'my-theme/' ] );

Put this in your theme's `functions.php` or a small mu-plugin. The prefix is matched literally, so keep the trailing slash.

## 3. Create an account for the generator

The routes are gated behind a dedicated capability, `view_pattern_library`. A bundled WP-CLI command creates a role that holds it, plus a user in that role:

```bash
wp pattern-library setup --login=pattern-library-bot
```

It prints an application password once:

```
Store these as CI secrets — the password is not recoverable:
PATTERN_LIBRARY_WP_USER=pattern-library-bot
PATTERN_LIBRARY_WP_APP_PASSWORD=ExsLVnKTz0aSHpwTXGwBlTC7
```

Copy it now.

{: .warning }

> **Your own admin account won't work without a grant.** `view_pattern_library` is a custom capability, so no built-in role holds it — administrator included. To use an existing user instead of a bot account, run `wp pattern-library setup` and then `wp pattern-library grant <user>`.

{: .note }

> **Application passwords need HTTPS, or a local environment.** If the command warns that they're unavailable, set `WP_ENVIRONMENT_TYPE` to `local` in `wp-config.php`. Most local environments already do.

## 4. Configure the generator
## 3. Configure the generator

In your project root — the repository, not the WordPress install — create `pattern-library.config.js`:

Expand All @@ -74,17 +48,17 @@ export default {
};
```

Credentials never go in this file. They come from the environment:
Tell it where the site is:

```bash
export PATTERN_LIBRARY_SITE="http://localhost:8888"
export PATTERN_LIBRARY_WP_USER="pattern-library-bot"
export PATTERN_LIBRARY_WP_APP_PASSWORD="ExsLVnKTz0aSHpwTXGwBlTC7"
```

Use whatever URL you actually browse the site at. Plain HTTP and a port number are fine.

## 5. Look before you leap
No account or password is needed: when `WP_ENVIRONMENT_TYPE` is `local`, the plugin serves its routes to anyone. Most local environments set it already; if yours doesn't, set it in `wp-config.php`. Capturing any other environment takes credentials — see [access control]({{ site.baseurl }}/plugin#access-control).

## 4. Look before you leap

```bash
npx @humanmade/wp-pattern-library build --dry-run
Expand All @@ -102,7 +76,7 @@ Dry run — nothing written.

A large "skipped" number is usually correct — patterns hidden from the inserter and template parts are excluded by default. See [exclusions]({{ site.baseurl }}/npm-package#exclusions).

## 6. Capture a few patterns
## 5. Capture a few patterns

Before committing to a full run, try one. A bare argument filters by pattern basename:

Expand All @@ -123,7 +97,7 @@ Wrote /path/to/project/docs/pattern-library/README.md and 15 category pages.

Open `docs/pattern-library/README.md` and click through. This is the moment to check that fonts loaded, images resolved, and nothing is cut off.

## 7. Run the whole thing
## 6. Run the whole thing

```bash
npx @humanmade/wp-pattern-library build
Expand Down
31 changes: 19 additions & 12 deletions docs/03-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ The plugin belongs in whichever environment you capture *from*. If you only gene

### Enabling it temporarily

Because the plugin is inert unless its query var is present, it's reasonable to activate it on a production site, capture, and deactivate again — for instance to document patterns that were built in the editor rather than committed to the theme.
Because the plugin is inert unless its query var is present, it's reasonable to activate it on a production site, capture, and deactivate again — for instance to document patterns that were built in the editor rather than committed to the theme.

Nothing persists when deactivated except the role, and the routes can be switched off without deactivating:

Expand All @@ -42,7 +42,13 @@ Prefixes are matched literally, so keep the trailing slash. You can also filter

## Access control

The routes are gated behind `view_pattern_library`, a custom primitive capability. No built-in role holds it — administrators included. That's the point: the account that reads the library should hold that one capability and nothing else.
When the environment type is `local`, the routes are open to any request — no account or password needed. In all other environments, they're gated as described below. To require authentication locally too:

```php
add_filter( 'pattern_library_allow_unauthenticated', '__return_false' );
```

Outside a local environment, the routes are gated behind `view_pattern_library`, a custom primitive capability. No built-in role holds it — administrators included. That's the point: the account that reads the library should hold that one capability and nothing else.

```bash
wp pattern-library setup # Create the role.
Expand All @@ -66,7 +72,7 @@ add_filter( 'pattern_library_user_can', fn () => current_user_can( 'edit_theme_o

## The endpoints

Both are query vars on `index.php`, on the front end.
Both are query vars on `index.php`, on the front end.

| URL | Returns |
| ----------------------------------------------- | ----------------------------------------- |
Expand All @@ -79,7 +85,7 @@ Both are query vars on `index.php`, on the front end.

A pattern renders in a minimal HTML document with `wp_head()` and `wp_footer()` intact, so the theme's real stylesheets, fonts and block styles load — but with no site header, footer or admin bar. The pattern is wrapped in `#pattern-library-preview`, which is what the capture tool crops to.

Every response carries `X-Robots-Tag: noindex, nofollow` and cache-busting headers. An unauthenticated request gets a `401` with a `WWW-Authenticate` challenge.
Every response carries `X-Robots-Tag: noindex, nofollow` and cache-busting headers. Outside a local environment, an unauthenticated request gets a `401` with a `WWW-Authenticate` challenge.

| Query var | Purpose |
| ----------------------------- | -------------------------------------------------------------- |
Expand Down Expand Up @@ -138,14 +144,15 @@ Keep the plugin and the CLI on the same version. They ship from one repository u

## Filters

| Filter | Purpose |
| ----------------------------------- | ----------------------------------------- |
| `pattern_library_enabled` | Disable the routes entirely. |
| `pattern_library_namespaces` | Pattern-name prefixes to expose. |
| `pattern_library_user_can` | Override the capability check. |
| `pattern_library_placeholder_image` | Markup of the placeholder featured image. |
| `pattern_library_wrapper_open` | Opening markup of a variant wrapper. |
| `pattern_library_wrapper_close` | Closing markup of a variant wrapper. |
| Filter | Purpose |
| --------------------------------------- | ----------------------------------------------------------- |
| `pattern_library_enabled` | Disable the routes entirely. |
| `pattern_library_namespaces` | Pattern-name prefixes to expose. |
| `pattern_library_user_can` | Override the capability check. |
| `pattern_library_allow_unauthenticated` | Skip authentication; defaults to `local` environments only. |
| `pattern_library_placeholder_image` | Markup of the placeholder featured image. |
| `pattern_library_wrapper_open` | Opening markup of a variant wrapper. |
| `pattern_library_wrapper_close` | Closing markup of a variant wrapper. |

Disable the routes outside development:

Expand Down
2 changes: 2 additions & 0 deletions docs/04-npm-package.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ Credentials and the site URL come from the environment:
| `PATTERN_LIBRARY_WP_APP_PASSWORD` | That user's application password. |
| `PATTERN_LIBRARY_EXTRA_HEADERS` | Extra headers, one `Name: value` per line. |

The two credential variables are set together or not at all. Leave both unset against a site whose `WP_ENVIRONMENT_TYPE` is `local`, which serves the routes without authentication.

## Exclusions

```js
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Allow unauthenticated access in local environments

Date: 2026-10-01

## Status

Proposed

## Context

Currently the preview routes require authentication and a specific capability. Capturing a library therefore takes four steps before the first screenshot: create the role, create or grant a user, mint an application password, and export the login and password into the shell.

This is unnecessary on a developer's own machine, and we'd like to remove friction from the set up process so that it's easier to trial the plugin and see if it will be useful on a project.

## Decision

The plugin will allow unauthenticated requests when the environment type is
`local`. The decision is made by a new filter, `pattern_library_allow_unauthenticated`,
whose default is `'local' === wp_get_environment_type()`. Its result is
combined with the capability check before the existing `pattern_library_user_can`
filter runs, so that filter keeps the final word.

The CLI stops requiring credentials. It sends the `Authorization` header and
Playwright's `httpCredentials` only when both a login and a password are
configured; one without the other is a configuration error. When a site answers
401 to a request that carried no credentials, the error says the site requires
them, rather than reporting an authentication failure for a user that was never
named.

The decision stays on the server. The CLI does not try to detect a local site,
and has no flag that skips authentication; it only declines to send credentials
it does not have. A deployed site answers exactly as it did before.

The GitHub Action keeps `username` and `app-password` as required inputs. It
exists to capture deployed environments, where the credentials are needed, and
making them optional would turn a forgotten secret into a confusing 401 rather
than an immediate input error.

## Consequences

A local capture needs only the site URL: `wp pattern-library setup`, the
application password and the credential exports move out of the getting-started
path and into the section on capturing a deployed site.

The routes are open on any environment whose type is `local`, including one a
developer exposes through a tunnel such as ngrok, or a deployed environment that
is misconfigured as `local`. The exposure is bounded — the routes are read-only,
render only patterns the site already registers, and send `noindex` and
no-cache headers — and the same misconfiguration already relaxes core's HTTPS
requirement for application passwords. A project that wants authentication
everywhere returns false from `pattern_library_allow_unauthenticated`.

Unauthenticated local requests render as a logged-out visitor, which is what a
pattern looks like to most of its audience. The authenticated path already
suppresses the admin bar, so the two differ only where a theme or block varies
its output for logged-in users — and the bot account a deployed capture uses
holds no capability beyond `read`, so it sees close to the logged-out page too.

The filter exists partly so the behaviour can be tested. The test suite runs in
wp-env with `WP_ENVIRONMENT_TYPE` set to `local`, and core caches the
environment type for the life of the process, so the tests cannot switch it per
case. They control the filter instead.
23 changes: 21 additions & 2 deletions inc/namespace.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,28 @@ function current_user_can_view(): bool {
/**
* Filters whether the current user may read the pattern library.
*
* @param bool $can Whether the current user holds the capability.
* @param bool $can Whether the current user holds the capability, or the
* environment allows unauthenticated access.
*/
return (bool) apply_filters( 'pattern_library_user_can', current_user_can( CAPABILITY ) );
return (bool) apply_filters( 'pattern_library_user_can', current_user_can( CAPABILITY ) || allows_unauthenticated() );
}

/**
* Whether the routes are open to any request, authenticated or not.
*
* Only in a `local` environment, where provisioning a user and application
* password protects nothing. Not `development`: on Altis and VIP that names a
* hosted environment reachable from the internet.
*/
function allows_unauthenticated(): bool {
/**
* Filters whether the pattern library routes skip authentication.
*
* Return false to require authentication in every environment.
*
* @param bool $allow Whether the environment type is `local`.
*/
return (bool) apply_filters( 'pattern_library_allow_unauthenticated', 'local' === wp_get_environment_type() );
}

/**
Expand Down
12 changes: 6 additions & 6 deletions src/capture.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { chromium } from 'playwright';
import sharp from 'sharp';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { hasCredentials } from './config.mjs';
import { previewUrl, shotsFor } from './manifest.mjs';
import { resolveAnimations } from './animations.mjs';

Expand Down Expand Up @@ -146,12 +147,11 @@ export async function captureAll( patterns, config, log = () => {} ) {
// preview route sends with its 401. `send: 'always'` is deliberately not
// used: it only affects Playwright's API request context, not page
// navigation. Scoped to the site's origin so the password is never attached
// to third-party requests a theme makes (fonts, analytics, CDNs).
httpCredentials: {
username: config.username,
password: config.appPassword,
origin,
},
// to third-party requests a theme makes (fonts, analytics, CDNs). Omitted
// when there are none, for a local site that serves the routes without.
httpCredentials: hasCredentials( config )
? { username: config.username, password: config.appPassword, origin }
: undefined,
} );

// Access-proxy headers gate the origin ahead of WordPress, so every request the
Expand Down
24 changes: 23 additions & 1 deletion src/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const absolute = ( path, cwd ) => ( isAbsolute( path ) ? path : resolve( cwd, pa
*
* Precedence, lowest first: defaults, config file, environment, CLI overrides.
* Credentials come from the environment only — they should never be committed to
* a config file.
* a config file — and are optional: a local site needs none.
*
* @param {string} cwd Directory to resolve the config and output paths from.
* @param {Object} overrides Values from CLI flags.
Expand Down Expand Up @@ -123,6 +123,17 @@ export async function loadConfig( cwd = process.cwd(), overrides = {} ) {

config.variants = normalizeVariants( config.variants );

// Credentials are optional — a local site serves the routes without them —
// but half a pair is always a mistake, and would otherwise surface as a
// confusing 401 rather than naming the variable that is missing.
if ( Boolean( config.username ) !== Boolean( config.appPassword ) ) {
throw new Error(
`Configuration error: set both PATTERN_LIBRARY_WP_USER and PATTERN_LIBRARY_WP_APP_PASSWORD, or neither; only ${
config.username ? 'PATTERN_LIBRARY_WP_USER' : 'PATTERN_LIBRARY_WP_APP_PASSWORD'
} is set.`,
);
}

config.siteUrl = config.siteUrl.replace( /\/$/, '' );
config.outputDir = absolute( config.outputDir, cwd );
config.screenshotsDir = config.screenshotsDir
Expand Down Expand Up @@ -268,6 +279,17 @@ function clean( object ) {
);
}

/**
* Whether the configuration carries credentials to send to the site.
*
* Without them, requests go out unauthenticated. A site whose environment type
* is `local` serves the routes anyway; any other answers 401.
*
* @param {Object} config Resolved configuration.
* @return {boolean} Whether a login and application password are both set.
*/
export const hasCredentials = ( config ) => Boolean( config.username && config.appPassword );

/**
* Throw a helpful error when required configuration is missing.
*
Expand Down
17 changes: 16 additions & 1 deletion src/manifest.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
* Fetch and filter the site's pattern manifest.
*/

import { hasCredentials } from './config.mjs';

const SUPPORTED_MANIFEST_VERSION = 1;

/**
Expand Down Expand Up @@ -56,13 +58,26 @@ export function authHeader( config ) {
*/
export async function fetchManifest( config ) {
const url = previewUrl( config, '__manifest' );
const credentials = hasCredentials( config );
const response = await fetch( url, {
headers: { ...config.extraHeaders, Authorization: authHeader( config ) },
headers: {
...config.extraHeaders,
...( credentials ? { Authorization: authHeader( config ) } : {} ),
},
redirect: 'follow',
} );

const body = await response.text();

if ( response.status === 401 && ! credentials ) {
throw new Error(
`${ url } requires credentials (HTTP 401). Only a site whose WP_ENVIRONMENT_TYPE is ` +
'"local" serves the pattern library without them. Set PATTERN_LIBRARY_WP_USER and ' +
'PATTERN_LIBRARY_WP_APP_PASSWORD for a user holding the view_pattern_library capability; ' +
'`wp pattern-library setup --login=<login>` creates one.',
);
}

if ( response.status === 401 || response.status === 403 ) {
throw new Error(
`Authentication failed (HTTP ${ response.status }) for ${ config.username } at ${ url }. ` +
Expand Down
Loading
Loading