sirius-press/plugins/sirius-press-sia-export/includes/class-spe-renderer.php

239 lines
8.2 KiB
PHP
Raw Normal View History

feat(sirius-press): a WordPress where the account is a key, not a mailbox WordPress makes two assumptions this project cannot accept: that identity comes from an email address, and that a site lives at one server. Both are things somebody else can take away — a mailbox is rented from a provider who can close it or be compelled to open it, and a server is one seizure from being gone. Sirius Press replaces the first and hedges the second. Signing in means signing a challenge with the key that controls a CashAddress. The address is recovered from the signature, so nothing is typed but the signature itself, and the result is an ordinary WordPress session cookie — roles, capabilities, nonces and the REST API never learn the login was different. Three ways to produce one: a wallet the browser already exposes, a phrase used once in the page and wiped, or a signature pasted in from any BIP-137 wallet, which needs no JavaScript and lets the key stay on a machine that never touches the web. There is no password reset, and the recovery page says so plainly rather than offering a form that cannot work. A reset mechanism is by construction a way to take an account from its owner, and it is always easier to attack than the cryptography it bypasses. Publishing a post also exports it as static HTML to the name's storage on Sia, signed by the key that owns the name, so the site keeps answering when the server does not. Email as a feature is untouched. wp_mail() still works, SMTP still sends, and contact forms still deliver to addresses real people typed. Only mail to the site's own unroutable placeholder addresses is diverted to an in-app inbox. The objection was to email as identity, not to email. Core is pinned and patched rather than vendored. WordPress 7.1.1 is 149 MB and 5,008 files; the fork's entire core diff is 75 lines in wp-admin/install.php. Carrying the former to express the latter would bury the patch where nobody reviews it and make every clone of the monorepo pay for it. Upstream releases still merge through tools/update-wordpress.sh, which reapplies the series and says exactly which hunk needs a human. The cryptography is implemented twice — PHP on the server, JavaScript in the page — because the server must verify and the browser must sign. Both are pinned against libauth, the library the Sirius portal wallet and the BNS gateway already use, so a disagreement of one byte fails the test suite rather than presenting as a rejected login at three in the morning. 132 checks, no framework, about a second.
2026-09-21 01:39:38 +02:00
<?php
/**
* Turning a live WordPress page into a file that stands on its own.
*
* The export is fetched over a loopback HTTP request rather than rendered
* in-process. That costs a round trip, and it is worth it: a theme's output
* depends on the whole request lifecycle the main query, `wp_head`,
* enqueued assets, late-filtered content, caching plugins. Re-creating that
* by calling `get_the_content()` produces something that looks like the page
* and is not the page, and the differences only show up in whichever theme
* the site owner actually uses.
*
* URLs are then rewritten to be document-relative. Not absolute, because the
* exported copy is served from the name, not from this WordPress host, and
* every absolute link would drag readers back to the origin the export exists
* to make optional. Not root-relative either, because the same bucket is
* browsable under `/bns/<name>/` on the public gateway, where a root-relative
* link points outside the site. Document-relative is the only form that works
* in both places.
*
* @package SiriusPress
*/
defined( 'ABSPATH' ) || exit;
final class SPE_Renderer {
/** Marks a request as the exporter's own, so the site can render for it. */
const FLAG = 'sirius_export';
/**
* Fetch a URL as an anonymous visitor would see it.
*
* @param string $url
* @return array{ok:bool,body:string,mime:string,error:string}
*/
public static function fetch( $url ) {
$request_url = add_query_arg( self::FLAG, self::token(), $url );
$response = wp_remote_get(
$request_url,
array(
'timeout' => 60,
'redirection' => 3,
// No cookies: the export must be what a logged-out reader
// sees, not what the admin who triggered it sees.
'cookies' => array(),
'sslverify' => apply_filters( 'sirius_press_export_sslverify', true ),
'headers' => array(
'user-agent' => 'SiriusPress/' . SIRIUS_PRESS_EXPORT_VERSION . ' (static export)',
'accept-encoding' => 'identity',
),
)
);
if ( is_wp_error( $response ) ) {
return self::error( $response->get_error_message() );
}
$code = (int) wp_remote_retrieve_response_code( $response );
if ( 200 !== $code ) {
return self::error( sprintf( 'the site returned HTTP %d for %s', $code, $url ) );
}
$body = wp_remote_retrieve_body( $response );
if ( '' === $body ) {
return self::error( sprintf( '%s rendered an empty page', $url ) );
}
return array(
'ok' => true,
'body' => $body,
'mime' => (string) wp_remote_retrieve_header( $response, 'content-type' ),
'error' => '',
);
}
/**
* A token proving a loopback request came from this site.
*
* Not a security boundary the pages being fetched are public. It exists
* so the site can recognise its own exporter and suppress things that
* make no sense in a static copy (admin bar, nonce-bearing markup) without
* giving a stranger a way to request that same altered output.
*/
public static function token() {
return substr( hash_hmac( 'sha256', 'sirius-export', wp_salt( 'nonce' ) ), 0, 24 );
}
/** True when the current request is the exporter fetching a page. */
public static function is_export_request() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
return isset( $_GET[ self::FLAG ] ) && hash_equals( self::token(), sanitize_text_field( wp_unslash( $_GET[ self::FLAG ] ) ) );
}
/**
* Rewrite a page's URLs for life outside this host.
*
* @param string $html
* @param string $doc_path Where this document will live, e.g. 'blog/hi/index.html'.
* @return array{html:string,assets:array<string,string>} Rewritten HTML and the
* local assets it referenced, as path => absolute source URL.
*/
public static function rewrite( $html, $doc_path ) {
$home = untrailingslashit( home_url() );
$site = untrailingslashit( site_url() );
$assets = array();
// The exporter's own marker must never survive into the output, or
// every internal link in the static copy carries it.
$html = preg_replace( '/([?&])' . preg_quote( self::FLAG, '/' ) . '=[^"\'&\s]*(&amp;|&)?/', '$1', $html );
$html = str_replace( array( '?"', "?'" ), array( '"', "'" ), $html );
$bases = array_unique( array( $home, $site, set_url_scheme( $home, 'http' ), set_url_scheme( $home, 'https' ) ) );
// Protocol-relative references to our own host (`//example.test/…`)
// are normalised to absolute first, so the pass below only has one
// shape to match.
//
fix(sirius-press): recovering a key is not the same as verifying a signature Running the fork against a live WordPress found a real hole in registration, and it is the kind that only shows up when you actually try it. ECDSA public-key recovery always succeeds. Given any well-formed signature and any digest it returns a key — just not the signer's, unless the digest is the one that was signed. The auth flow leaned on that as if a wrong message would fail. It does not; it quietly yields a stranger's address. At sign-in this was harmless, because the wrong address matches no account and the attempt fails. Registration and wallet-linking were another matter: both took the recovered address and bound it to an account, so a signature over slightly different text — a challenge copied without its blank line, a wallet that rewrote the text, a login signature replayed at the registration form — created an account keyed to an address nobody could sign for. The person would see "success" and discover the truth the next time they tried to get in. Wallet-linking was worse still: it would move an existing account onto a dead address and lock its owner out of their own site. Both paths now require the address the signer claims and compare it to the recovered one, which is what verification actually means. Sign-in accepts the claim when the page sends it and uses it to turn "no account uses that wallet" into the more useful "that signature is not over the text we asked for". Also from running it: URL rewriting mangled every link on a site whose URL carries a port. The protocol-relative pass matched inside absolute URLs and gave each one a second scheme, and matching the host without its port left the port stranded as `//host:8760:8760/`. Local and staging installs would have exported a site of broken links. Plain permalinks silently collapse an entire site onto one exported file, because every post's URL is `/?p=N` and its path is `/`. The queue looks healthy the whole time. The Publishing screen now says so. Translations loaded on `plugins_loaded`, which WordPress 6.7 warns about on every request — the kind of noise that trains people to stop reading logs. And one deletion: an `is_email()` filter written on the assumption that WordPress rejects `.invalid` addresses. It does not — `is_email()` validates syntax, not whether a domain could exist — so the filter never fired. A filter that appears to relax a rule but does not is worse than no filter, because someone later reasons from it. The documentation made the same claim and has been corrected. Verification added rather than asserted: tests/live.mjs drives a real instance over HTTP (40 checks), and tests/mock-gateway.mjs answers uploads with the signature check transcribed from the gateway's own source, so the publishing path can be exercised without a registered name.
2026-09-21 02:35:32 +02:00
// Two details, both of which produced mangled links when they were
// missing. The lookbehind stops this from also matching the
// `//example.test` sitting inside every `https://example.test`, which
// would give every absolute URL on the page a second scheme. And the
// authority has to include the port: replacing `//host` alone inside
// `//host:8760/x` leaves the port behind, producing `//host:8760:8760/x`.
foreach ( array_unique( array_filter( array( $home, $site ) ) ) as $base ) {
$authority = preg_replace( '#^https?:#', '', $base ); // '//host[:port]'
if ( '' === $authority ) {
continue;
}
feat(sirius-press): a WordPress where the account is a key, not a mailbox WordPress makes two assumptions this project cannot accept: that identity comes from an email address, and that a site lives at one server. Both are things somebody else can take away — a mailbox is rented from a provider who can close it or be compelled to open it, and a server is one seizure from being gone. Sirius Press replaces the first and hedges the second. Signing in means signing a challenge with the key that controls a CashAddress. The address is recovered from the signature, so nothing is typed but the signature itself, and the result is an ordinary WordPress session cookie — roles, capabilities, nonces and the REST API never learn the login was different. Three ways to produce one: a wallet the browser already exposes, a phrase used once in the page and wiped, or a signature pasted in from any BIP-137 wallet, which needs no JavaScript and lets the key stay on a machine that never touches the web. There is no password reset, and the recovery page says so plainly rather than offering a form that cannot work. A reset mechanism is by construction a way to take an account from its owner, and it is always easier to attack than the cryptography it bypasses. Publishing a post also exports it as static HTML to the name's storage on Sia, signed by the key that owns the name, so the site keeps answering when the server does not. Email as a feature is untouched. wp_mail() still works, SMTP still sends, and contact forms still deliver to addresses real people typed. Only mail to the site's own unroutable placeholder addresses is diverted to an in-app inbox. The objection was to email as identity, not to email. Core is pinned and patched rather than vendored. WordPress 7.1.1 is 149 MB and 5,008 files; the fork's entire core diff is 75 lines in wp-admin/install.php. Carrying the former to express the latter would bury the patch where nobody reviews it and make every clone of the monorepo pay for it. Upstream releases still merge through tools/update-wordpress.sh, which reapplies the series and says exactly which hunk needs a human. The cryptography is implemented twice — PHP on the server, JavaScript in the page — because the server must verify and the browser must sign. Both are pinned against libauth, the library the Sirius portal wallet and the BNS gateway already use, so a disagreement of one byte fails the test suite rather than presenting as a rejected login at three in the morning. 132 checks, no framework, about a second.
2026-09-21 01:39:38 +02:00
$html = preg_replace(
fix(sirius-press): recovering a key is not the same as verifying a signature Running the fork against a live WordPress found a real hole in registration, and it is the kind that only shows up when you actually try it. ECDSA public-key recovery always succeeds. Given any well-formed signature and any digest it returns a key — just not the signer's, unless the digest is the one that was signed. The auth flow leaned on that as if a wrong message would fail. It does not; it quietly yields a stranger's address. At sign-in this was harmless, because the wrong address matches no account and the attempt fails. Registration and wallet-linking were another matter: both took the recovered address and bound it to an account, so a signature over slightly different text — a challenge copied without its blank line, a wallet that rewrote the text, a login signature replayed at the registration form — created an account keyed to an address nobody could sign for. The person would see "success" and discover the truth the next time they tried to get in. Wallet-linking was worse still: it would move an existing account onto a dead address and lock its owner out of their own site. Both paths now require the address the signer claims and compare it to the recovered one, which is what verification actually means. Sign-in accepts the claim when the page sends it and uses it to turn "no account uses that wallet" into the more useful "that signature is not over the text we asked for". Also from running it: URL rewriting mangled every link on a site whose URL carries a port. The protocol-relative pass matched inside absolute URLs and gave each one a second scheme, and matching the host without its port left the port stranded as `//host:8760:8760/`. Local and staging installs would have exported a site of broken links. Plain permalinks silently collapse an entire site onto one exported file, because every post's URL is `/?p=N` and its path is `/`. The queue looks healthy the whole time. The Publishing screen now says so. Translations loaded on `plugins_loaded`, which WordPress 6.7 warns about on every request — the kind of noise that trains people to stop reading logs. And one deletion: an `is_email()` filter written on the assumption that WordPress rejects `.invalid` addresses. It does not — `is_email()` validates syntax, not whether a domain could exist — so the filter never fired. A filter that appears to relax a rule but does not is worse than no filter, because someone later reasons from it. The documentation made the same claim and has been corrected. Verification added rather than asserted: tests/live.mjs drives a real instance over HTTP (40 checks), and tests/mock-gateway.mjs answers uploads with the signature check transcribed from the gateway's own source, so the publishing path can be exercised without a registered name.
2026-09-21 02:35:32 +02:00
'#(?<!:)' . preg_quote( $authority, '#' ) . '#',
$base,
feat(sirius-press): a WordPress where the account is a key, not a mailbox WordPress makes two assumptions this project cannot accept: that identity comes from an email address, and that a site lives at one server. Both are things somebody else can take away — a mailbox is rented from a provider who can close it or be compelled to open it, and a server is one seizure from being gone. Sirius Press replaces the first and hedges the second. Signing in means signing a challenge with the key that controls a CashAddress. The address is recovered from the signature, so nothing is typed but the signature itself, and the result is an ordinary WordPress session cookie — roles, capabilities, nonces and the REST API never learn the login was different. Three ways to produce one: a wallet the browser already exposes, a phrase used once in the page and wiped, or a signature pasted in from any BIP-137 wallet, which needs no JavaScript and lets the key stay on a machine that never touches the web. There is no password reset, and the recovery page says so plainly rather than offering a form that cannot work. A reset mechanism is by construction a way to take an account from its owner, and it is always easier to attack than the cryptography it bypasses. Publishing a post also exports it as static HTML to the name's storage on Sia, signed by the key that owns the name, so the site keeps answering when the server does not. Email as a feature is untouched. wp_mail() still works, SMTP still sends, and contact forms still deliver to addresses real people typed. Only mail to the site's own unroutable placeholder addresses is diverted to an in-app inbox. The objection was to email as identity, not to email. Core is pinned and patched rather than vendored. WordPress 7.1.1 is 149 MB and 5,008 files; the fork's entire core diff is 75 lines in wp-admin/install.php. Carrying the former to express the latter would bury the patch where nobody reviews it and make every clone of the monorepo pay for it. Upstream releases still merge through tools/update-wordpress.sh, which reapplies the series and says exactly which hunk needs a human. The cryptography is implemented twice — PHP on the server, JavaScript in the page — because the server must verify and the browser must sign. Both are pinned against libauth, the library the Sirius portal wallet and the BNS gateway already use, so a disagreement of one byte fails the test suite rather than presenting as a rejected login at three in the morning. 132 checks, no framework, about a second.
2026-09-21 01:39:38 +02:00
$html
);
}
$pattern = '#(?:' . implode( '|', array_map( function ( $b ) {
return preg_quote( $b, '#' );
}, $bases ) ) . ')(/[^"\'\s<>\\\\)]*)?#';
$html = preg_replace_callback(
$pattern,
function ( $matches ) use ( $doc_path, &$assets ) {
$path = isset( $matches[1] ) ? $matches[1] : '/';
return self::localise( $path, $doc_path, $assets );
},
$html
);
return array(
'html' => $html,
'assets' => $assets,
);
}
/**
* One absolute URL becomes one relative one, and any asset it names gets
* remembered so the caller can queue it.
*/
private static function localise( $path, $doc_path, &$assets ) {
$parts = wp_parse_url( $path );
$clean = isset( $parts['path'] ) ? $parts['path'] : '/';
$suffix = ( isset( $parts['query'] ) && '' !== $parts['query'] ? '?' . $parts['query'] : '' )
. ( isset( $parts['fragment'] ) ? '#' . $parts['fragment'] : '' );
$target = SPE_Mapper::path_for_url_path( $clean );
if ( '' === $target ) {
// Nothing sensible to point at — an upload directory listing, a
// path with characters the bucket will not take. Leave the URL
// absolute rather than producing a link to nowhere.
return untrailingslashit( home_url() ) . $path;
}
if ( SPE_Mapper::is_asset( $target ) ) {
$assets[ $target ] = home_url( $clean );
// Assets are versioned with ?ver=; the bucket stores one copy, so
// the query string would only ever produce a 404.
$suffix = isset( $parts['fragment'] ) ? '#' . $parts['fragment'] : '';
}
return self::relative( $doc_path, $target ) . $suffix;
}
/**
* Path of `$target` as seen from the document at `$from`.
*
* `blog/post/index.html` referring to `assets/app.css` yields
* `../../assets/app.css`.
*/
public static function relative( $from, $target ) {
$from_dir = explode( '/', $from );
array_pop( $from_dir ); // Drop the file name.
$to = explode( '/', $target );
while ( $from_dir && $to && $from_dir[0] === $to[0] ) {
array_shift( $from_dir );
array_shift( $to );
}
$up = str_repeat( '../', count( $from_dir ) );
$rel = $up . implode( '/', $to );
return '' === $rel ? './' : $rel;
}
private static function error( $message ) {
return array(
'ok' => false,
'body' => '',
'mime' => '',
'error' => $message,
);
}
/**
* Strip the parts of a page that only make sense on the live site.
*
* Runs on the *live* request when the exporter is the one asking, which
* is why it is here rather than in the rewriting pass: removing the admin
* bar after the fact means also unpicking the styles and spacing it added.
*/
public static function hooks() {
add_action(
'init',
function () {
if ( ! self::is_export_request() ) {
return;
}
show_admin_bar( false );
/**
* Fires on a page being rendered for static export.
*
* The place for a theme or plugin to drop anything that cannot
* work without PHP behind it a live search box, a comment
* form, a cart widget.
*/
do_action( 'sirius_press_rendering_export' );
},
1
);
}
}