diff --git a/README.md b/README.md index 11a6b80..f5ff28d 100644 --- a/README.md +++ b/README.md @@ -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/' ], @@ -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. diff --git a/bin/pattern-library.mjs b/bin/pattern-library.mjs index 45c6146..f82ca3b 100755 --- a/bin/pattern-library.mjs +++ b/bin/pattern-library.mjs @@ -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'; @@ -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 ); diff --git a/docs/02-getting-started.md b/docs/02-getting-started.md index 1cd0d7c..ea55ef7 100644 --- a/docs/02-getting-started.md +++ b/docs/02-getting-started.md @@ -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 `. - -{: .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`: @@ -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 @@ -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: @@ -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 diff --git a/docs/03-plugin.md b/docs/03-plugin.md index a8bb381..8477e56 100644 --- a/docs/03-plugin.md +++ b/docs/03-plugin.md @@ -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: @@ -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. @@ -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 | | ----------------------------------------------- | ----------------------------------------- | @@ -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 | | ----------------------------- | -------------------------------------------------------------- | @@ -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: diff --git a/docs/04-npm-package.md b/docs/04-npm-package.md index a3082a4..703df1a 100644 --- a/docs/04-npm-package.md +++ b/docs/04-npm-package.md @@ -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 diff --git a/docs/architecture/2026-10-01-allow-unauthenticated-access-in-local-environments.md b/docs/architecture/2026-10-01-allow-unauthenticated-access-in-local-environments.md new file mode 100644 index 0000000..d90ccbc --- /dev/null +++ b/docs/architecture/2026-10-01-allow-unauthenticated-access-in-local-environments.md @@ -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. diff --git a/inc/namespace.php b/inc/namespace.php index 4961a82..58c119e 100644 --- a/inc/namespace.php +++ b/inc/namespace.php @@ -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() ); } /** diff --git a/src/capture.mjs b/src/capture.mjs index 731c576..876e477 100644 --- a/src/capture.mjs +++ b/src/capture.mjs @@ -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'; @@ -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 diff --git a/src/config.mjs b/src/config.mjs index 8457541..9b28498 100644 --- a/src/config.mjs +++ b/src/config.mjs @@ -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. @@ -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 @@ -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. * diff --git a/src/manifest.mjs b/src/manifest.mjs index b2f672d..9f99011 100644 --- a/src/manifest.mjs +++ b/src/manifest.mjs @@ -2,6 +2,8 @@ * Fetch and filter the site's pattern manifest. */ +import { hasCredentials } from './config.mjs'; + const SUPPORTED_MANIFEST_VERSION = 1; /** @@ -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=` creates one.', + ); + } + if ( response.status === 401 || response.status === 403 ) { throw new Error( `Authentication failed (HTTP ${ response.status }) for ${ config.username } at ${ url }. ` + diff --git a/tests/js/config.test.mjs b/tests/js/config.test.mjs index 1a80c62..1b2a683 100644 --- a/tests/js/config.test.mjs +++ b/tests/js/config.test.mjs @@ -9,7 +9,7 @@ import { mkdtemp, writeFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, isAbsolute } from 'node:path'; -import { loadConfig, requireConfig, flatClassify } from '../../src/config.mjs'; +import { loadConfig, requireConfig, hasCredentials, flatClassify } from '../../src/config.mjs'; const ENV_KEYS = [ 'PATTERN_LIBRARY_SITE', @@ -108,6 +108,24 @@ describe( 'loadConfig', () => { assert.equal( config.siteUrl, 'https://example.com' ); assert.equal( config.username, 'bot' ); assert.equal( config.appPassword, 'abcd efgh' ); + assert.equal( hasCredentials( config ), true ); + } ); + + test( 'treats credentials as optional, for a local site that needs none', async () => { + process.env.PATTERN_LIBRARY_SITE = 'http://localhost:8888'; + + const config = await loadConfig( cwd ); + + assert.equal( hasCredentials( config ), false ); + } ); + + test( 'rejects a login without a password, and a password without a login', async () => { + process.env.PATTERN_LIBRARY_WP_USER = 'bot'; + await assert.rejects( loadConfig( cwd ), /PATTERN_LIBRARY_WP_APP_PASSWORD/ ); + + delete process.env.PATTERN_LIBRARY_WP_USER; + process.env.PATTERN_LIBRARY_WP_APP_PASSWORD = 'abcd efgh'; + await assert.rejects( loadConfig( cwd ), /PATTERN_LIBRARY_WP_USER/ ); } ); test( 'lets the environment win over the config file, and CLI flags over both', async () => { diff --git a/tests/js/manifest.test.mjs b/tests/js/manifest.test.mjs index 76e8226..62601a0 100644 --- a/tests/js/manifest.test.mjs +++ b/tests/js/manifest.test.mjs @@ -172,6 +172,29 @@ describe( 'fetchManifest', () => { } ); } ); + test( 'sends no Authorization header when no credentials are configured', async () => { + const fetchStub = stubFetch( { body: JSON.stringify( manifest ) } ); + + await fetchManifest( config( { username: '', appPassword: '' } ) ); + + assert.equal( 'Authorization' in fetchStub.calls[ 0 ].options.headers, false ); + } ); + + test( 'explains a 401 to a request that sent no credentials', async () => { + stubFetch( { status: 401, body: 'Authentication required.' } ); + + await assert.rejects( + fetchManifest( config( { username: '', appPassword: '' } ) ), + ( error ) => { + assert.match( error.message, /requires credentials/ ); + assert.match( error.message, /WP_ENVIRONMENT_TYPE/ ); + assert.match( error.message, /PATTERN_LIBRARY_WP_USER/ ); + assert.doesNotMatch( error.message, /Authentication failed/ ); + return true; + }, + ); + } ); + test( 'points at an access proxy when HTML arrives instead of JSON', async () => { stubFetch( { body: 'Sign in', contentType: 'text/html' } ); diff --git a/tests/php/access-test.php b/tests/php/access-test.php index 2fe6b58..65c51a1 100644 --- a/tests/php/access-test.php +++ b/tests/php/access-test.php @@ -20,6 +20,7 @@ use const HM\Pattern_Library\ROLE; use function HM\Pattern_Library\allow_application_password; +use function HM\Pattern_Library\allows_unauthenticated; use function HM\Pattern_Library\current_user_can_view; use function HM\Pattern_Library\is_preview_request; @@ -28,6 +29,19 @@ */ class Access_Test extends WP_UnitTestCase { + /** + * Close the local-environment bypass. + * + * The suite runs in wp-env, whose environment type is `local`, and core + * caches the type for the life of the process. Without this every test of + * the capability gate would pass through the bypass instead. Tests of the + * bypass itself remove or replace the filter. + */ + public function set_up(): void { + parent::set_up(); + add_filter( 'pattern_library_allow_unauthenticated', '__return_false' ); + } + /** * Clear the query var between tests. */ @@ -128,6 +142,39 @@ public function test_the_capability_check_is_filterable(): void { $this->assertFalse( current_user_can_view() ); } + /** + * Without a filter, the bypass follows the environment type, and opens only + * for `local` — `development` is a hosted environment on Altis and VIP. + */ + public function test_the_bypass_defaults_to_local_environments_only(): void { + remove_filter( 'pattern_library_allow_unauthenticated', '__return_false' ); + + $this->assertSame( 'local' === wp_get_environment_type(), allows_unauthenticated() ); + } + + /** + * With the bypass open, a logged-out request can read the library. + */ + public function test_the_bypass_admits_a_logged_out_request(): void { + add_filter( 'pattern_library_allow_unauthenticated', '__return_true', 11 ); + + $this->assertSame( 0, get_current_user_id() ); + $this->assertTrue( current_user_can_view() ); + } + + /** + * A project that wants authentication everywhere can still have it, and + * pattern_library_user_can keeps the final word over the bypass. + */ + public function test_the_capability_filter_overrides_the_bypass(): void { + add_filter( 'pattern_library_allow_unauthenticated', '__return_true', 11 ); + add_filter( 'pattern_library_user_can', '__return_false' ); + + $this->assertFalse( current_user_can_view() ); + + remove_filter( 'pattern_library_user_can', '__return_false' ); + } + /** * The plugin hooks nothing onto the ordinary request path beyond the two * filters it needs, so an inactive route costs a visitor nothing.