From ea9cfc9f6a2f09deb193850b84399f2bd72680b2 Mon Sep 17 00:00:00 2001 From: Peterino Date: Wed, 25 Nov 2026 13:37:53 -0700 Subject: [PATCH] Add agent notes and initial design documents lore-forge is a Rust web server that runs beside Epic's Lore version control server and provides accounts, sign-in through GitHub, Discord and Google, the tokens Lore verifies, per-repository permissions and a self-hosted forge UI. AGENTS.md describes the project and its conventions. The documents under .ai/designs record the architecture agreed so far: how lore-forge integrates with Lore, the account and sign-in model, the token issuer, namespaces and access control, the server-rendered web UI, forge features and SQLite storage. No code yet; this is design only. --- .ai/designs/accounts-and-sign-in.md | 141 ++++++++++++++++++++++ .ai/designs/architecture-overview.md | 123 +++++++++++++++++++ .ai/designs/forge-features.md | 113 +++++++++++++++++ .ai/designs/lore-integration.md | 174 +++++++++++++++++++++++++++ .ai/designs/namespaces-and-access.md | 132 ++++++++++++++++++++ .ai/designs/storage.md | 113 +++++++++++++++++ .ai/designs/token-issuer.md | 144 ++++++++++++++++++++++ .ai/designs/web-ui.md | 96 +++++++++++++++ AGENTS.md | 51 ++++++++ 9 files changed, 1087 insertions(+) create mode 100644 .ai/designs/accounts-and-sign-in.md create mode 100644 .ai/designs/architecture-overview.md create mode 100644 .ai/designs/forge-features.md create mode 100644 .ai/designs/lore-integration.md create mode 100644 .ai/designs/namespaces-and-access.md create mode 100644 .ai/designs/storage.md create mode 100644 .ai/designs/token-issuer.md create mode 100644 .ai/designs/web-ui.md create mode 100644 AGENTS.md diff --git a/.ai/designs/accounts-and-sign-in.md b/.ai/designs/accounts-and-sign-in.md new file mode 100644 index 0000000..391beb4 --- /dev/null +++ b/.ai/designs/accounts-and-sign-in.md @@ -0,0 +1,141 @@ +# Accounts and sign-in + +Status: design, nothing built. Last updated 2026-11-25. + +The account system follows **piki**, the owner's Go project (`../piki`). Piki's +`agents/data-auth-services.md` maps its auth code; the schema is in +`internal/db/migrations/` (`013_oauth.sql`, `016_google_sso_sessions.sql`). Where this document +says "as in piki", that is the behaviour to match. + +## Principles + +- **The lore-forge account is the identity.** GitHub, Discord and Google are ways to sign in + to an existing account, not sources of identity. +- **No second factor is required.** The "2FA" in the original brief meant sign-in through + those providers. +- **`loreserver` never sees credentials.** It trusts tokens that lore-forge signs. + +## Getting an account + +As in piki: + +- **First run:** `/setup` creates the instance owner with a username and password. It is only + available while no user exists. +- **Signup toggle:** the owner turns public signup on or off. +- **Invite keys:** the owner can require an invite key for signup. A key has a name, a maximum + number of uses and an active flag, and records who used it. Signup with a key uses a path of + the form `/signup/`. + +## Signing in + +Three methods, all ending in the same kind of session: + +1. **Username and password.** +2. **A linked provider:** GitHub, Discord or Google. +3. **A passkey** (optional, registered from the profile). + +### Provider sign-in + +As in piki: + +- **Existing accounts only.** A provider can sign a person in only after they linked it from + their profile while signed in. +- **Explicit linking, never by email.** A link is keyed by `(provider, subject id)`. Sign-ins + are never matched to accounts by email address or username. This prevents takeover through a + provider account that merely shares an email. +- **One link per provider per account.** +- **Provider tokens are not kept.** They are used once to read the identity, then revoked + (GitHub, Discord) or discarded (Google). +- **Flows are single-use.** Each sign-in or link attempt is a row with a hashed state value, an + intent (`signin` or `link`), a PKCE verifier, a nonce where the provider supports it, and an + expiry. +- **Start is a CSRF-protected POST** from the login form, so the "stay signed in" choice + travels with the flow. + +Protocol notes: + +- GitHub and Discord are plain OAuth 2.0 authorization-code flows followed by an identity + request. +- Google is OpenID Connect with PKCE and a per-flow nonce; identity comes from the ID token. + +### Provider configuration + +As in piki: + +- The owner enters each provider's client ID and secret in the settings UI and enables it. +- The settings page shows the exact callback URL to register with the provider. +- Secrets are stored encrypted (AES-GCM) with a 32-byte key supplied through the environment. + The same key protects lore-forge's token signing keys (see [token-issuer.md](token-issuer.md)). +- The owner sets the instance's canonical public URL. Callback URLs, passkey configuration and + the issuer URL derive from it, never from request headers. + +### Passkeys + +As in piki: optional, registered from the profile while signed in, usernameless sign-in with +user verification, only the public key stored. They are an additional sign-in method, not a +required second step. + +## Sessions + +As in piki: + +- A session token is random; only its hash is stored. +- Cookies are `HttpOnly`, `Secure` in production and `SameSite=Lax`. Unsafe methods require a + CSRF token. +- "Stay signed in" keeps a session for 30 days after last use, up to 90 days in total. +- Each session records how it was created (password, provider, passkey) and its user agent. +- Users see their active sessions in their profile and can revoke one or all others. + +### What lore-forge adds + +Lore CLI logins appear in the same list. Each `lore auth login` produces a refresh token; it +is listed beside browser sessions with its creation time and last use, and revoking it ends +that CLI login. See [token-issuer.md](token-issuer.md). + +## Device approval + +`lore auth login` opens the browser on a lore-forge page carrying a short code. + +- If the person is not signed in, they sign in by any method above. +- They then see which device is asking and approve or deny. +- If already signed in, approval is one click. + +This page is part of the web UI and uses the ordinary browser session. + +## Instance roles + +Separate from repository permissions: + +| Role | Can | +| --- | --- | +| Owner | Everything, including provider configuration and instance settings | +| Admin | Manage users, invites and organisations | +| Member | Use the instance according to their grants | + +Repository and organisation permissions are in +[namespaces-and-access.md](namespaces-and-access.md). + +## API tokens + +As in piki, a user can create named API tokens, stored hashed, with scopes and optional +expiry. In lore-forge they serve two purposes: + +- authenticating to lore-forge's JSON API; +- logging the Lore CLI in without a browser, for CI. Lore defines API-key login as a token + exchange with the subject token type `urn:lore:params:oauth:token-type:api-key`. + +## Identity recorded by Lore + +Lore writes the caller's identity into revision history permanently. + +**Recommended, not yet confirmed:** put a stable internal user ID in the token, not the +username, and have lore-forge answer Lore's name lookup service. Usernames can then change +without rewriting history, and the CLI still shows names. The alternative is to use the +username directly, which is simpler but makes usernames effectively permanent. + +## Open questions + +- Whether an invite may be redeemed directly with a provider, creating an account that never + has a password. Piki does not allow this; the design currently matches piki. +- Whether usernames can be changed, which depends on the identity decision above and on + namespace renames (see [namespaces-and-access.md](namespaces-and-access.md)). diff --git a/.ai/designs/architecture-overview.md b/.ai/designs/architecture-overview.md new file mode 100644 index 0000000..bc6f029 --- /dev/null +++ b/.ai/designs/architecture-overview.md @@ -0,0 +1,123 @@ +# Architecture overview + +Status: design, nothing built. Last updated 2026-11-25. + +## What lore-forge is + +A single Rust binary that runs beside an unmodified Lore server (`loreserver`) and provides +what Lore deliberately leaves out: + +- accounts and sign-in, including GitHub, Discord and Google; +- the tokens `loreserver` verifies, scoped per repository; +- user and organisation namespaces, teams and permissions; +- a web forge: repository browsing, change requests, review-gated landing, activity. + +lore-forge is **not** a proxy. Repository data flows directly between Lore clients and +`loreserver`. lore-forge handles login, tokens, permissions and the web UI. + +## Why this shape + +Lore's server has no user database and no login. It verifies JWTs issued by an external OIDC +issuer and reads permissions from token claims. Any off-the-shelf provider can supply global +roles, but Lore's own survey found no open-source provider able to issue the per-repository +tokens its finer-grained mode needs, and the sample service Lore ships for that is marked as +not for production. lore-forge fills that gap by being the issuer. See +[lore-integration.md](lore-integration.md). + +## Block diagram + +``` +┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────────────┐ +│ Lore CLI │ │ Browser │ │ CI jobs │ │ Sign-in providers │ +│ │ │ │ │ │ │ GitHub, Discord, Google │ +└─┬──────┬─┘ └────┬─────┘ └────┬─────┘ └────────────┬─────────────┘ + │ │ login, │ web UI │ API tokens │ OAuth redirects + │ │ tokens │ │ │ + │ ┌──▼─────────▼─────────────▼─────────────────────▼─────────────┐ + │ │ lore-forge (one Rust binary, one data directory) │ + │ │ ┌──────────────────────────────────────────────────────────┐ │ + │ │ │ Web layer: server-rendered UI, JSON API │ │ + │ │ └──────────────────────────────────────────────────────────┘ │ + │ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────────┐ │ + │ │ │ Accounts │ │ Token issuer │ │ Access │ │ + │ │ │ sign-in, │ │ signs Lore │ │ orgs, teams, │ │ + │ │ │ invites │ │ tokens │ │ role presets │ │ + │ │ └────────────────┘ └────────────────┘ └────────────────────┘ │ + │ │ ┌────────────────┐ ┌────────────────┐ ┌────────────────────┐ │ + │ │ │ Repo browser │ │ Change │ │ Activity │ │ + │ │ │ trees, diffs, │ │ requests, │ │ events, webhooks │ │ + │ │ │ locks │ │ landing │ │ │ │ + │ │ └────────────────┘ └────────────────┘ └────────────────────┘ │ + │ │ ┌───────────────────────────┐ ┌────────────────────────────┐ │ + │ │ │ Lore client │ │ SQLite │ │ + │ │ │ gRPC as the signed-in user│ │ data, signing keys, cache │ │ + │ │ └─────────────┬─────────────┘ └────────────────────────────┘ │ + │ └───────────────┼──────────────────────────────────────────────┘ + │ repository data │ browse, land, subscribe ▲ keys, registry, + │ (QUIC / gRPC) │ │ name lookup +┌─▼───────────────────▼──────────────────────────────┴───────────────┐ +│ loreserver: unmodified Lore server. Verifies tokens locally and │ +│ stores all repository data. Hosts every namespace's repositories. │ +└────────────────────────────────────────────────────────────────────┘ +``` + +`loreserver` calls back into lore-forge for three things: signing keys at startup, approval of +repository creates and deletes, and user name lookups. + +## Modules + +One cargo workspace, built as a modular monolith. Crate names are provisional. + +| Crate | Responsibility | Design document | +| --- | --- | --- | +| `forge-id` | Accounts, sessions, provider linking, the token issuer | [accounts-and-sign-in.md](accounts-and-sign-in.md), [token-issuer.md](token-issuer.md) | +| `forge-access` | Namespaces, orgs, teams, grants, role presets, the Lore registry service | [namespaces-and-access.md](namespaces-and-access.md) | +| `forge-lore` | Typed client for `loreserver` (gRPC and HTTP), minting on-behalf tokens. The only crate that depends on Lore's protocol definitions | [lore-integration.md](lore-integration.md) | +| `forge-core` | Change requests, reviews, comments, landing | [forge-features.md](forge-features.md) | +| `forge-events` | Lore notification subscriber: activity feed, webhooks | [forge-features.md](forge-features.md) | +| `forge-web` | HTTP server, templates, JSON API | [web-ui.md](web-ui.md) | +| `forge-store` | SQLite access and migrations | [storage.md](storage.md) | + +There is no separate worker process. Landing a change is a single call to `loreserver`, so +background work runs as tasks inside the one binary. + +## Decisions + +| Topic | Decision | Source | +| --- | --- | --- | +| Relationship to Lore | Issuer and forge beside `loreserver`, not a proxy in front of it | Follows from Lore's design | +| Scope | Full forge, built in phases with identity first | Owner | +| UI | Server-rendered from the Rust binary | Owner | +| Second factor | None required. "2FA" in the original brief meant sign-in through GitHub, Discord or Google | Owner | +| Account model | Follow piki: local accounts, signup toggle, invite keys, explicit provider linking | Owner | +| Database | SQLite | Owner | +| Repository layout | GitHub-style user and organisation namespaces | Owner | +| Permission UI | Role presets, with an advanced per-action view | Owner | +| Landing | Per-branch choice between review-gated and direct push | Owner | +| Permission source | Grants managed in lore-forge, optional mapping from GitHub teams and Discord roles later | Recommended; owner had no preference | +| Deployment | `loreserver` as a separate process; lore-forge generates its auth config | Recommended; owner had no preference | +| Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference | +| Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed | +| Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Recommended, not explicitly confirmed | +| Who may create orgs | An owner setting, defaulting to instance admins only | Defaulted, not confirmed | + +## Phases + +1. **Identity.** `lore auth login` works end to end: accounts, provider sign-in, the issuer, + namespaces, grants, per-repository tokens. Everything else depends on this. +2. **Read-only forge.** Repository list, file browser, history, diffs, locks, activity feed. +3. **Collaboration.** Branch-based change requests, reviews, comments, gated landing. +4. **Integrations.** Webhooks, Discord notifications, CI status checks, API tokens for CI. +5. **Game-development specifics.** Asset previews (textures, `.uasset` thumbnails), lock + management. + +## Things to keep in mind + +- **Epic plans its own web client.** Lore's roadmap lists an open-source web client with code + review tools as committed for 2027. lore-forge overlaps with it. The parts Epic is least + likely to cover are the identity layer, GitHub and Discord integration, and single-binary + self-hosting. +- **Lore is pre-1.0.** Its APIs and protocols can change between releases. All contact with + Lore is confined to one crate for that reason. +- **The issuer is the most sensitive component.** Whoever holds its signing keys can mint + access to every repository. See the security section of [web-ui.md](web-ui.md). diff --git a/.ai/designs/forge-features.md b/.ai/designs/forge-features.md new file mode 100644 index 0000000..3ee0e05 --- /dev/null +++ b/.ai/designs/forge-features.md @@ -0,0 +1,113 @@ +# Forge features + +Status: design, nothing built. Last updated 2026-11-25. + +These are phases 2 to 5 and are designed in less detail than identity. Each section says what +Lore provides for it; see [lore-integration.md](lore-integration.md) for what was verified. + +## Repository browser (phase 2) + +- **Repository list** per owner, and a dashboard of the repositories a user can reach. +- **File browser:** directory listings and file views at any branch or revision. +- **History:** revisions on a branch, with author names resolved by lore-forge. +- **Diffs:** between two revisions, and per file. +- **Downloads** through presigned URLs. + +Backed by Lore's read-only `ThinClientService` (`RevisionTree`, `RevisionInfo`, +`RevisionDiff`, `ContentDiff`) and its HTTP content routes. A deployment can run a second, +read-only `loreserver` that mounts only that service, to keep browsing load off the main +server. + +All reads are made as the browsing user; see [web-ui.md](web-ui.md). + +## Locks (phase 2, extended in phase 5) + +Locking is central to binary-asset workflows: two people should not edit the same asset. + +- **Lock dashboard** per repository: who holds what, since when. +- **Release** a lock you hold; admins can release others'. +- **Live updates** from Lore's lock and unlock events. + +Backed by `LockService`. Note that Lore's roadmap describes current locking as informing +rather than enforcing, with enforcement planned. + +## Change requests (phase 3) + +Lore has no forks yet, so change requests are **branch-based**: a change request proposes +landing one branch of a repository onto another branch of the same repository. + +- **Open** a change request from a pushed branch. +- **Review:** comments on the change and on lines of a diff, approvals, requests for changes. +- **Updates:** pushing more revisions to the source branch updates the change request. +- **Checks:** external systems report status against the head revision (phase 4). + +## Landing + +Each branch is in one of two modes. This is a per-branch setting because branch protection in +Lore is per branch. + +### Review required + +- lore-forge protects the branch in Lore. +- lore-forge's own landing identity is the only holder of `push-protected` on the repository, + apart from service accounts explicitly given it. +- When a change request meets its requirements, lore-forge lands it with one call to Lore: + a branch push naming the source branch's head revision, with `fast_forward_merge` set so the + server attempts the merge if the target has moved. +- No hook or modified server is involved; the gate is enforced by who holds the permission. + +If the server cannot merge, the author brings their branch up to date locally and pushes +again. How Lore reports that case is unverified. + +### Direct push + +- The branch stays unprotected; anyone with Writer access pushes to it. +- Each push appears in the activity feed. +- People can comment on a pushed revision after the fact. + +This suits repositories of binary assets where work is trunk-based and coordinated by locks. + +### Requirements for landing (to be designed) + +Number of approvals, who may approve, required checks, and whether the author may land their +own change. Not yet decided. + +## Activity and integrations (phases 2 and 4) + +lore-forge subscribes to Lore's notification stream. Events available: branch created, branch +pushed, branch deleted, resource locked, resource unlocked, obliterate. + +- **Activity feed** per repository, per owner and per user (phase 2). +- **Live page updates** through server-sent events (phase 2). +- **Webhooks:** outbound HTTP calls on events, configured per repository or organisation + (phase 4). +- **Discord notifications:** post events to a channel (phase 4). +- **CI:** webhooks trigger builds; a status API lets CI report results against a revision, + which change requests can require (phase 4). + +Whether an external subscriber can use the notification stream in Lore's default configuration +is unverified. + +## Game-development specifics (phase 5) + +- **Asset previews:** images and textures first; thumbnails for `.uasset` files; 3D previews + later. +- **Image comparison** in diffs: side by side, swipe, onion skin. +- **Lock management** at scale: filters, bulk release for admins, stale-lock reports. + +Untrusted content rules in [web-ui.md](web-ui.md) apply to every preview. + +## Relationship to Epic's planned web client + +Lore's roadmap commits to an open-source web client with code review tools in 2027. If it +ships with a review model of its own, lore-forge should prefer interoperating with it over +maintaining a parallel one. Until its shape is known, the change request design here stays +simple and close to what Lore's protocol already offers. + +## Open questions + +- Requirements for landing (approvals, checks, self-landing). +- Whether change requests need a "merge commit" style as well as fast-forward landing. +- How after-the-fact review on direct-push branches is surfaced: per revision, or grouped per + push. +- Search across repositories, change requests and comments. diff --git a/.ai/designs/lore-integration.md b/.ai/designs/lore-integration.md new file mode 100644 index 0000000..b56dd51 --- /dev/null +++ b/.ai/designs/lore-integration.md @@ -0,0 +1,174 @@ +# Lore integration + +Status: design, nothing built. Last updated 2026-11-25. + +Facts here were checked against Lore's `main` at commit `6b12f00` (2026-11-25), workspace +version `0.14.1-nightly`. Lore is pre-1.0, so re-check before relying on them. + +## Minimum Lore version + +**v0.14.0** (12 November 2026). + +- v0.11.0 added OIDC login through the device grant and the per-repository token exchange. +- v0.12.0 added token refresh and logout revocation. +- v0.14.0 fixed verification of tokens from a token-exchange issuer. + +## How Lore handles authentication + +Verified in `docs/reference/lore-server-config.md` and +`docs/proposals/2026-08-20-oidc-oauth2-authentication.md`. + +- `loreserver` has no user database. With `[server.auth]` configured it verifies a bearer JWT + on every request, locally, against keys it fetched from the issuer. It makes no call to the + issuer per request. +- It advertises the issuer to clients, which then log in at the issuer directly. +- Lore defines two modes: + - **Tier 1:** actions are read from a role claim in the login token and apply to every + repository on the server. + - **Tier 2:** the client exchanges its login token for a short-lived token scoped to one + repository, and the server reads permissions from that token's `resources` claim. +- lore-forge uses Tier 2. + +## What the issuer must provide + +Lore calls this the capability profile. lore-forge implements all of it; details are in +[token-issuer.md](token-issuer.md). + +| Requirement | Standard | Used for | +| --- | --- | --- | +| Discovery document and JWKS | OIDC Discovery | Server and client find endpoints and keys | +| JWT access tokens with a stable `sub` | RFC 9068 (`at+jwt`) | Local verification | +| Device authorization grant | RFC 8628 | `lore auth login` | +| Refresh token grant | RFC 6749 | Keeping CLI logins alive | +| Client credentials grant | RFC 6749 | CI logins | +| Fixed audience | | Server rejects tokens minted for other services | +| Token exchange with a resource indicator | RFC 8693, RFC 8707 | Per-repository tokens | +| Revocation | RFC 7009 | `lore auth logout` | + +## Server configuration lore-forge will generate + +A sketch of the `loreserver` settings for this design. Field names are from the config +reference; the values are examples. + +```toml +[server.auth] +jwt_issuer = "https://forge.example.com" +jwt_audience = ["https://lore.example.com"] +jwt_typ = "at+jwt" +resource_claim = "resources" # enables per-repository authorization + +[server.auth.oidc] +client_id = "lore-cli" +scopes = ["openid", "offline_access"] +resource_template = "https://lore.example.com/partitions/{id}" +# token_exchange_issuer defaults to jwt_issuer, which is what we want: +# lore-forge is both the login issuer and the exchange issuer. + +[environment.endpoint] +user_url = "https://forge.example.com" # registry and name lookup +``` + +Defaults worth knowing: `resource_id_template` is `urc-{id}` and `resource_wildcard` is +`urc-*`, so a resource entry for a repository is named `urc-`. + +**Start order:** `loreserver` fetches the issuer's keys at startup and refuses to start if it +cannot. lore-forge must be up first. + +## Surfaces lore-forge uses + +| Need | Lore surface | Verified | +| --- | --- | --- | +| Browse trees, history, diffs | `lore.thin_client.v1.ThinClientService`: `RevisionTree`, `RevisionInfo`, `RevisionDiff`, `ContentDiff` | Proto read | +| Download file content | HTTP `/v1/repository/{id}/content/{address}`, plus presigned URLs | Routes read | +| Activity, webhooks, CI triggers | `NotificationService.Subscribe`. Events: branch created, pushed, deleted; resource locked, unlocked; obliterate | Proto read; `[notification] mode = "local"` is the default | +| Locks | `LockService`: `Lock`, `Query`, `Status`, `Unlock`, `AdminLock` | Proto read | +| Repository and branch admin | `lore.repository.v1.RepositoryService`, `lore.revision.v1.RevisionService` | Proto read | +| Landing a change | `RevisionService.BranchPush` with `fast_forward_merge` | Proto read | + +### Landing + +`BranchPushRequest` takes the signature of a revision that is already on the server, and a +`fast_forward_merge` flag: when the new tip does not descend from the current one, the server +attempts the merge itself. So lore-forge can land a reviewed branch with one call and needs no +working copy or Lore library. + +### Hooks are not used + +Lore's server hooks (`lore-server/src/hooks/`) are Rust traits compiled into the server. There +are no out-of-process hooks. lore-forge does not rely on them; review gating is done through +token permissions instead (see [forge-features.md](forge-features.md)). + +## Services lore-forge provides to Lore + +Both are defined in `lore-proto/proto/lore/user/v1/user.proto` and reached through `user_url`. + +### RepositoryRegistryService + +- **`RepositoryRegister(id, name)`** — `loreserver` calls this before storing a new repository, + forwarding the caller's login token, and refuses the create if the registry refuses. The + registry may reject the name, deny permission, or report a missing prerequisite. This is how + lore-forge enforces namespaces; see [namespaces-and-access.md](namespaces-and-access.md). +- **`RepositoryUnregister(id)`** — called before a delete, which is refused if the registry + refuses. The forwarded token may be repository-scoped or the login token. +- **`RepositoryList`** — streams the repositories the caller has permissions on, with those + permissions. Backs `lore repository list`. + +### UserService + +- **`UserGet`**, **`UserFind`** — resolve user IDs to display names and back. Lore records only + an identifier in revision history, so this is how the CLI shows names for revision authors + and lock holders. + +## Repositories on one server + +- One `loreserver` hosts many repositories. Each has an ID, a name, branches and metadata. Lore + also calls a repository a "partition". +- Names are `/`-separated segments of ASCII alphanumerics, `-`, `_` and `.`; no segment is + empty or starts with `.`. So `studio/game` is a valid name. +- Repositories are addressed as `lore://host:port/`. +- Listing fails past 100,000 repositories, which indicates the intended scale. + +## Token details that affect lore-forge + +- **Signing algorithm:** the server takes the algorithm from each key's declared `alg` in the + JWKS and verifies with the `jsonwebtoken` crate; RS256 is assumed only when `alg` is absent. + lore-forge will use ES256 and always declare `alg`. +- **Identity:** the server reads the caller's identity from the `identity` claim, or the alias + `https://lore.org/claims/identity`, falling back to `sub`. That value is recorded as the + creator and committer of revisions. +- **Where a token may be sent:** the client refuses to send a token to a host the token does + not name. It reads allowed hosts from a `root_domains` claim (or its namespaced alias), and + otherwise from `aud` entries that are `https` URLs or domains. The audience must therefore + cover the `loreserver` host. +- **Actions:** `read`, `write`, `owner`, `admin`, `migrate`, `push-protected`, `set-protected`, + `obliterate`, `presign`. Any grant on a repository implies `read`. +- **Exchanged token lifetime:** at most five minutes in Lore's sample service. The client keeps + an exchanged token until it expires, so a permission change takes effect within that window. + +## Not relied upon + +- **Lore's Rust crates.** They are unpublished (`publish = false`) and pre-1.0. lore-forge + talks to Lore over its network protocols. Only `forge-lore` uses Lore's protocol + definitions, pinned to a git revision. +- **Forks.** Lore's roadmap lists forks as "later, exploring", so change requests are + branch-based. + +## Unverified + +- How `BranchPush` with `fast_forward_merge` reports a conflict. +- Whether a repository can be renamed, which decides whether namespaces can be renamed. +- Whether identical content is deduplicated across repositories or only within one. +- The exact form of `user_url` and whether both services must share one endpoint. +- Whether `NotificationService.Subscribe` is reachable by an external subscriber in the default + `local` mode, and what permission it needs. +- What `loreserver` itself checks on repository create beyond asking the registry. +- How stable `ThinClientService` is between releases. + +## Upstream files worth reading + +- `docs/proposals/2026-08-20-oidc-oauth2-authentication.md` — the authentication design. +- `docs/reference/lore-server-config.md`, section "Authentication" — every setting. +- `contrib/oidc/README.md` and `contrib/oidc/exchange/` — runnable demos and the sample + token exchange service, which is the contract lore-forge's issuer follows. +- `lore-proto/proto/` — all gRPC definitions. +- `docs/roadmap.md` — what Epic plans, including its own web client. diff --git a/.ai/designs/namespaces-and-access.md b/.ai/designs/namespaces-and-access.md new file mode 100644 index 0000000..f5d9197 --- /dev/null +++ b/.ai/designs/namespaces-and-access.md @@ -0,0 +1,132 @@ +# Namespaces and access + +Status: design, nothing built. Last updated 2026-11-25. + +## Namespaces + +Repositories live under GitHub-style owners: `owner/repo`. + +- **Two kinds of owner:** a user (personal namespace) or an organisation. +- **One name table.** Usernames and organisation names share a single table, so they cannot + collide. +- **Every user has a personal namespace** named after their username. +- **Organisations** have members and teams. +- **Names are fixed in the first version.** Renaming a namespace would mean renaming the Lore + repositories under it, and whether Lore allows that is unverified. + +### How this maps to Lore + +Verified in Lore's source; see [lore-integration.md](lore-integration.md). + +- Lore repository names may contain `/`, so `studio/game` is a valid repository, addressed as + `lore://host/studio/game`. +- One `loreserver` hosts all namespaces. +- Lore identifies a repository by ID. The name is a label; permissions and tokens use the ID. + +### Enforcing namespaces through the registry + +`loreserver` asks lore-forge before it creates or deletes a repository, forwarding the +caller's token. + +On **register** (create), lore-forge: + +1. checks the name has the form `/` and that both parts are valid; +2. checks the owner exists (answers "not found" otherwise); +3. checks the caller may create repositories in that namespace (answers "permission denied" + otherwise); +4. records the repository with the caller as its owner. + +On **unregister** (delete), lore-forge checks the caller holds the owner role on the +repository. + +For **list**, lore-forge returns the repositories the caller has any grant on, with the +actions held on each. + +So `lore repository create lore://host/studio/game` works from the CLI and is subject to the +same rules as creating a repository in the web UI. + +### Who may create what + +| Action | Allowed for | +| --- | --- | +| Create a repository in a personal namespace | That user | +| Create a repository in an organisation | Members the organisation allows (owners by default) | +| Create an organisation | An instance setting. Defaulted to instance admins only; not yet confirmed | + +## Organisations and teams + +- **Members** belong to an organisation with an organisation role: owner or member. +- **Teams** are named groups of members within one organisation. +- **Base permission:** an organisation may give all its members a default role on all its + repositories (for example Reader), or none. + +## Role presets + +Permissions are presented as presets that map onto Lore's actions. + +| Preset | Lore actions | Meant for | +| --- | --- | --- | +| Reader | `read` | Clone and browse | +| Writer | `write` | Push to unprotected branches, take locks | +| Maintainer | `write`, `set-protected` | Also protect and unprotect branches | +| Admin | `write`, `admin` | Also release others' locks, manage the repository | +| Owner | `owner` | Also delete the repository | + +Notes: + +- In Lore, any grant on a repository implies `read`. +- The mapping of `admin` and `owner` to specific operations is taken from Lore's + documentation: branch protection needs `owner`, `admin` or `set-protected`; repository delete + needs `owner` or `admin`. The table above should be re-checked against Lore's enforcement + points before implementation. + +### Advanced view + +Four actions are not part of any human preset and are granted individually: + +| Action | What it allows | Why it is separate | +| --- | --- | --- | +| `push-protected` | Push to a protected branch | Holding it bypasses review; see below | +| `obliterate` | Permanently remove content from the server | Destructive and irreversible | +| `presign` | Issue presigned download URLs | Meant for services | +| `migrate` | Administrative lock operations | Rarely needed | + +**No human preset includes `push-protected`.** On a review-gated branch, lore-forge's own +landing identity is the only holder, which is what makes the gate enforceable. A CI service +account can be given it explicitly. See [forge-features.md](forge-features.md). + +## Grants + +A grant gives a subject a preset, plus optional extra actions, on a repository. + +- **Subjects:** a user, a team, or a service account. +- **Sources of a user's access to a repository**, combined by union: + 1. the repository is in their personal namespace (Owner); + 2. their organisation role and the organisation's base permission; + 3. grants to teams they belong to; + 4. direct grants as a collaborator. +- **Resolution** produces the set of Lore actions that goes into the repository-scoped token. + It happens at token exchange time; see [token-issuer.md](token-issuer.md). +- **Changes apply within five minutes**, when the client's current scoped token expires. + +Resolution is on the hot path of every token exchange, so it must be answerable from a small +number of indexed reads. + +## Mapping from GitHub and Discord (later) + +Recommended and not yet designed in detail: an organisation can be linked to a GitHub +organisation or a Discord server, with rules that map GitHub teams or Discord roles onto +lore-forge teams. Membership would be synchronised periodically and on sign-in. + +This depends on a decision already made: provider tokens are not kept after sign-in. A +synchronisation feature would need either an installed GitHub App or Discord bot acting for +the organisation, or a change to that rule. Not part of phase 1. + +## Open questions + +- Confirm who may create organisations. +- Whether namespaces can be renamed (depends on Lore). +- Whether repositories can be transferred between namespaces. +- Visibility: whether a repository can be public to all signed-in users, or to anonymous + visitors of the web UI. Lore itself has no anonymous access when authentication is enabled. +- The exact organisation-level roles beyond owner and member. diff --git a/.ai/designs/storage.md b/.ai/designs/storage.md new file mode 100644 index 0000000..961336f --- /dev/null +++ b/.ai/designs/storage.md @@ -0,0 +1,113 @@ +# Storage + +Status: design, nothing built. Last updated 2026-11-25. + +## What lore-forge stores + +lore-forge stores everything about people, permissions and collaboration. It stores **no +repository data**; that is entirely in `loreserver`. + +## SQLite + +The owner chose SQLite, matching piki. + +- **One binary, one data directory.** Running an instance means one process and one directory + to back up, alongside `loreserver`'s own storage. +- **Write-ahead logging** so readers do not block the single writer. +- **Numbered SQL migrations** applied at startup, as in piki. +- **No high availability.** One instance, one database file. This fits the assumed audience of + a single self-hosted studio or community. + +### The token exchange path must not write + +Every active Lore client exchanges a token for each repository it uses about every five +minutes. With SQLite's single writer, that path is kept read-only: it resolves grants and +signs. Anything recorded about exchanges (last-used times, audit entries) is batched and +written periodically, not per request. See [token-issuer.md](token-issuer.md). + +### Library + +Not yet decided. `sqlx` (async, compile-time-checked queries, built-in migrations) is the +default candidate; `rusqlite` with a dedicated writer thread is the alternative. + +## Data directory + +| Item | Contents | +| --- | --- | +| Main database | All tables below | +| Render cache | Rendered and highlighted trees, files and diffs, keyed by content hash. Disposable; kept out of the main database so backups stay small | +| Generated `loreserver` config | The auth settings lore-forge produces for the Lore server | + +## Secrets + +One 32-byte key, supplied through the environment, encrypts: + +- provider client secrets (GitHub, Discord, Google); +- lore-forge's private token signing keys. + +The key is not stored in the data directory. As in piki, losing it means provider secrets must +be re-entered; here it also means new signing keys, which invalidates outstanding tokens and +requires `loreserver` to pick up the new keys. + +Stored only as hashes, never recoverable: passwords, session tokens, refresh tokens, API +tokens, device codes, invite-flow state. + +## Tables (phase 1 sketch) + +Names are provisional. + +### Accounts — following piki + +| Table | Holds | +| --- | --- | +| `users` | Username, display name, password hash, instance role, disabled flag | +| `sessions` | Hashed token, user, method used, user agent, created, expires, revoked | +| `invite_keys`, `invite_key_uses` | Key, name, maximum uses, active flag; who used it | +| `oauth_provider_configs` | Provider, client ID, encrypted secret, enabled | +| `oauth_identities` | `(provider, subject id)` → user; unique per user and provider | +| `oauth_flows` | Hashed state, intent, PKCE verifier, nonce, expiry, used | +| `passkey_credentials`, `passkey_ceremonies` | Public keys; single-use ceremony state | +| `settings` | Instance settings: signup toggle, canonical URL, who may create organisations | + +### Namespaces and access + +| Table | Holds | +| --- | --- | +| `namespaces` | Name, kind (user or organisation). The single name table | +| `orgs`, `org_members` | Organisation details; member and organisation role | +| `teams`, `team_members` | Teams within an organisation | +| `repos` | Lore repository ID, namespace, name, base permission, per-branch landing settings | +| `grants` | Repository, subject (user, team or service account), preset, extra actions | + +### Issuer + +| Table | Holds | +| --- | --- | +| `signing_keys` | Key ID, algorithm, encrypted private key, public key, state | +| `device_codes` | Hashed device code, user code, client, status, expiry | +| `refresh_tokens` | Hashed token, user, created, last used, revoked. Shown in the session list | +| `service_accounts` | Non-human identities and their owner | +| `api_tokens` | Hashed token, owner, name, scopes, expiry, last used | + +### Shared + +| Table | Holds | +| --- | --- | +| `audit_log` | Who did what, when: sign-ins, grant changes, settings changes, landings | + +### Later phases + +Change requests, reviews, comments, activity events, webhooks and their deliveries, check +statuses. Full-text search can use SQLite's FTS5. + +## Backups + +- Back up the main database and the encryption key (stored separately). +- The render cache does not need backing up. +- Repository data is backed up through `loreserver`'s own storage. + +## Open questions + +- `sqlx` or `rusqlite`. +- How long to retain audit entries and activity events. +- Whether exchanged-token activity is audited at all. diff --git a/.ai/designs/token-issuer.md b/.ai/designs/token-issuer.md new file mode 100644 index 0000000..f7631e4 --- /dev/null +++ b/.ai/designs/token-issuer.md @@ -0,0 +1,144 @@ +# Token issuer + +Status: design, nothing built. Last updated 2026-11-25. + +lore-forge is the OpenID Connect issuer that `loreserver` trusts. This document covers what it +must serve. The requirements come from Lore; see [lore-integration.md](lore-integration.md). + +## Role + +- Lore clients log in at lore-forge and receive tokens. +- `loreserver` verifies those tokens locally with lore-forge's public keys. +- lore-forge is both the login issuer and the token-exchange issuer, under one issuer URL. + +lore-forge is an issuer for Lore clients. It is not a general-purpose identity provider for +other applications. + +## Endpoints + +| Endpoint | Purpose | +| --- | --- | +| `/.well-known/openid-configuration` | Discovery document | +| JWKS endpoint | Public signing keys, each with `alg` declared | +| Device authorization endpoint | Starts a CLI login | +| Token endpoint | All grants below | +| Revocation endpoint | `lore auth logout` | +| Device verification page | Browser page where the person approves a CLI login (part of the web UI) | + +## Grants on the token endpoint + +| Grant | Used by | Result | +| --- | --- | --- | +| Device code (RFC 8628) | `lore auth login` | Login token and refresh token | +| Refresh token | Lore client, automatically | New login token; refresh token rotated | +| Client credentials | CI, `lore auth login --client-id` | Login token for a service account | +| Token exchange (RFC 8693), login token in | Lore client, per repository | Repository-scoped token | +| Token exchange (RFC 8693), API token in | CI without a browser | Login token for the token's user | + +The device grant must honour the polling rules Lore's client expects: `interval`, +`slow_down`, `expired_token` and `access_denied`. + +## Tokens + +### Login token + +A JWT access token (`typ: at+jwt`) identifying the user. + +| Claim | Value | +| --- | --- | +| `iss` | lore-forge's issuer URL | +| `sub` | Stable internal user ID | +| `aud` | The `loreserver` deployment URL | +| `identity` | The identity Lore records in history (see below) | +| `root_domains` | Hosts the token may be sent to, if `aud` alone does not cover them | +| `name`, `preferred_username` | For display | +| `exp`, `iat` | Short lifetime; renewed by refresh | + +It carries no repository permissions. `loreserver` accepts it for calls that do not name one +repository, such as creating a repository, and forwards it to lore-forge's registry. + +### Repository-scoped token + +Issued by token exchange for exactly one repository. + +- Same `iss`, `sub`, `aud` and `identity` as the login token, so the caller is the same user to + `loreserver` in both. +- Adds `resources: [{"resource_id": "urc-", "permission": [...]}]` with the + actions the user holds on that repository. +- Lifetime of at most five minutes, and never past the login token's expiry. + +### Exchange behaviour + +1. The client sends its login token as `subject_token` and names the repository as + `resource=`. +2. lore-forge verifies the login token, resolves the user's actions on that repository from + its grants, and signs the scoped token. +3. Errors follow the sample service Lore ships: `invalid_grant` for a login token that does + not verify (the client reports "not authenticated"), `invalid_target` for a repository the + user has no grant on (the client reports "not authorized"). + +### Performance constraint + +Every active Lore client repeats the exchange for each repository it uses about every five +minutes. This path must be cheap: it reads grants and signs, and performs no database write. +Audit records for exchanges are batched or sampled. See [storage.md](storage.md). + +### Refresh tokens + +- Opaque, stored hashed, rotated on use. +- One per CLI login. Shown in the user's session list and revocable there. +- Lore's client requests `offline_access` on every login; lore-forge issues a refresh token + for it. +- Revocation through the revocation endpoint ends the login. + +## Signing keys + +- **Algorithm:** ES256, with `alg` always declared in the JWKS. `loreserver` takes the + algorithm from the declared value. +- **Storage:** private keys are stored encrypted with the same environment-supplied key that + protects provider secrets. +- **Rotation:** the JWKS publishes the current key and the previous one. `loreserver` re-fetches + keys when it sees an unknown key ID, so rotation needs no server restart. +- **Stability:** keys persist across restarts. Lore's sample service regenerates its key on + every start, which invalidates all outstanding tokens; lore-forge must not. + +## Identity claim + +Lore records `identity` (or `sub` when absent) as the creator and committer of revisions. + +**Recommended, not yet confirmed:** set it to the stable internal user ID and serve names +through Lore's `UserService`. See [accounts-and-sign-in.md](accounts-and-sign-in.md). + +## Service accounts and CI + +- A service account is a non-human identity owned by a user or organisation. +- It logs in with client credentials, or with an API token through token exchange. +- It receives grants like any user. The `push-protected` action is how a CI account is allowed + to push to a protected branch. + +## Revocation and how fast changes apply + +| Change | Takes effect | +| --- | --- | +| Grant added or removed | Within five minutes, when the client's scoped token expires | +| CLI login revoked | When the current login token expires; no new tokens after that | +| User disabled | Same as a revoked login, for all of that user's logins | +| Signing key rotated out | When removed from the JWKS | + +Lifetimes for the login token and refresh token are not yet decided. + +## Security notes + +- The private signing keys grant access to every repository. They are the most sensitive data + lore-forge holds. +- The token endpoint and the cookie-authenticated web UI share a process. Constraints that + keep untrusted repository content away from them are in [web-ui.md](web-ui.md). +- The audience is fixed to the deployment, so tokens cannot be replayed against another + service, and Lore's client will not send them to a host the token does not name. + +## Open questions + +- Login token and refresh token lifetimes. +- Whether the audience alone covers every host a token must reach, or a `root_domains` claim + is needed (relevant if `loreserver` and lore-forge are on unrelated domains). +- Whether to keep an audit trail of token exchanges, and at what granularity. diff --git a/.ai/designs/web-ui.md b/.ai/designs/web-ui.md new file mode 100644 index 0000000..3d21e37 --- /dev/null +++ b/.ai/designs/web-ui.md @@ -0,0 +1,96 @@ +# Web UI + +Status: design, nothing built. Last updated 2026-11-25. + +## Approach + +The UI is rendered on the server by the same Rust binary that serves everything else. There is +no separate frontend application and no Node build step. + +| Concern | Choice | Notes | +| --- | --- | --- | +| HTTP framework | axum | Lore's server uses it too | +| Templates | maud | Components are plain Rust functions, so a handler can return a whole page or one fragment. Askama is the alternative if HTML should live in template files | +| Interactivity | htmx | Vendored, not fetched from a CDN | +| Scripts | A few small hand-written ones | Only where HTML is not enough: diff viewer, image comparison, later 3D previews | +| Styles | Plain CSS with custom properties | | +| Assets | Embedded in the binary | One file to deploy | +| Live updates | Server-sent events | Fed by Lore's notification stream: activity, lock state, CI status | +| API | JSON under `/api/v1` | Calls the same core services as the pages; authenticated by API tokens | + +The template and interactivity choices are recommendations that have not been explicitly +confirmed; "server-rendered" has. + +## Why server rendering suits Lore + +Lore is content-addressed. A tree, a file and a diff between two revisions are each fixed by +their hashes and never change. + +- Rendered and syntax-highlighted output can be cached indefinitely, keyed by hash. +- The hash is a natural `ETag`, so browsers and proxies cache correctly without extra logic. +- Only branch tips, locks and activity are mutable; those are the parts driven by live updates. + +## Large files + +Game repositories hold very large binary files. lore-forge does not relay them. + +- Downloads redirect to presigned URLs served by `loreserver`. +- The browser fetches large assets directly from `loreserver`. +- Listings and diffs are streamed from Lore's gRPC streams into the response rather than + buffered. + +## Security + +The web UI shares a process with the token issuer, which holds the keys to every repository. +Repository content is untrusted: Markdown, SVG and HTML files can carry script. + +- **Raw content on a separate origin.** Raw files and previews are served from a different + hostname than the UI and issuer, so a malicious file cannot read session cookies or call the + UI as the user. +- **Strict content security policy** on the main origin, with no inline script. Server + rendering makes this straightforward; htmx is configured to work without inline handlers. +- **Rendered Markdown is sanitised** before it is placed in a page on the main origin. +- **Server-side sessions** with CSRF tokens on unsafe methods; see + [accounts-and-sign-in.md](accounts-and-sign-in.md). +- **The canonical public URL is configured, not inferred** from request headers. Behind a + reverse proxy, forwarded headers are trusted only when explicitly enabled. + +## Acting as the user + +When a page needs data from `loreserver`, lore-forge mints a short-lived repository-scoped +token carrying the browsing user's identity and their actual grants, and calls `loreserver` +with it. + +- The web UI and the CLI are authorised by the same rule, enforced in the same place. +- lore-forge holds no standing super-user credential for reading repositories. +- The one exception is landing a change on a review-gated branch, where lore-forge uses its own + landing identity; see [forge-features.md](forge-features.md). + +## Routes (sketch) + +| Path | Page | +| --- | --- | +| `/` | Dashboard: your repositories and recent activity | +| `/setup`, `/login`, `/signup/` | Account entry points | +| `/device` | Approve a CLI login | +| `/settings/...` | Profile, linked providers, sessions, API tokens; instance settings for the owner | +| `/` | A user's or organisation's repositories | +| `//` | Repository home | +| `///tree//` | File browser | +| `///history/` | Revision history | +| `///revision/` | One revision and its diff | +| `///changes`, `/changes/` | Change requests | +| `///locks` | Lock dashboard | +| `///settings` | Access, branch rules | +| `/.well-known/openid-configuration`, token and device endpoints | The issuer | +| `/api/v1/...` | JSON API | + +Because owners occupy the top level of the path, reserved words such as `login`, `settings` +and `api` cannot be used as usernames or organisation names. + +## Open questions + +- Confirm maud and htmx. +- Hostname scheme for the raw-content origin, and how it is configured for small self-hosted + installs that have only one hostname. +- Whether anonymous visitors can see anything. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b2e5f46 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,51 @@ +# Agent Notes + +lore-forge is a Rust web server that sits beside Epic's [Lore](https://github.com/EpicGames/lore) +version control server. It provides accounts, sign-in through GitHub, Discord and Google, the +tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on top. + +**Status:** design only. No code has been written yet. + +## Git commits + +- **Do not add Claude or any other AI attribution to commits.** No `Co-Authored-By: Claude ...` + trailer, no "Generated with Claude Code" line, no similar footer. This applies to commit + messages and to pull request descriptions. +- Commit only when asked. + +## Where things are + +- [.ai/designs/](.ai/designs/) holds the design documents. Start with + [architecture-overview.md](.ai/designs/architecture-overview.md), which links to the rest. + +| Document | Covers | +| --- | --- | +| [architecture-overview.md](.ai/designs/architecture-overview.md) | The whole system, decisions made so far, build phases | +| [lore-integration.md](.ai/designs/lore-integration.md) | What Lore provides and requires, and how lore-forge connects to it | +| [accounts-and-sign-in.md](.ai/designs/accounts-and-sign-in.md) | Accounts, invites, provider linking, sessions | +| [token-issuer.md](.ai/designs/token-issuer.md) | The OIDC issuer: endpoints, grants, claims, keys | +| [namespaces-and-access.md](.ai/designs/namespaces-and-access.md) | User/org namespaces, teams, role presets, grants | +| [web-ui.md](.ai/designs/web-ui.md) | Server-rendered UI stack and its security constraints | +| [forge-features.md](.ai/designs/forge-features.md) | Repo browser, change requests, landing, activity | +| [storage.md](.ai/designs/storage.md) | SQLite, the data directory, tables | + +## Working on the design + +- Keep the design documents current. When a decision changes, edit the document that owns it + and the decision table in the overview, rather than adding a new file that contradicts it. +- Each document separates what was **verified in Lore's source** from what is **assumed** or + **open**. Keep that distinction when editing; do not promote an assumption to a fact without + checking. +- Lore is pre-1.0 and changes quickly. Before relying on a Lore behaviour described here, + re-check it against the Lore version in use. The documents record which commit they were + checked against. +- Put open design decisions to the project owner as interactive questions with a recommended + option, rather than listing them in prose and assuming an answer. + +## References + +- **Lore:** . Minimum version for this design is v0.14.0. + The most relevant upstream files are listed in + [lore-integration.md](.ai/designs/lore-integration.md). +- **piki:** the owner's Go project (a sibling checkout, `../piki`) is the reference for the + account system. Its `agents/data-auth-services.md` maps the auth code.