Replace Basic Auth with multi-user login, roles, groups, and Lib\Access

Admin login & user management (novaconium/ISSUES.md): session-based
login against a SQLite users table replaces the single-user HTTP Basic
Auth stopgap (admin_username/admin_password_hash and /admin/password-hash
are gone; one admin_auth_enabled flag, off by default with zero DB
footprint). New /admin/login, /admin/logout (POST-only, real page), and
/admin/users pages plus bin/create-admin-user.php.

First user created is the admin; everyone after is registered with a
unique normalized email and an optional group. /admin/* and drafts are
admin-only; Lib\Access gates page content from sidecars
(Access::require('group:members')) with login-redirect/404 responses —
public by default, static pages always public by construction. User
management covers disable/enable, delete, promote/demote, group, email,
and password, with last-active-admin lockout guards.

Also: Session::regenerate() against fixation, friendly missing-PDO-driver
errors in Lib\Db, docs at /admin/docs/access-control and updates across
admin-auth/drafts/sidecars/config/libraries and README/AGENTS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
code
2026-07-15 00:17:54 +00:00
parent cb64836901
commit b882c304b1
39 changed files with 1476 additions and 318 deletions
@@ -19,6 +19,7 @@
<li><a class="icon-link" href="/admin/docs/sitemap">{{ icons.sitemap() }}XML sitemap</a></li>
<li><a class="icon-link" href="/admin/docs/rss">{{ icons.rss() }}RSS feeds</a></li>
<li><a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}Admin authentication</a></li>
<li><a class="icon-link" href="/admin/docs/access-control">{{ icons.lock() }}Access control</a></li>
<li><a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}Draft pages</a></li>
<li><a class="icon-link" href="/admin/docs/layouts">{{ icons.book() }}Layouts</a></li>
<li><a class="icon-link" href="/admin/docs/caching">{{ icons.book() }}Static caching</a></li>
@@ -0,0 +1,70 @@
{% extends 'admin/docs/_layout/layout.twig' %}
{% import '_layout/icons.twig' as icons %}
{% block title %}Access control{% endblock %}
{% block description %}Assign a page or section to a user or group from its sidecar with Lib\Access — public by default, static pages always public.{% endblock %}
{% block robots %}noindex, nofollow{% endblock %}
{% block docs_content %}
<h1>Access control</h1>
<p><code>Lib\Access</code> (<code>novaconium/lib/Access.php</code>) assigns a page to a user, a group, or just "anyone logged in" — from the page's own sidecar, using the accounts <a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}Admin authentication</a> manages at <a href="/admin/users">/admin/users</a>. One call at the top of <code>index.php</code>:</p>
<pre><code>&lt;?php
use Lib\Access;
if ($denied = Access::require('group:members')) {
return $denied;
}
return [
// ...normal sidecar context...
];</code></pre>
<p><code>Access::require()</code> returns <code>null</code> when the request may proceed, or a <code>Response</code> the sidecar returns as-is: nobody logged in → a <code>303</code> to <a href="/admin/login">/admin/login</a> carrying a <code>?return=</code> path so a successful login lands right back on the page they wanted; logged in but not allowed → a plain <code>404</code>, the same hide-don't-tease posture as <a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}draft pages</a>.</p>
<h2>Rules</h2>
<ul>
<li><code>Access::require()</code> — no rules: any logged-in user (admin or registered).</li>
<li><code>Access::require('group:members')</code> — users whose group (assigned at <a href="/admin/users">/admin/users</a>) is <code>members</code>. Each user has at most one group; a group is just a text label, matched exactly — there's no groups table to manage.</li>
<li><code>Access::require('user:bob')</code> — exactly that account.</li>
<li><code>Access::require('group:members', 'user:bob')</code> — several rules mean <em>any</em> of them grants access.</li>
</ul>
<p><strong>Admins always pass every rule</strong> — the admin role exists to run the site, so there's no way to write a rule that locks an admin out of content.</p>
<h2>Public is the default — and static pages are always public</h2>
<p>A sidecar that never calls <code>Access::require()</code> is completely untouched by all of this, and a page with no sidecar at all <em>can't</em> call it — so sidecar-less pages are always public. That's load-bearing rather than incidental: only sidecar-less pages are ever written to the <a class="icon-link" href="/admin/docs/caching">{{ icons.book() }}static HTML cache</a>, which Apache serves before PHP (and therefore any access check) runs. Because a gated page necessarily has a sidecar, it's never statically cached, so there's no way to leak a gated page through the cache — the caching/auth rule that drafts and <code>/admin/*</code> need explicit cache exclusions for is satisfied here by construction.</p>
<h2>Gating a section</h2>
<p>There's no per-directory config for this — a "section" is gated by giving each page in it a sidecar with the same check, which stays visible and greppable at the page level. To keep the rule itself in one place, put a <code>_access.php</code> file in the section directory (any file that isn't <code>index.php</code>/<code>index.twig</code> is invisible to the router) and <code>require</code> it from each sidecar — a PHP file can return a value, so it composes exactly like a direct call:</p>
<pre><code>&lt;?php
// App/pages/members/_access.php — the section's one shared rule
use Lib\Access;
return Access::require('group:members');</code></pre>
<pre><code>&lt;?php
// App/pages/members/anything/index.php — each page in the section
if ($denied = require dirname(__DIR__) . '/_access.php') {
return $denied;
}
return [];</code></pre>
<h2>Interactions worth knowing</h2>
<ul>
<li><strong>Off means open.</strong> With <code>admin_auth_enabled</code> off (or while no users exist yet), <code>Access::require()</code> allows everything — there'd be nothing to log in as. Same open-until-configured posture as the rest of admin auth, and the same zero-footprint guarantee: it never touches <code>Lib\Db</code> in that state.</li>
<li><strong>Gated pages stay out of <a class="icon-link" href="/admin/docs/content-index">{{ icons.search() }}search and the sitemap</a> automatically.</strong> The content-index crawl runs every sidecar as an anonymous GET, so a gated sidecar short-circuits to the login redirect and the crawler skips the page — nothing to configure, verified for real. <code>require()</code> also has no side effects on deny (the return path travels in the redirect URL, not the session), so a crawl can't scribble on the visiting user's session.</li>
<li><strong>Who's logged in?</strong> A sidecar that wants to greet the user (or vary content by account) can read <code>App\AdminAuth::currentUser()</code> — <code>id</code>/<code>username</code>/<code>email</code>/<code>role</code>/<code>user_group</code>, or <code>null</code> — and pass what it needs into its template context.</li>
</ul>
{% endblock %}
@@ -4,49 +4,67 @@
{% block title %}Admin authentication{% endblock %}
{% block description %}Gating /admin/* behind HTTP Basic Auth, reusable for any future admin page.{% endblock %}
{% block description %}Session-based login with admin/registered roles, groups, and user management, gating /admin/* and draft pages.{% endblock %}
{% block robots %}noindex, nofollow{% endblock %}
{% block docs_content %}
<h1>Admin authentication</h1>
<p>Every route under <code>/admin/*</code> — <code>/admin</code>, <code>/admin/clear-cache</code>, the docs section, and any admin page a project adds later — can be gated behind HTTP Basic Auth with two <code>App/config.php</code> keys. It's off by default (same posture as Matomo): an empty <code>admin_password_hash</code> means no gate at all, matching this project's original wide-open behavior.</p>
<p>Every route under <code>/admin/*</code> — <code>/admin</code>, <code>/admin/clear-cache</code>, the docs section, and any admin page a project adds later — can be gated behind a session-based login against a <code>users</code> table in the <a class="icon-link" href="/admin/docs/database">{{ icons.book() }}database</a>'s <code>default</code> connection. It's off by default (same posture as the <a class="icon-link" href="/admin/docs/content-index">{{ icons.search() }}content index</a>, and for the same reason: it depends on SQLite, a real dependency plenty of sites won't want): with <code>admin_auth_enabled</code> left <code>false</code>, <code>/admin/*</code> is wide open, <code>/admin/login</code>, <code>/admin/logout</code>, and <code>/admin/users</code> all <code>404</code> as if they didn't exist, and nothing ever touches <code>Lib\Db</code> because of this feature — no <code>data/novaconium.sqlite</code> gets created just because the code exists.</p>
<p>This replaced the old <code>docs_enabled</code> config flag, which only hid the docs section specifically. Since this gate covers all of <code>/admin/*</code> — including docs — there's no need for a separate docs-only toggle anymore; set a password and the whole admin area (docs included) requires login.</p>
<p>This replaced the original single-user HTTP Basic Auth stopgap (an <code>admin_username</code>/<code>admin_password_hash</code> config pair — both keys, and the <code>/admin/password-hash</code> hash-generator page, are gone). Same call sites in <code>bootstrap.php</code>, new mechanism: multiple accounts, real server-side login state (riding on <a class="icon-link" href="/admin/docs/session">{{ icons.book() }}<code>Lib\Session</code></a>), and user management in the browser.</p>
<h2>Two roles: admin and registered</h2>
<p>The <strong>first user ever created is the admin</strong>; every user created after that is <strong>registered</strong>. An admin runs the site: full <code>/admin/*</code> access, sees <a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}draft pages</a>, and passes every <a class="icon-link" href="/admin/docs/access-control">{{ icons.lock() }}<code>Lib\Access</code></a> rule. A registered user can log in at the same <a href="/admin/login">/admin/login</a> and sees whatever content <code>Lib\Access</code> assigns to their account or their group — but <code>/admin/*</code> returns a plain <code>404</code> for them, not a login prompt (they <em>are</em> logged in; what they lack is the role). Each registered user can be assigned at most one <strong>group</strong> — a plain text label (e.g. <code>members</code>) that <code>Access::require('group:members')</code> matches exactly; there's no groups table to manage.</p>
<h2>Enabling it</h2>
<p>Generate a password hash once — either on the command line:</p>
<pre><code>php -r "echo password_hash('yourpassword', PASSWORD_DEFAULT), PHP_EOL;"</code></pre>
<p>...or, if you'd rather not touch a terminal, at <a class="icon-link" href="/admin/password-hash">{{ icons.lock() }}/admin/password-hash</a> — a small built-in form that does the same <code>password_hash()</code> call and hands back a ready-to-paste config snippet. Nothing typed there is stored or logged. Since it lives under <code>/admin/*</code> like everything else here, it's automatically covered by this same gate once a password is set — reachable while <code>admin_password_hash</code> is still empty (so you can generate your first one), then protected like any other admin page afterward.</p>
<p>Then set both keys in <code>App/config.php</code>:</p>
<p>Turn it on in <code>App/config.php</code>:</p>
<pre><code>&lt;?php
// App/config.php
return [
'admin_username' =&gt; 'admin',
'admin_password_hash' =&gt; '$2y$10$...',
'admin_auth_enabled' =&gt; true,
];</code></pre>
<p>Every request into <code>/admin/*</code> now requires that username/password via the browser's built-in Basic Auth prompt; anything outside <code>/admin</code> is unaffected.</p>
<p>Since this is the first SQLite-backed feature most sites turn on, make sure PHP has the <code>pdo_sqlite</code> extension enabled first (<code>php -m | grep -i sqlite</code>) — it's bundled with PHP but not always enabled; Debian/Ubuntu package it as <code>php-sqlite3</code>. Without it, the first request into <code>/admin/*</code> fails naming the missing extension. See <a href="/admin/docs">Overview</a>'s requirements list.</p>
<p>Enabling the flag alone protects nothing yet — <strong>while zero users exist, the whole admin area stays open</strong>, precisely so the first user (the admin) can be created. Do that either in the browser at <a href="/admin/users">/admin/users</a> (you're logged in as the first user automatically the moment it's created, and the gate closes), or from the command line:</p>
<pre><code>php novaconium/bin/create-admin-user.php admin admin@example.com</code></pre>
<p>The CLI reads the password from stdin (echo suppressed at an interactive prompt, and pipeable from a deploy script), and always creates an <em>admin</em> — it exists for first-user setup and lockout recovery, both of which need one; registered users are created at <code>/admin/users</code>. Running it <em>before</em> flipping <code>admin_auth_enabled</code> on is the safer order — the open setup window then never exists at all.</p>
<p>The <code>users</code> table ships as a framework migration (<code>novaconium/migrations/0002_create_users.sql</code>) and is created automatically the first time anything touches the <code>default</code> connection — no manual schema step. Passwords are stored as <code>password_hash()</code> hashes and checked with <code>password_verify()</code>; no plaintext, and nothing here ever selects the hash back out except to verify a login. Every account also has a <strong>unique email address</strong>, stored normalized (trimmed, lowercased, via <code>Lib\Validate::isEmail()</code>) — not used for login (that's the username) or for any mail yet, but required up front so the planned email-verification flow (see <code>novaconium/ISSUES.md</code>) has an address for every account that already exists by then.</p>
<h2>Managing users</h2>
<p><a href="/admin/users">/admin/users</a> lists every account and handles the rest: create a user (registered, with an email address and an optional group — only the very first is the admin), disable/enable one, assign or change a group, promote/demote between admin and registered, change an email address, change a password, and delete an account outright. Behaviors worth knowing:</p>
<ul>
<li><strong>Disabling is immediate.</strong> A disabled user can't log in, and any session they already had is re-checked against the table on its next request — there's no "still logged in until the session expires" window. The same immediate re-check applies to a role or group change.</li>
<li><strong>The last active admin can't be disabled, demoted, or deleted.</strong> Any of the three would lock everyone out of <code>/admin/*</code> permanently (the zero-users setup window doesn't reopen — the table isn't empty), leaving only the CLI or hand-editing the database as recovery. The form refuses instead. Registered users carry no such guard.</li>
<li><strong>Delete is a hard delete</strong> — the row is gone, the username and email become reusable, and any live session dies on its next request, same as disabling. Disable is the right tool for "shut this account out but keep it"; delete is for accounts that shouldn't exist at all.</li>
<li><strong>More admins are allowed</strong> — "first user is the admin" is the default, not a cap; promote a registered user any time.</li>
</ul>
<h2>How it's wired</h2>
<p><code>novaconium/src/AdminAuth.php</code> is a single reusable check — <code>AdminAuth::requireLogin($username, $passwordHash)</code> — called once from <code>novaconium/bootstrap.php</code> for any resolved route whose path is <code>admin</code> or starts with <code>admin/</code>, and only for routes that actually resolved (no login prompt on an unrelated 404). Because the check lives in <code>bootstrap.php</code> rather than on each page, <strong>a new admin page needs zero extra wiring</strong> to be protected — dropping a new directory under <code>App/pages/admin/</code> or <code>novaconium/pages/admin/</code> is automatically gated the moment it exists.</p>
<p><code>novaconium/src/AdminAuth.php</code> is a pair of reusable checks called once from <code>novaconium/bootstrap.php</code> for any resolved route whose path is <code>admin</code> or starts with <code>admin/</code>, and only for routes that actually resolved (no redirect on an unrelated 404): <code>AdminAuth::requireLogin($enabled)</code> redirects anyone not logged in to the login form, then <code>AdminAuth::isAdmin($enabled)</code> 404s anyone who <em>is</em> logged in but isn't an admin — a registered user is authenticated, so bouncing them back to the login form would be a lie. Because the checks live in <code>bootstrap.php</code> rather than on each page, <strong>a new admin page needs zero extra wiring</strong> to be protected — dropping a new directory under <code>App/pages/admin/</code> or <code>novaconium/pages/admin/</code> is automatically gated the moment it exists. The one exemption is <code>admin/login</code> itself, which has to stay reachable logged-out or the redirect to it would loop.</p>
<p>The credential check itself is a separate method, <code>AdminAuth::isAuthenticated($username, $passwordHash)</code> — <code>requireLogin()</code> is just that check plus the <code>401</code>-challenge response on failure. <a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}Draft pages</a> reuse <code>isAuthenticated()</code> directly with a different failure response (a plain <code>404</code>, not a login prompt), rather than duplicating the credential logic.</p>
<p>The login form is a normal page with a normal form: CSRF-protected like every other form here (see <a class="icon-link" href="/admin/docs/forms">{{ icons.email() }}Forms</a>), reading the username via <code>Lib\Input</code> and the password straight from <code>$_POST</code> (the documented exact-value exception — cleaning would strip characters like <code>&lt;</code>/<code>&gt;</code> and fail a login whose password actually matches). A successful login regenerates the session id (<code>Session::regenerate()</code>) before storing the user id, so a session id planted or observed pre-login never becomes an authenticated one — then lands on <code>?return=</code> (how <code>Lib\Access</code> sends someone back to the gated page they wanted; validated to be a local path, never another site), or, with no return path, on <code>/admin</code> for admins and the homepage for registered users.</p>
<p><a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}Draft pages</a> reuse <code>isAdmin()</code> directly with a different failure response (a plain <code>404</code> for <em>everyone</em> unauthorized, never a login redirect), rather than duplicating the logic. The session cookie is scoped to the whole origin, so logging in once at <code>/admin/login</code> covers draft URLs and <code>Lib\Access</code>-gated pages too.</p>
<p>Templates can read the <code>admin_auth_enabled</code> Twig global (it mirrors the config flag) — <code>admin/index.twig</code> uses it to show the "Admin users" and "Logout" links only when the feature is on. It's a display flag only; enforcement never depends on Twig.</p>
<h2>Logging out</h2>
<p>HTTP Basic Auth has no real server-side logout — the browser just keeps resending the same cached credentials on every request to that realm. Visiting <code>/admin/logout</code> works around this: <code>AdminAuth::logout()</code> always issues a fresh <code>401</code> challenge, regardless of what credentials were sent, which makes the browser discard what it had cached and prompt again the next time <code>/admin</code> is visited. Credentials themselves aren't invalidated server-side (there's nothing to invalidate — it's just a password check on every request), so this is a client-side-only logout, same as any Basic Auth site. The "Logout" link only appears on <code>/admin</code> when <code>admin_auth_enabled</code> is true (i.e. a password is actually set).</p>
<p><a href="/admin/logout">/admin/logout</a> is a real server-side logout now (its Basic Auth predecessor could only trick the browser into forgetting cached credentials with a fresh <code>401</code>): a POST — with a small GET confirm form, same shape as <code>/admin/clear-cache</code> — that drops the logged-in user id from the session, regenerates the session id, and redirects to the login form. It's deliberately not logout-on-GET: sidecars must stay side-effect-free on GET, both as ordinary HTTP hygiene and because the <a class="icon-link" href="/admin/docs/content-index">{{ icons.search() }}content index</a>'s crawl invokes every page's sidecar the way a real GET would — a logout-on-GET would end the crawling admin's own session the moment a lazy reindex rendered this page.</p>
<h2>What this is (and isn't)</h2>
<p>This is HTTP Basic Auth against a single username/password pair in config — no sessions, no user table, no password reset, no multiple accounts. It's a deliberate stopgap: see <code>novaconium/ISSUES.md</code>'s "Admin login &amp; user management" entry for the planned real multi-user system (backed by SQLite, with proper sessions). That feature will <em>replace</em> this mechanism, not layer on top of it. Until then, this is enough to keep the general public out of <code>/admin</code> on a production site.</p>
<p>Basic Auth credentials are sent base64-encoded on every request (not encrypted) — always serve <code>/admin</code> over HTTPS in production, same as any password-protected page.</p>
<p>This is authentication plus a deliberately small authorization model: two roles and one group label per user, matched by <a class="icon-link" href="/admin/docs/access-control">{{ icons.lock() }}<code>Lib\Access</code></a> rules in sidecars — no permissions matrix, no role hierarchy, no per-admin capability flags. Registration is admin-driven only; there's no self-serve sign-up form. Sessions are PHP's native ones via <code>Lib\Session</code>, with the same cookie hardening it always applies (<code>httponly</code>, <code>SameSite=Lax</code>, <code>secure</code> on HTTPS). As with any password form, serve <code>/admin</code> over HTTPS in production.</p>
{% endblock %}
@@ -13,13 +13,13 @@
<p>If a page has <strong>no</strong> sidecar, its rendered HTML is written to <code>public/cache/&lt;path&gt;/index.html</code> after the first request. <code>.htaccess</code> checks for that file before PHP ever runs, so repeat visits are served straight by Apache with zero PHP/Twig overhead. Pages with a sidecar are never cached this way, since their output can vary per request.</p>
<p>Two kinds of route are excluded from the cache unconditionally, regardless of whether they have a sidecar: every <a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}draft page</a> and every <code>/admin/*</code> route. Both are gated by <a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}HTTP Basic Auth</a>, and a cached copy would bypass that check entirely — <code>.htaccess</code> serves a cached file before PHP (and therefore any auth check) ever runs, so a cached admin or draft page would be served to anyone, unauthenticated, forever after the first authenticated view. See <a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}Draft pages</a> for the full write-up.</p>
<p>Two kinds of route are excluded from the cache unconditionally, regardless of whether they have a sidecar: every <a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}draft page</a> and every <code>/admin/*</code> route. Both are gated by the <a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}admin login</a>, and a cached copy would bypass that check entirely — <code>.htaccess</code> serves a cached file before PHP (and therefore any auth check) ever runs, so a cached admin or draft page would be served to anyone, unauthenticated, forever after the first authenticated view. See <a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}Draft pages</a> for the full write-up.</p>
<p>To force a single page to re-render, delete its file under <code>public/cache/</code>. To clear everything at once, there are two equivalent options:</p>
<ul>
<li><strong>CLI:</strong> <code>php novaconium/bin/clear-cache.php</code> — a standalone script for deploys, cron jobs, or anywhere you'd rather not go through a browser. Prints <code>Cache cleared.</code> and exits.</li>
<li><strong>Web:</strong> <a href="/admin/clear-cache">/admin/clear-cache</a> — a POST form under <code>/admin</code>, covered by the same <a href="/admin/docs/admin-auth">HTTP Basic Auth gate</a> as the rest of <code>/admin/*</code> once a password is set.</li>
<li><strong>Web:</strong> <a href="/admin/clear-cache">/admin/clear-cache</a> — a POST form under <code>/admin</code>, covered by the same <a href="/admin/docs/admin-auth">admin login gate</a> as the rest of <code>/admin/*</code> once admin auth is enabled.</li>
</ul>
<p>Both end up calling the same underlying <code>Cache::clear()</code> — see <code>/admin/docs/config</code>'s "For developers: using <code>Cache.php</code> directly" section for how each entry point constructs it. Clearing the cache only deletes the generated static HTML; it doesn't affect <code>App/pages/</code> or any other source. Any project change that should show up on an already-cached page — a new <code>site_name</code>, a new Sass color, a new admin toggle — needs a cache clear before it's visible, since the old <code>index.html</code> would otherwise keep being served as-is.</p>
@@ -9,7 +9,7 @@
{% block docs_content %}
<h1>Configuration</h1>
<p><code>novaconium/config.php</code> holds the framework defaults — <code>pages_dirs</code>, <code>cache_dir</code>, <code>debug</code>, <code>site_name</code>, <code>matomo_url</code>, <code>matomo_site_id</code>, <code>admin_username</code>, <code>admin_password_hash</code>, <code>db_connections</code>, <code>draft_routes</code> — and is not meant to be edited per-project, same as everything else under <code>novaconium/</code>.</p>
<p><code>novaconium/config.php</code> holds the framework defaults — <code>pages_dirs</code>, <code>cache_dir</code>, <code>debug</code>, <code>site_name</code>, <code>matomo_url</code>, <code>matomo_site_id</code>, <code>admin_auth_enabled</code>, <code>db_connections</code>, <code>draft_routes</code> — and is not meant to be edited per-project, same as everything else under <code>novaconium/</code>.</p>
<p><code>App/config.php</code> ships with the skeleton as an empty, commented placeholder — uncomment (or add) whichever keys you want to change, returning an array of just those:</p>
@@ -37,11 +37,11 @@ return [
<h2>Admin authentication</h2>
<p><code>admin_username</code> / <code>admin_password_hash</code> gate every <code>/admin/*</code> route behind HTTP Basic Auth — see <a href="/admin/docs/admin-auth">Admin authentication</a> for the full write-up. Both are set via <code>App/config.php</code>; leaving <code>admin_password_hash</code> empty (the default) disables the gate.</p>
<p><code>admin_auth_enabled</code> (default <code>false</code>) gates every <code>/admin/*</code> route behind a session login against the <code>users</code> table — see <a href="/admin/docs/admin-auth">Admin authentication</a> for the full write-up, including roles (the first user is the admin; the rest are registered) and how the first user gets created. The same flag powers <a href="/admin/docs/access-control">Access control</a> (<code>Lib\Access</code>) for member/group-gated content. When left off, <code>/admin/*</code> is open, the login/users routes <code>404</code>, and <code>Access::require()</code> allows everything.</p>
<h2>Draft pages</h2>
<p><code>draft_routes</code> (default <code>[]</code>) is a list of routes only an authenticated admin can see — everyone else gets a plain <code>404</code>. Requires <code>admin_password_hash</code> above to be set to actually gate anything. See <a href="/admin/docs/drafts">Draft pages</a> for the full write-up, including why a cached draft page would be a security problem and how that's avoided.</p>
<p><code>draft_routes</code> (default <code>[]</code>) is a list of routes only an authenticated admin can see — everyone else gets a plain <code>404</code>. Requires <code>admin_auth_enabled</code> above (and at least one user) to actually gate anything. See <a href="/admin/docs/drafts">Draft pages</a> for the full write-up, including why a cached draft page would be a security problem and how that's avoided.</p>
<h2>For developers: using <code>Cache.php</code> directly</h2>
@@ -16,18 +16,17 @@
<pre><code>&lt;?php
// App/config.php
return [
'admin_username' =&gt; 'admin',
'admin_password_hash' =&gt; '$2y$10$...',
'draft_routes' =&gt; ['blog/upcoming-post'],
'admin_auth_enabled' =&gt; true,
'draft_routes' =&gt; ['blog/upcoming-post'],
];</code></pre>
<p>Each entry matches the same path format <a class="icon-link" href="/admin/docs/routing">{{ icons.link() }}Routing</a> resolves internally — no leading slash, directory segments joined with <code>/</code> (e.g. <code>App/pages/blog/upcoming-post/</code> is listed as <code>'blog/upcoming-post'</code>).</p>
<h2>Not a login prompt</h2>
<p>An unauthenticated visitor to a draft route gets the site's normal 404 page — not a <code>401</code> Basic Auth challenge like <code>/admin/*</code> gives. This is deliberate: prompting for a login would itself reveal that something is gated at that URL. A draft is indistinguishable from a URL that was never routable in the first place.</p>
<p>An unauthenticated visitor to a draft route gets the site's normal 404 page — not a redirect to the login form like <code>/admin/*</code> gives. This is deliberate: bouncing to a login would itself reveal that something is gated at that URL. A draft is indistinguishable from a URL that was never routable in the first place.</p>
<p>There's no separate login flow for drafts, and none is needed — <code>AdminAuth::isAuthenticated()</code> (the same credential check <a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}Admin authentication</a>'s <code>requireLogin()</code> uses) is reused directly. In practice, an admin authenticates once by visiting <code>/admin</code> and entering credentials there; HTTP Basic Auth credentials are scoped to the whole origin/realm, not a single path, so the browser then resends those same credentials automatically on later requests to a draft URL too, without a second prompt.</p>
<p>There's no separate login flow for drafts, and none is needed — <code>AdminAuth::isAdmin()</code> (the same check <a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}Admin authentication</a>'s admin gate uses) is reused directly, so drafts are admin-only: a logged-in <em>registered</em> user gets the same 404 as everyone else (previewing unpublished work is a site-running privilege, not a membership perk — use <a class="icon-link" href="/admin/docs/access-control">{{ icons.lock() }}<code>Lib\Access</code></a> for members-only content). In practice, an admin logs in once at <code>/admin/login</code>; the session cookie is scoped to the whole origin, not a single path, so it covers later requests to a draft URL too. With <code>admin_auth_enabled</code> left off (or while no users exist yet), drafts are open to everyone, consistent with the rest of <code>/admin/*</code>.</p>
<h2>The caching interaction</h2>
@@ -9,7 +9,7 @@
{% block docs_content %}
<h1>Getting started</h1>
<p><strong>Requirements:</strong> PHP 8.1+ (uses <code>readonly</code> constructor-promoted properties) and, for production, Apache with <code>mod_rewrite</code> and <code>AllowOverride All</code>. The <a href="/admin/docs/database">Database</a>/<a href="/admin/docs/content-index">Content index</a> features are optional and off by default — see <a href="/admin/docs">Overview</a> for the extensions they need (<code>pdo_sqlite</code>, optionally <code>pdo_mysql</code>/FTS5) if you turn them on.</p>
<p><strong>Requirements:</strong> PHP 8.1+ (uses <code>readonly</code> constructor-promoted properties) and, for production, Apache with <code>mod_rewrite</code> and <code>AllowOverride All</code>. The <a href="/admin/docs/database">Database</a>/<a href="/admin/docs/content-index">Content index</a>/<a href="/admin/docs/admin-auth">Admin authentication</a> features are optional and off by default — see <a href="/admin/docs">Overview</a> for the extensions they need (<code>pdo_sqlite</code>, optionally <code>pdo_mysql</code>/FTS5) if you turn them on.</p>
<h2>Run it locally (no Apache needed)</h2>
+2 -1
View File
@@ -38,7 +38,8 @@
<li><a class="icon-link" href="/admin/docs/content-index">{{ icons.search() }}Content index</a> — the shared crawler behind <code>/sitemap.xml</code>, <code>/search</code>, and blog tag browsing. Off by default.</li>
<li><a class="icon-link" href="/admin/docs/sitemap">{{ icons.sitemap() }}XML sitemap</a> — per-page <code>changefreq</code>/<code>priority</code>, what's included, and submitting it to search engines.</li>
<li><a class="icon-link" href="/admin/docs/rss">{{ icons.rss() }}RSS feeds</a> — <code>Lib\Rss</code>, building one feed or several for any content collection.</li>
<li><a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}Admin authentication</a> — gate <code>/admin/*</code> behind HTTP Basic Auth, reusable for any future admin page.</li>
<li><a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}Admin authentication</a> — gate <code>/admin/*</code> behind a session login, with admin/registered roles, groups, and user management.</li>
<li><a class="icon-link" href="/admin/docs/access-control">{{ icons.lock() }}Access control</a> — assign a page or section to a user or group from its sidecar with <code>Lib\Access</code>; public by default, static pages always public.</li>
<li><a class="icon-link" href="/admin/docs/drafts">{{ icons.lock() }}Draft pages</a> — let an admin preview a page before the public can see it, reusing the same auth check.</li>
<li><a class="icon-link" href="/admin/docs/layouts">{{ icons.book() }}Layouts</a> — pages and layouts are overridable, just like <code>Lib\</code>.</li>
<li><a class="icon-link" href="/admin/docs/caching">{{ icons.book() }}Static caching</a> — how sidecar-less pages get served as static HTML.</li>
@@ -26,5 +26,9 @@
<li><code>Lib\Validate</code> — the lower-level validation primitives <code>FormValidator</code> calls into (<code>isEmail()</code>, <code>minLength()</code>/<code>maxLength()</code>, <code>isMatch()</code>, <code>isPhone()</code>, <code>isPostalCode()</code>/<code>isZipCode()</code>) — call these directly from a sidecar when you just need a validated/normalized value back rather than an accumulated field-error. See <a href="/admin/docs/sidecars">Sidecars</a>' "Spam prevention" section.</li>
<li><code>Lib\Input</code> — a cleaning accessor for <code>$_POST</code>/<code>$_GET</code> (<code>Input::post()</code>/<code>Input::get()</code>), used by every sidecar instead of the superglobals directly. Defense-in-depth against HTML/script injection, <strong>not</strong> a defense against SQL injection — see <a href="/admin/docs/sidecars">Sidecars</a>' "Form security" section for the full caveat.</li>
<li><code>Lib\Csrf</code> — standalone session-token CSRF protection (<code>Csrf::token()</code>/<code>::verify()</code>), called directly from a sidecar rather than through <code>FormValidator</code>. See <a href="/admin/docs/sidecars">Sidecars</a>' "Form security" section.</li>
<li><code>Lib\Db</code> — the thin no-ORM PDO wrapper behind everything database-backed here. See <a href="/admin/docs/database">Database</a>.</li>
<li><code>Lib\Session</code> — native PHP sessions with a consistent get/set/flash API. See <a href="/admin/docs/session">Session</a>.</li>
<li><code>Lib\Access</code> — sidecar-level access control: assign a page to a user or group (<code>Access::require('group:members')</code>). See <a href="/admin/docs/access-control">Access control</a>.</li>
<li><code>Lib\Rss</code> — a generic RSS 2.0 envelope builder. See <a href="/admin/docs/rss">RSS feeds</a>.</li>
</ul>
{% endblock %}
@@ -44,9 +44,8 @@ novaconium/ the framework itself — boilerplate, not meant to be edite
<ol>
<li>Requires <strong><code>novaconium/autoload.php</code></strong>, registering the <code>Twig\</code>/<code>App\</code>/<code>Lib\</code> class autoloader (see <a href="/admin/docs/libraries">Libraries</a>) before anything below tries to instantiate a class.</li>
<li>Requires <strong><code>novaconium/config.php</code></strong>, then shallow-merges <strong><code>App/config.php</code></strong> over it if that file exists — see <a href="/admin/docs/config">Configuration</a>.</li>
<li>Special-cases <code>/admin/logout</code> directly against the request path — see <a href="/admin/docs/admin-auth">Admin authentication</a> — since it isn't a real page for the router to find.</li>
<li>Constructs a <strong><code>Router</code></strong> (<code>novaconium/src/Router.php</code>) and calls <code>resolve()</code> to turn the URL into a <strong><code>Route</code></strong> (<code>novaconium/src/Route.php</code>) — see <a href="/admin/docs/routing">Routing</a>.</li>
<li>If the resolved route is under <code>admin</code>/<code>admin/*</code>, calls <strong><code>AdminAuth::requireLogin()</code></strong> (<code>novaconium/src/AdminAuth.php</code>), reading that same <code>Route</code>.</li>
<li>If the resolved route is under <code>admin</code>/<code>admin/*</code> (except <code>admin/login</code> itself), calls <strong><code>AdminAuth::requireLogin()</code></strong> (<code>novaconium/src/AdminAuth.php</code>), reading that same <code>Route</code>.</li>
<li>Constructs a <strong><code>Cache</code></strong> (<code>novaconium/src/Cache.php</code>) and a <strong><code>Renderer</code></strong> (<code>novaconium/src/Renderer.php</code>), then calls <code>renderNotFound()</code> or <code>render($route, ...)</code> depending on <code>$route-&gt;found</code> — see <a href="/admin/docs/sidecars">Sidecars</a> for what happens inside <code>Renderer</code> itself (running the matched directory's <code>index.php</code>, if any; resolving the nearest layout; rendering <code>index.twig</code>; writing the static cache for sidecar-less pages).</li>
</ol>
</li>
@@ -37,9 +37,8 @@
<ol>
<li>Config loads (framework defaults + optional <code>App/config.php</code> override).</li>
<li><code>/admin/logout</code> is special-cased directly against the raw request path, before routing even runs — it isn't a real page, so there'd be no <code>Route</code> for it anyway.</li>
<li><strong><code>Router::resolve()</code> runs</strong> and returns a <code>Route</code> — this is the only place a <code>Route</code> gets created.</li>
<li>If <code>$route-&gt;dir</code> is under <code>admin</code>/<code>admin/*</code>, <code>AdminAuth::requireLogin()</code> gates it — reading <code>$route-&gt;dir</code> directly off the value object <code>Router</code> handed back.</li>
<li>If <code>$route-&gt;dir</code> is under <code>admin</code>/<code>admin/*</code> (except <code>admin/login</code>, which must stay reachable logged-out), <code>AdminAuth::requireLogin()</code> gates it — reading <code>$route-&gt;dir</code> directly off the value object <code>Router</code> handed back.</li>
<li><code>Renderer</code> takes over, also just reading the same <code>Route</code>: <code>renderNotFound()</code> if <code>$route-&gt;found</code> is <code>false</code>, otherwise <code>render($route, ...)</code> — using <code>$route-&gt;dir</code> to find the sidecar/layout/template and <code>$route-&gt;params</code> as template context.</li>
</ol>
@@ -24,6 +24,8 @@ Session::remove('user_id');</code></pre>
<p>The session is started lazily — nothing calls <code>session_start()</code> until the first real call to any <code>Session</code> method, so a page that never touches <code>Session</code> never gets a session cookie. <a class="icon-link" href="/admin/docs/libraries">{{ icons.book() }}Lib\Csrf</a> uses the exact same lazy-start mechanism to run its own session-token CSRF protection — both classes can touch the same native session in the same request without conflict, since <code>session_start()</code> is only ever actually called once (PHP no-ops a second call).</p>
<p><code>Session::regenerate()</code> swaps the session id for a fresh one while keeping the session's data — call it on any privilege change, so a session id an attacker planted or observed before the change is worthless after it (session fixation). <a class="icon-link" href="/admin/docs/admin-auth">{{ icons.lock() }}Admin authentication</a> does exactly this on login and logout.</p>
<h2>Flash data</h2>
<p>A flashed value is readable on exactly the next request, then gone — useful for post/redirect/GET flows (a "message sent" banner after a redirect) without a query-string flag like <code>?sent=1</code>:</p>
@@ -65,7 +65,9 @@ $all = Input::post(); // the whole cleaned $_POST array</code><
<p><strong>This is not SQL-injection protection.</strong> The cleaning <code>Input</code> does (trim + strip tags, via <code>Lib\Validate::clean()</code>, plus null-byte stripping) is defense-in-depth against HTML/script injection in output contexts — Twig already autoescapes <code>{{ '{{ }}' }}</code> output by default (see <code>novaconium/src/Renderer.php</code>), so this is a second layer, not the only one. No string transform makes arbitrary input safe to concatenate into a SQL query; the real defense is parameterized queries. <a href="/admin/docs/database">Lib\Db</a>'s <code>query()</code> method uses PDO prepared statements exclusively for exactly this reason. <code>Input</code> deliberately has no <code>sqlSafe()</code>-style method, since a method implying "cleaned = safe to interpolate into SQL" would be actively dangerous.</p>
<p>One documented exception: a field that needs an exact, unmodified value — a password about to be hashed, say — should read <code>$_POST</code> directly instead of going through <code>Input::post()</code>. Cleaning would silently strip characters like <code>&lt;</code>/<code>&gt;</code> before hashing, producing a hash that doesn't match what's actually typed later. See <code>novaconium/pages/admin/password-hash/index.php</code> for the one place this framework does that on purpose.</p>
<p>One documented exception: a field that needs an exact, unmodified value — a password about to be hashed or verified, say — should read <code>$_POST</code> directly instead of going through <code>Input::post()</code>. Cleaning would silently strip characters like <code>&lt;</code>/<code>&gt;</code> before hashing, producing a hash that doesn't match what's actually typed later (or failing a login whose password actually matches). See the password fields in <code>novaconium/pages/admin/users/index.php</code> and <code>novaconium/pages/admin/login/index.php</code> for the places this framework does that on purpose.</p>
<p>A sidecar is also where a page gets assigned to a user or group: one <code>Lib\Access</code> call at the top, returning its <code>Response</code> when access is denied — see <a href="/admin/docs/access-control">Access control</a>.</p>
<h3>CSRF protection</h3>
@@ -140,7 +142,7 @@ $phone = Validate::isPhone($old['phone']); // '5551234567' or false</code></pr
<p>All three classes live under <code>novaconium/lib/</code> as framework defaults — like any other <code>Lib\</code> class, a project can override any of them by dropping a same-named file in <code>App/lib/</code> (see <a href="/admin/docs/libraries">Libraries</a>).</p>
<h2>Copy-paste starter: a sidecar, three ways</h2>
<h2>Copy-paste starter: a sidecar, four ways</h2>
<p>Drop this in as <code>App/pages/example/index.php</code> (next to an <code>App/pages/example/index.twig</code> using the <a href="/admin/docs/seo">SEO starter template</a>) and delete whichever example you don't need:</p>
@@ -166,9 +168,26 @@ return [
//
// ob_start();
// phpinfo();
// return Response::html(ob_get_clean());{% endverbatim %}</code></pre>
// return Response::html(ob_get_clean());
<p>Only one of the three <code>return</code>s in a real sidecar ever runs, obviously — pick one, or branch between them with an <code>if</code>. The IP example works with or without a sidecar-only page (no <code>index.twig</code>); the <code>phpinfo()</code> example needs <em>no</em> <code>index.twig</code> at all, since <code>Response::html()</code> bypasses Twig — see the JSON-only example above for another sidecar-only page.</p>
// 4. Require a login — gate the page to a group, a user, or any
// logged-in account before doing anything else. Access::require()
// returns null when the visitor may proceed, or a ready-made Response
// (a login redirect that comes back here afterwards, or a 404 for the
// wrong account) for you to return as-is. Needs admin_auth_enabled and
// at least one user — see /admin/docs/access-control for the rules and
// /admin/docs/admin-auth for accounts and groups.
// use Lib\Access;
//
// if ($denied = Access::require('group:members')) {
// return $denied;
// }
//
// return [
// 'message' => 'Hello, member!',
// ];{% endverbatim %}</code></pre>
<p>Only one of the numbered <code>return</code>s in a real sidecar ever runs, obviously — pick one, or branch between them with an <code>if</code>. The IP example works with or without a sidecar-only page (no <code>index.twig</code>); the <code>phpinfo()</code> example needs <em>no</em> <code>index.twig</code> at all, since <code>Response::html()</code> bypasses Twig — see the JSON-only example above for another sidecar-only page. The login gate in example 4 isn't really an alternative to the other three — it's a first line that composes with any of them: gate first, then return whatever the page normally would. Swap the rule for <code>Access::require('user:bob')</code>, several rules (any one grants access), or no rules at all for "anyone logged in"; admins always pass.</p>
<p><strong>Never ship <code>phpinfo()</code> to production</strong> — it dumps environment variables, file paths, loaded extensions, and configuration values that are useful to an attacker mapping your server. Delete the page after you're done with it, or at minimum gate it behind <a href="/admin/docs/admin-auth">admin authentication</a> the same way <code>/admin/*</code> already is, so it's never reachable by the public.</p>