diff --git a/.env.example b/.env.example index dac08f9..6741b38 100644 --- a/.env.example +++ b/.env.example @@ -17,19 +17,23 @@ APP_MAINTENANCE_DRIVER=file # PHP_CLI_SERVER_WORKERS=4 -# Argon2id reads a whole password, where bcrypt stops at 72 bytes (OWASP ASVS -# 6.2.9). Accounts made while this app still hashed with bcrypt are rehashed -# as they sign in: uncomment HASH_VERIFY until they have been. +# Argon2id reads a whole password, where bcrypt (Laravel's default) stops at +# 72 bytes (OWASP ASVS 6.2.9). To bring in accounts hashed with bcrypt, say +# from an app this one replaces, uncomment HASH_VERIFY: they're rehashed as +# they sign in. HASH_DRIVER=argon2id # HASH_VERIFY=false # Where sign ins come from, for the device list and the NewCountry and # ImpossibleTravel risk signals. Unset, nothing is located. "cloudflare" reads # Cloudflare's location headers: only safe when every request has to come -# through Cloudflare, since anyone else can send them. "demo" is for playing -# on your own machine: the login page gets a "Pretend to be in" picker. It's -# ignored unless APP_ENV is local or testing. +# through Cloudflare, since anyone else can send them. +# @monorepo-only:start +# "demo" is for playing on your own machine: the login page gets a "Pretend +# to be in" picker. It's ignored unless APP_ENV is local or testing. # KEYRING_LOCATOR=demo +# @monorepo-only:end +# KEYRING_LOCATOR=cloudflare # Have I Been Pwned. Unset, new passwords are checked in production only, as # Keyring does by default. true checks them everywhere, and every password diff --git a/.gitattributes b/.gitattributes index 4da48a8..1d7f82b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,5 +7,3 @@ *.php diff=php CHANGELOG.md export-ignore -README.md export-ignore -.github/workflows/browser-tests.yml export-ignore diff --git a/.github/workflows/kits.yml b/.github/workflows/kits.yml new file mode 100644 index 0000000..9d1d093 --- /dev/null +++ b/.github/workflows/kits.yml @@ -0,0 +1,252 @@ +# Checks the monorepo, exports every starter kit (kits/*/kit.json) as a +# standalone Laravel app and checks that too. On a published release, each +# kit's tested export is pushed to its read-only repository. +name: Kits + +on: + push: + branches: [main] + pull_request: + release: + types: [published] + +permissions: + contents: read + +concurrency: + group: kits-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + list: + name: List the kits + runs-on: ubuntu-latest + outputs: + kits: ${{ steps.list.outputs.kits }} + steps: + - uses: actions/checkout@v5 + + # Each kit's repository comes from its kit.json, and the deploy key + # for it from a secret named after the kit: + # inertia-react -> STARTER_INERTIA_REACT_DEPLOY_KEY. Names and + # repositories are checked here, since later jobs put them in paths + # and commands. + - id: list + run: | + node -e ' + const fs = require("node:fs"); + const kits = fs.readdirSync("kits") + .filter((name) => fs.existsSync(`kits/${name}/kit.json`)) + .sort() + .map((name) => { + if (!/^[a-z0-9-]+$/.test(name)) { + throw new Error(`kits/${name}: kit names are lowercase letters, digits and dashes`); + } + const kit = JSON.parse(fs.readFileSync(`kits/${name}/kit.json`, "utf8")); + if (kit.name !== name) { + throw new Error(`kits/${name}/kit.json says its name is ${kit.name}`); + } + if (!/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/.test(kit.repository ?? "")) { + throw new Error(`kits/${name}/kit.json needs a repository, like owner/name`); + } + return { + name, + repository: kit.repository, + secret: `STARTER_${name.toUpperCase().replace(/-/g, "_")}_DEPLOY_KEY`, + }; + }); + fs.appendFileSync(process.env.GITHUB_OUTPUT, `kits=${JSON.stringify(kits)}\n`); + console.log(kits); + ' + + monorepo: + name: Monorepo + runs-on: ubuntu-latest + env: + # .env.example points at a local Postgres and Redis; CI has neither. + DB_CONNECTION: sqlite + CACHE_STORE: array + steps: + - uses: actions/checkout@v5 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.5' + coverage: none + + - uses: actions/setup-node@v5 + with: + node-version: lts/* + cache: npm + + - run: composer install --no-interaction --no-progress + - run: cp .env.example .env && php artisan key:generate + - run: npm ci + - name: Export tooling tests + run: node --test bin/ + - run: npm run build + - run: npm test + - run: composer ci:check + + kit: + name: Kit (${{ matrix.kit.name }}) + needs: list + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + kit: ${{ fromJSON(needs.list.outputs.kits) }} + env: + KIT: ${{ matrix.kit.name }} + EXPORT: ${{ github.workspace }}/../starter-${{ matrix.kit.name }} + steps: + - uses: actions/checkout@v5 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.5' + coverage: none + + - uses: actions/setup-node@v5 + with: + node-version: lts/* + cache: npm + + # The export formats the files it rewrites with the monorepo's tools. + - run: npm ci + + - name: Export + run: | + node bin/export-kit.mjs "$KIT" "$EXPORT" + tar -czf "$RUNNER_TEMP/export.tgz" -C "$EXPORT" . + + - uses: actions/upload-artifact@v4 + with: + name: starter-${{ matrix.kit.name }} + path: ${{ runner.temp }}/export.tgz + retention-days: 7 + + # What `laravel new --using` and `composer create-project` do, then + # the kit's own checks. + - name: Install + working-directory: ${{ env.EXPORT }} + run: | + composer validate --no-check-publish + composer install --no-interaction --no-progress + composer run post-root-package-install + php artisan key:generate + npm ci + + - name: Build + working-directory: ${{ env.EXPORT }} + run: npm run build + + - name: Check and test + working-directory: ${{ env.EXPORT }} + run: | + npm test + composer ci:check + + release: + name: Release (${{ matrix.kit.name }}) + needs: [list, monorepo, kit] + if: >- + github.event_name == 'release' && + github.event.action == 'published' && + !github.event.release.prerelease + runs-on: ubuntu-latest + # The deploy keys are secrets of this environment, which only tags + # may deploy to (see the README's "CI and releases"). + environment: release + strategy: + fail-fast: false + matrix: + kit: ${{ fromJSON(needs.list.outputs.kits) }} + env: + KIT: ${{ matrix.kit.name }} + REPOSITORY: ${{ matrix.kit.repository }} + SECRET: ${{ matrix.kit.secret }} + steps: + # Skipped only while the kit's repository doesn't exist yet. Once + # it does, a missing key or a failed check fails the release. + - name: Check the target + id: target + env: + DEPLOY_KEY: ${{ secrets[matrix.kit.secret] }} + GH_TOKEN: ${{ github.token }} + run: | + status=$(curl -sS -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H 'Accept: application/vnd.github+json' \ + "https://api.github.com/repos/$REPOSITORY") + + if [ "$status" = 404 ]; then + echo "::notice::$REPOSITORY doesn't exist yet (or isn't public), so $KIT isn't released." + echo "skip=true" >> "$GITHUB_OUTPUT" + elif [ "$status" != 200 ]; then + echo "::error::Checking $REPOSITORY returned HTTP $status." + exit 1 + elif [ -z "$DEPLOY_KEY" ]; then + echo "::error::$REPOSITORY exists, but the release environment has no $SECRET secret." + exit 1 + else + echo "skip=false" >> "$GITHUB_OUTPUT" + fi + + - if: steps.target.outputs.skip == 'false' + uses: actions/download-artifact@v4 + with: + name: starter-${{ matrix.kit.name }} + path: ${{ runner.temp }} + + - name: Push + if: steps.target.outputs.skip == 'false' + env: + DEPLOY_KEY: ${{ secrets[matrix.kit.secret] }} + TAG: ${{ github.event.release.tag_name }} + SOURCE: ${{ github.repository }}@${{ github.sha }} + run: | + set -euo pipefail + + key="$RUNNER_TEMP/deploy_key" + hosts="$RUNNER_TEMP/known_hosts" + printf '%s\n' "$DEPLOY_KEY" > "$key" + chmod 600 "$key" + echo 'github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl' > "$hosts" + export GIT_SSH_COMMAND="ssh -i $key -o IdentitiesOnly=yes -o UserKnownHostsFile=$hosts -o StrictHostKeyChecking=yes" + + # Keep the repository's history: each release is one commit + # on top of the last, and an empty repository gets its first. + target="$RUNNER_TEMP/target" + git clone --depth 1 "git@github.com:$REPOSITORY.git" "$target" + cd "$target" + git checkout -B main + find . -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} + + tar -xzf "$RUNNER_TEMP/export.tgz" -C . + git add -A + + # A re-run: the tag is there already. Fine if it holds these + # exact files, an error if it holds anything else. + if git ls-remote --exit-code --tags origin "refs/tags/$TAG" > /dev/null; then + git fetch --depth 1 origin "refs/tags/$TAG:refs/tags/$TAG" + + if [ "$(git rev-parse "refs/tags/$TAG^{tree}")" = "$(git write-tree)" ]; then + echo "$TAG is already on $REPOSITORY with these files." + exit 0 + fi + + echo "::error::$TAG is already on $REPOSITORY with different files." + exit 1 + fi + + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + + if git diff --cached --quiet; then + echo "Nothing changed since the last release." + else + git commit -q -m "chore(release): $TAG from $SOURCE" + fi + + git tag -a "$TAG" -m "$TAG from $SOURCE" + git push --atomic origin main "refs/tags/$TAG" diff --git a/.gitignore b/.gitignore index 5040c95..23b02fb 100644 --- a/.gitignore +++ b/.gitignore @@ -51,5 +51,7 @@ yarn-error.log frankenphp frankenphp-worker.php +# @monorepo-only:start # Maizzle writes its IDE type definitions here. /.maizzle +# @monorepo-only:end diff --git a/README.md b/README.md index 229afe9..a48c7be 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,192 @@ -# Keyring example + + +# Keyring starter kits + +Laravel starter kits with [Keyring](https://github.com/keyringphp/keyring) for sign in, passkeys, second factors, sessions and security emails. Every kit shares one Laravel backend, the app at the root of this repository, and each is also published on its own, ready for `laravel new`. + +| Kit | Frontend | Install | +| ---------------- | ----------------------------------------------------------------- | ------------------------------------------------------------- | +| `inertia-react` | Inertia and React, the app in this repository (`resources/js`) | `laravel new my-app --using=keyringphp/starter-inertia-react` | +| `tanstack-start` | TanStack Start, talking to the backend headless (coming, `kits/`) | | +| `nuxt` | Nuxt, talking to the backend headless (coming, `kits/`) | | + +## Installing a kit + +```bash +laravel new my-app --using=keyringphp/starter-inertia-react +cd my-app +composer dev +``` + +Without the installer, `composer create-project keyringphp/starter-inertia-react my-app` followed by `npm install && npm run build` does the same. Either way the new app gets its `.env` from `.env.example`, an app key and a migrated SQLite database, like Laravel's own starter kits. + +A kit is a clean starter, not this repository's demo: a plain welcome page and dashboard, every auth page, the settings pages (profile, security, appearance) and Keyring's emails, under the app's own name. `php artisan db:seed` adds one test user, as Laravel's kits do. The demo stays here, for keyringphp.com and the browser tests (see [The demo](#the-demo)). + +`APP_URL` in `.env` has to be the address the app is opened at, because Keyring builds the passkey origin and every emailed link from it. `laravel new my-app` sets it (to `http://my-app.test` under Herd or Valet, `http://localhost:8000` otherwise), and `composer create-project` sets `http://localhost:8000`, where `composer dev` serves. `laravel new .` leaves it at `http://localhost`, so set it yourself after that, or whenever you serve the app somewhere else. + +Each kit's repository (`keyringphp/starter-`) is read-only and built from this one on every release, so issues and pull requests come here. + +## Layout + +``` +app/, config/, routes/... # the Laravel backend every kit shares +app/Demo/, routes/demo.php # the demo, which no kit gets (see "The demo") +resources/js/ # inertia-react's frontend: pages, layouts, Keyring's components +resources/css/app.css # inertia-react's stylesheet: the theme, then its @source lines +packages/ +├── theme/ # @keyringjs/theme: Tailwind v4, the palette, shadcn tokens, dark mode, fonts +└── ui-react/ # @keyringjs/ui-react: the shadcn/ui primitives, cn() and useIsMobile() +kits/ +├── inertia-react/ # kit.json (how to export it) and the README its repository gets +└── / # a headless kit: kit.json and its frontend app (coming) +bin/export-kit.mjs # builds one kit as a standalone Laravel app +.github/workflows/kits.yml # checks the monorepo and every kit, and publishes them on release +``` + +The JavaScript side is one npm workspace (`packages/*` and `kits/*`), with one `package-lock.json` at the root. + +`@keyringjs/theme` is the one stylesheet every kit imports, React or Vue, so they all look the same: + +```css +@import '@keyringjs/theme'; +@source '../views'; +``` + +It brings Tailwind and `tw-animate-css` with it. Dark mode follows a `dark` class on ``, and the font stack starts with Inter, which this app loads through `laravel-vite-plugin`'s Bunny fonts. A kit without that imports `@keyringjs/theme/fonts.css` first. + +`@keyringjs/ui-react` has no router or Inertia imports, so any React kit can use it. Its files are imported one at a time, like shadcn's: + +```tsx +import { Button } from '@keyringjs/ui-react/button'; +import { useIsMobile } from '@keyringjs/ui-react/hooks/use-mobile'; +import { cn } from '@keyringjs/ui-react/utils'; +``` + +Two things stay in the app because they need Inertia: the toaster (`resources/js/components/ui/sonner.tsx`, which shows Inertia's flashed toasts) and `toUrl()` (`resources/js/lib/url.ts`, which reads Inertia's link types). So do Keyring's own components, pages and layouts, until the TanStack kit gives them a router-free shape. `components.json` (and the `paths` in `tsconfig.json`) point shadcn's CLI at the package, so `npx shadcn add ` writes new primitives to `packages/ui-react/src/components/ui`. An exported kit gets the usual `components.json` back, pointing at its own `resources/js/components/ui`. + +## The demo + +The app here is also the demo keyringphp.com runs and the browser tests drive: a welcome page with two seeded accounts (one with an authenticator app, shown as a QR code), a dashboard of things to try, the login page's location picker (`KEYRING_LOCATOR=demo`), signed links into each state of the app (`php artisan example:links`), and an email gallery at `/emails`. None of it reaches an exported kit, and nothing in the app is kept twice, once with the demo and once without. Instead the demo lives in its own places, which the kit's manifest excludes: + +| Where | What | +| ------------------------ | --------------------------------------------------------------------------------------------------------------------- | +| `app/Demo/` | `DemoServiceProvider`, the props it adds to pages (`DemoProps`), its locator, controllers, commands and email gallery | +| `routes/demo.php` | the location picker's route, and the local-only links and email gallery | +| `database/seeders/Demo/` | the two demo accounts and their month of history, seeded in place of `DatabaseSeeder`'s test user | +| `resources/js/demo/` | the demo's welcome page and dashboard, the login page's extras, and the header and sidebar links to this repository | +| `resources/views/demo/` | the email gallery | +| `tests/Feature/Demo/` | the demo's tests | +| `resources/emails/` | the Maizzle sources of the emails, which kits get built (see [Emails](#emails)) | + +The app reaches the demo only through lines tagged `@monorepo-only`, which the export strips: the provider in `bootstrap/providers.php`, `require __DIR__.'/demo.php'` in `routes/web.php`, the `demoAccounts`, `demoSettings` and `demoLocation` props in `WelcomeController`, `DashboardController` and `HandleInertiaRequests`, the `demo` locator in `config/keyring.php` and `.env.example`, the emailed codes `KeyringServiceProvider` registers for it, the demo's extras on the login page and in the header and sidebar, and the page resolver in `resources/js/app.tsx`. That resolver, `resources/js/demo/pages.ts`, takes a page in `resources/js/demo/pages` over the one of the same name in `resources/js/pages`. The demo's welcome page and dashboard render the plain ones with their own content inside (as `children`), and get the plain page's `layout` when they don't set one, so the header, the alerts and the layout are written once. `resources/js/pages.test.tsx` renders the plain ones, as a kit has them. + +The manifest's `forbid` list then names `demo` and `Demo`, and the demo's classes, paths, routes and props, and the export stops if any exported file still has one in its text or its path. A new reference to the demo from shared code has to be tagged, or the export fails. + +## Running it + +```bash +composer install +npm install # the app and every workspace package +cp .env.example .env # Postgres and Redis settings are in here; adjust to taste +php artisan key:generate +php artisan migrate --seed +composer dev # http://localhost:8000 +``` + +`.env.example` here points at a local Postgres on port 5433 and Redis. An exported kit's uses Laravel's defaults instead (SQLite, and the database for the cache). + +The checks CI runs: + +```bash +npm run check # Vite+ lint and format +npm run types:check +npm run build +npm test # the page tests (Vitest, through Vite+) +composer test # Pint, PHPStan and the PHP tests +node --test bin/ # the export script's own tests +``` + +## Exporting a kit + +```bash +node bin/export-kit.mjs inertia-react /tmp/starter-inertia-react +node bin/export-kit.mjs inertia-react /tmp/starter-inertia-react --force # empty it first +node bin/export-kit.mjs inertia-react /tmp/starter-inertia-react --skip-lock # leave the lockfiles as copied +``` + +The output is what the kit's repository gets: a complete Laravel app with no workspace in it. Run `composer install`, `npm ci`, `npm run build`, `npm test` and `composer ci:check` there to try it. The script needs git, npm and composer, and the monorepo's `node_modules` (for the formatter). It: + +1. Copies every file git tracks, as it is in the working tree (so uncommitted changes to tracked files come along, but untracked files never do), except `kits/`, `packages/`, `bin/`, `.github/` and the kit's `exclude` list. Symlinks stay symlinks. +2. Inlines the workspace packages the kit uses: copies their files into the app, rewrites imports of them (`@keyringjs/ui-react/button` becomes `@/components/ui/button` again), and adds their dependencies to `package.json`. +3. Copies the kit's own files over the result. +4. Leaves out text tagged monorepo-only: a line whose comment (`//`, `#`, `/*`, ` + +## Notes on running it Keyring comes from Packagist (`keyring/keyring`) and its browser package from npm (`@keyringjs/keyring`), like in any other app. -```bash -composer install -npm install -cp .env.example .env # Postgres and Redis settings are in here; adjust to taste -php artisan key:generate -php artisan migrate --seed -composer dev # http://localhost:8000 -``` +The app hashes passwords with argon2id (`HASH_DRIVER` in `.env.example`), where Laravel's default is bcrypt. To bring in accounts hashed with bcrypt, say from an app this one replaces, set `HASH_VERIFY=false`, so they're rehashed as they sign in. -The app hashes passwords with argon2id (`HASH_DRIVER` in `.env.example`). If your database has accounts from when it used bcrypt, either set `HASH_VERIFY=false`, so they're rehashed as they sign in, or run `php artisan example:reset`. That command is also how to get the demo accounts' recovery codes in the form Keyring makes them now: older, shorter codes are no longer accepted. + + +This app hashed with bcrypt until it moved to argon2id, so a database from before then needs it. For the demo accounts, `php artisan example:reset` does it too. That command is also how to get their recovery codes in the form Keyring makes them now: older, shorter codes are no longer accepted. + + Keyring clears out old devices, sessions, email changes and log entries with `keyring:prune`, which it adds to Laravel's scheduler itself (daily at 03:00, see `php artisan schedule:list`). It only runs where the scheduler does: `php artisan schedule:work` locally, or the usual cron entry on a server. Passkeys need a secure context. `http://localhost` counts, so open the app as `localhost`, not `127.0.0.1`. `APP_URL` has to match the address in your browser, because Keyring builds the passkey origin and every emailed link from it. -Emails (codes, email change links, security notices) go to `storage/logs/laravel.log`. `composer dev` shows that log as it's written. To see how they look, open `http://localhost:8000/emails` while running locally: a gallery of every email the app sends, Keyring's and Laravel's verification and password reset emails, each with sample content (see [Emails](#emails)). +Emails (codes, email change links, security notices) go to `storage/logs/laravel.log`. `composer dev` shows that log as it's written. + + + +To see how they look, open `http://localhost:8000/emails` while running locally: a gallery of every email the app sends, Keyring's and Laravel's verification and password reset emails, each with sample content (see [Emails](#emails)). + + ## Risk signals @@ -58,11 +251,14 @@ A new country (30) and impossible travel (60) together score 90, so a sign in fr Nothing is located by default. `KEYRING_LOCATOR` in `.env` picks a locator (`config/keyring.php`): ```ini -KEYRING_LOCATOR=demo # a "Pretend to be in" picker on the login page, only when APP_ENV is local or testing KEYRING_LOCATOR=cloudflare # Cloudflare's CF-IPCountry (and city and coordinates) headers ``` -`demo` is `App\Support\DemoLocator`, a demo aid and nothing more: it puts each request wherever the login page's picker says (a cookie, London until you pick), so the location signals can be tried on a machine where every request comes from `127.0.0.1`. Anyone can set that cookie, so it's only taken when `APP_ENV` is `local` or `testing`. Anywhere else `KEYRING_LOCATOR=demo` means no locator, and the picker and its route are gone. Paris after London is a new country, which asks for a second factor. Tokyo or New York straight after is impossible travel too, and the sign in is refused (and logged, and emailed). Locations also show on Settings → Security. + + +The demo has one more, `KEYRING_LOCATOR=demo`: a "Pretend to be in" picker on the login page, only when `APP_ENV` is `local` or `testing`. It's `App\Demo\DemoLocator`, a demo aid and nothing more: it puts each request wherever the login page's picker says (a cookie, London until you pick), so the location signals can be tried on a machine where every request comes from `127.0.0.1`. Anyone can set that cookie, so it's only taken when `APP_ENV` is `local` or `testing`. Anywhere else `KEYRING_LOCATOR=demo` means no locator, and the picker and its route are gone. Paris after London is a new country, which asks for a second factor. Tokyo or New York straight after is impossible travel too, and the sign in is refused (and logged, and emailed). Locations also show on Settings → Security. + + `cloudflare` is Keyring's `HeaderLocator`. Only use it when every request has to come through Cloudflare: anyone who can reach the app directly can send those headers and say where they are. For a real lookup by IP address, see [Locations with stevebauman/location](https://github.com/keyringphp/keyring/blob/main/docs/recipes.md#locations-with-stevebaumanlocation). @@ -82,7 +278,11 @@ Only the first five characters of the password's SHA-1 leave the server. ## Emails -Keyring sends its own emails, and this app gives every one of them its look with [Maizzle](https://maizzle.com): the twelve security notices, the five emails a flow needs, and Laravel's own verification and password reset emails. +Keyring sends its own emails, and this app gives every one of them its look: the twelve security notices, the five emails a flow needs, and Laravel's own verification and password reset emails. Each is two Blade views in `resources/views/emails/keyring`, HTML and plain text, with the logo and icons in `public/images/emails`. + + + +The views are built with [Maizzle](https://maizzle.com), from the templates in `resources/emails`. The kits get the built views without the templates or Maizzle. ``` resources/emails/ @@ -106,15 +306,19 @@ npm run emails:dev # Maizzle's preview server, with hot reload npm run emails:images # redraw the logo and icons after changing the list ``` +`emails:images` draws them in Chromium with Playwright, so it needs `npx playwright install chromium` once. + The templates are Vue files with Tailwind classes. Maizzle inlines the CSS and writes each one out as two Blade views, HTML and plain text, which are committed so the app runs without a build. Anything that changes per email is a Blade variable wrapped in ``, which Maizzle passes through untouched: ```vue {{ $intro }} ``` + + Every email has the same frame: the logo (the app's key, as in the sidebar), a card with an icon and a coloured bar in the email's tone, and a footer saying why it was sent and, for the security emails, who to contact if it wasn't you. Alerts (a new device, unusual activity, a failed second step, a locked account, a copied key) are red or amber, confirmations (a new password, a sign-in method added, a changed email address) green, and the rest indigo. Codes get a large code block, and links a button with the full link under it for mail apps that won't open it. Dark mode follows `prefers-color-scheme` where the mail app supports it. The logo and icons are PNGs, since many mail apps won't show an SVG. -Keyring sends the security notices itself, so the app only gives them their look. One callback in `KeyringServiceProvider` builds every notice from `notice.vue`, and `App\Notifications\Keyring\NoticeMail` picks each notice's tone, icon, label, details (the key's name, the recovery codes left, what the risk signals noticed) and advice: +Keyring sends the security notices itself, so the app only gives them their look. One callback in `KeyringServiceProvider` builds every notice from the `emails.keyring.notice` view, and `App\Notifications\Keyring\NoticeMail` picks each notice's tone, icon, label, details (the key's name, the recovery codes left, what the risk signals noticed) and advice: ```php SecurityNotice::toMailUsing(Notifications\NoticeMail::build(...)); @@ -126,10 +330,16 @@ The five emails a flow needs (the emailed code, the two for an email change, and Blade escapes what the HTML views print, so a name someone typed for their security key can't add a link to a genuine security email. The plain text views print values as they are, since there's no markup to protect. -While developing, [`/emails`](http://localhost:8000/emails) shows a gallery of every email with sample content, grouped into security alerts, confirmations, the emails a flow needs and Laravel's two, with `/emails/{type}` showing one of them and `/emails/{type}/text` its plain text. The pages only exist when `APP_ENV` is `local`. `App\Support\EmailGallery` makes the samples. + + +While developing, [`/emails`](http://localhost:8000/emails) shows a gallery of every email with sample content, grouped into security alerts, confirmations, the emails a flow needs and Laravel's two, with `/emails/{type}` showing one of them and `/emails/{type}/text` its plain text. The pages only exist when `APP_ENV` is `local`. `App\Demo\EmailGallery` makes the samples. + + The logo, icons and links in every email start at `APP_URL` (`Keyring::linkRoot()`), never at the request that caused the email: `asset()` would follow the `Host` header, and anyone asking for a password reset can send a forged one. + + ## Demo accounts | Email | Password | Second step | @@ -152,20 +362,25 @@ php artisan example:links --base=https://your-machine.example:9420 # reached s Each link signs the browser out first, then signs in or starts the sign in as one of the demo accounts. Behind a proxy like `tailscale serve`, set `TRUSTED_PROXIES=127.0.0.1` so the app believes it's on HTTPS. -## What changed from the starter kit + + +## What changed from Laravel's starter kit + +The app started as Laravel's React starter kit, with Fortify taken out and Keyring put in: - `laravel/fortify` and `laravel/chisel` removed. `keyring/keyring` added, with its migrations published. - `App\Models\User` uses `HasKeyring`. Email and password can only change through Keyring's flows. -- `App\Providers\KeyringServiceProvider` turns on every factor, a two-factor policy once someone has a second factor, the `keyring.enrolled` middleware that makes everyone add one, every security email and every risk signal (the breached password one behind a setting). +- `App\Providers\KeyringServiceProvider` turns on every factor but emailed codes (there to uncomment, since they aren't a second factor), a two-factor policy once someone has a second factor, the `keyring.enrolled` middleware that makes everyone add one, every security email and every risk signal (the breached password one behind a setting). - `config/keyring.php` has the features, the page people are sent to for a second factor or a new password (both `/settings/security`), the list of words a password mustn't be made up of, the breached password check and the locator, both picked from `.env`. -- `app/Notifications/Keyring` holds every email Keyring sends, built from the Maizzle templates in `resources/emails`. -- The kit's page names already match Keyring's (`auth/login`, `auth/challenge`…), so only step-up confirmation is remapped, to the challenge page. +- `app/Notifications/Keyring` holds every email Keyring sends, with its views in `resources/views/emails/keyring`. +- Laravel's page names already match Keyring's (`auth/login`, `auth/challenge`…), so only step-up confirmation is remapped, to the challenge page. - New pages: `auth/challenge` (second step and step-up), and the pages emailed links open, each with one button that posts the link's token or signature in the body: `auth/email-change`, `auth/device-report` and `auth/email-verification`. Login gained passkey sign-in, and shows Keyring's message for whatever sent you there. -- A welcome page about the demo instead of Laravel's, a key for a logo, and sidebar links to this repository and Keyring's docs. +- A key for a logo, and a sidebar link to Keyring's docs. +- A welcome page about the demo instead of Laravel's, a dashboard of things to try, sidebar links to this repository, and emailed codes turned on, to show what they are. - Settings → Security lists sign-in methods (the password form opens from the password's row), where you're signed in (devices and sessions, with one "Sign out everywhere else"), and recent activity. It talks to Keyring's JSON routes through `@keyringjs/keyring` (`resources/js/keyring/actions.ts` handles the 423 step-up answer and shows Keyring's own messages). - `HandleInertiaRequests` shares the flashed `status` and its message from `Keyring::statusMessage()`. - Settings → Profile changes the name directly and the email through Keyring's confirmed flow. -- The kit's Fortify tests were rewritten against Keyring (`php artisan test`). +- Laravel's Fortify tests were rewritten against Keyring (`php artisan test`), and `npm test` renders the welcome page and the dashboard. ## OWASP ASVS @@ -186,7 +401,15 @@ Keyring's docs have a page on what to turn on for each level of [OWASP ASVS 5.0. `tests/Feature/KeyringConformanceTest.php` runs Keyring's own conformance suite against this setup. -What a demo can't be, and a real app still has to do: serve over HTTPS (with `SESSION_SECURE_COOKIE=true`, which also gives Keyring's cookies their `__Host-` names), leave out the seeded accounts and their published password, write down its timeouts and its word list, and give administrators a way to end someone's sessions (`php artisan keyring:sign-out`) and a process for someone who has lost every sign-in method. One thing here goes against Level 3 on purpose: email codes are registered, to show what they are. +What configuration can't do, and a real app still has to: serve over HTTPS (with `SESSION_SECURE_COOKIE=true`, which also gives Keyring's cookies their `__Host-` names), write down its timeouts and its word list, and give administrators a way to end someone's sessions (`php artisan keyring:sign-out`) and a process for someone who has lost every sign-in method. + + + +Two things in the demo aren't for a real app: it registers emailed codes, to show what they are, which goes against Level 3, and it seeds two accounts with a published password. + + + + ## Browser tests @@ -224,7 +447,9 @@ Chrome's virtual authenticator attests with a certificate it signs itself and ma `KEYRING_REVEAL_TAKEN=true` is one more setting only the browser tests use. It turns on `keyring.registration.reveal_taken`, for the two pages nobody reaches without it: with it a new user is signed in before verifying their address, sees `auth/verify-email`, and verifies with the button on `auth/email-verification`. -There's no CI yet. +CI doesn't run them yet. They aren't part of the exported kits. + + ## Working on Keyring Itself diff --git a/app/Demo/Console/PrintDemoLinks.php b/app/Demo/Console/PrintDemoLinks.php new file mode 100644 index 0000000..6ec4792 --- /dev/null +++ b/app/Demo/Console/PrintDemoLinks.php @@ -0,0 +1,30 @@ +isLocal(), 1, 'The links only work with APP_ENV=local.'); + + $base = rtrim($this->option('base') ?: config('app.url'), '/'); + $until = now()->addHours((int) $this->option('hours')); + + foreach (DemoStateController::STATES as $state => $about) { + $this->line("{$about}"); + $this->line($base.URL::temporarySignedRoute('demo.state', $until, ['state' => $state], absolute: false)); + $this->newLine(); + } + + $this->comment("The links work until {$until->toDayDateTimeString()} UTC. Each one signs the browser out first."); + } +} diff --git a/app/Demo/Console/ResetDemoAccounts.php b/app/Demo/Console/ResetDemoAccounts.php new file mode 100644 index 0000000..fb0e917 --- /dev/null +++ b/app/Demo/Console/ResetDemoAccounts.php @@ -0,0 +1,23 @@ +whereIn('email', ['demo@keyring.test', '2fa@keyring.test'])->get()->each->delete(); + + $this->call('db:seed', ['--class' => DemoSeeder::class]); + } +} diff --git a/app/Http/Controllers/DemoLocationController.php b/app/Demo/DemoLocationController.php similarity index 92% rename from app/Http/Controllers/DemoLocationController.php rename to app/Demo/DemoLocationController.php index 242d2af..534e324 100644 --- a/app/Http/Controllers/DemoLocationController.php +++ b/app/Demo/DemoLocationController.php @@ -1,8 +1,8 @@ + */ + public static function accounts(): array + { + $url = app(Google2FA::class)->getQRCodeUrl(config('app.name'), '2fa@keyring.test', DemoSeeder::TOTP_SECRET); + $svg = new Writer(new ImageRenderer(new RendererStyle(144, 0), new SvgImageBackEnd))->writeString($url); + + return [ + 'password' => 'password', + 'totpSecret' => DemoSeeder::TOTP_SECRET, + 'recoveryCode' => DemoSeeder::RECOVERY_CODES[0], + // Without the XML declaration, to go straight into the page. + 'totpQr' => trim(substr($svg, strpos($svg, "\n") + 1)), + ]; + } + + /** + * The dashboard's "things to try" cards (DashboardController). A few + * depend on how the app was started, so the cards say which settings + * are on. + * + * @return array + */ + public static function settings(): array + { + return [ + 'locator' => match (config('keyring.devices.locator')) { + NullLocator::class => null, + HeaderLocator::class => 'cloudflare', + DemoLocator::class => 'demo', + default => 'other', + }, + // Sign ins are only checked with BREACHED_PASSWORD_CHECK=true. + // New passwords are also checked by Keyring's default (null) + // in production. + 'breachCheck' => [ + 'signIns' => config('keyring.passwords.uncompromised') === true, + 'newPasswords' => config('keyring.passwords.uncompromised') ?? app()->isProduction(), + ], + // The /emails previews only exist while running locally. + 'emailPreviews' => app()->isLocal(), + ]; + } + + /** + * The login page's "Pretend to be in" picker, shared with every page + * (HandleInertiaRequests), only with the demo locator + * (KEYRING_LOCATOR=demo). + * + * @return array{current: string, places: array}|null + */ + public static function location(Request $request): ?array + { + return DemoLocator::enabled() ? [ + 'current' => DemoLocator::current($request), + 'places' => array_map(fn (array $place) => [ + 'city' => $place['city'], + 'country' => $place['country'], + ], DemoLocator::PLACES), + ] : null; + } +} diff --git a/app/Demo/DemoServiceProvider.php b/app/Demo/DemoServiceProvider.php new file mode 100644 index 0000000..dbda14b --- /dev/null +++ b/app/Demo/DemoServiceProvider.php @@ -0,0 +1,57 @@ +app->bind(DatabaseSeeder::class, DemoSeeder::class); + } + + public function boot(): void + { + // The local-only links into each state of the app (example:links) + // stay open to someone who still has to add a second factor. + // A cached config already has it (config:cache boots the app). + $except = config('keyring.enrollment_except'); + + if (! in_array('demo.state', $except, true)) { + config(['keyring.enrollment_except' => [...$except, 'demo.state']]); + } + + // Not only in the console: the reset link (DemoStateController) runs + // example:reset during a web request. This only registers them for + // when Artisan starts. + $this->commands([ResetDemoAccounts::class, PrintDemoLinks::class]); + } +} diff --git a/app/Http/Controllers/DemoStateController.php b/app/Demo/DemoStateController.php similarity index 99% rename from app/Http/Controllers/DemoStateController.php rename to app/Demo/DemoStateController.php index 18509a8..b9af617 100644 --- a/app/Http/Controllers/DemoStateController.php +++ b/app/Demo/DemoStateController.php @@ -1,6 +1,6 @@ [ - 'locator' => match (config('keyring.devices.locator')) { - NullLocator::class => null, - HeaderLocator::class => 'cloudflare', - DemoLocator::class => 'demo', - default => 'other', - }, - // Sign ins are only checked with BREACHED_PASSWORD_CHECK=true. - // New passwords are also checked by Keyring's default (null) - // in production. - 'breachCheck' => [ - 'signIns' => config('keyring.passwords.uncompromised') === true, - 'newPasswords' => config('keyring.passwords.uncompromised') ?? app()->isProduction(), - ], - // The /emails previews only exist while running locally. - 'emailPreviews' => app()->isLocal(), - ], - ]); + $page = Inertia::render('dashboard'); + $page->with('demoSettings', DemoProps::settings()); // @monorepo-only + + return $page; } } diff --git a/app/Http/Controllers/WelcomeController.php b/app/Http/Controllers/WelcomeController.php index ce42484..c55e27f 100644 --- a/app/Http/Controllers/WelcomeController.php +++ b/app/Http/Controllers/WelcomeController.php @@ -2,35 +2,17 @@ namespace App\Http\Controllers; -use BaconQrCode\Renderer\Image\SvgImageBackEnd; -use BaconQrCode\Renderer\ImageRenderer; -use BaconQrCode\Renderer\RendererStyle\RendererStyle; -use BaconQrCode\Writer; -use Database\Seeders\DatabaseSeeder; +use App\Demo\DemoProps; // @monorepo-only use Inertia\Inertia; use Inertia\Response; -use PragmaRX\Google2FA\Google2FA; class WelcomeController extends Controller { - /** - * The demo's front page: what it is, and the two seeded accounts to sign - * in with. The two-factor account's secret comes as a QR code too, so - * an authenticator app can scan it instead of having it typed in. - */ - public function __invoke(Google2FA $google2fa): Response + public function __invoke(): Response { - $url = $google2fa->getQRCodeUrl(config('app.name'), '2fa@keyring.test', DatabaseSeeder::TOTP_SECRET); - $svg = new Writer(new ImageRenderer(new RendererStyle(144, 0), new SvgImageBackEnd))->writeString($url); + $page = Inertia::render('welcome'); + $page->with('demoAccounts', DemoProps::accounts()); // @monorepo-only - return Inertia::render('welcome', [ - 'demoAccounts' => [ - 'password' => 'password', - 'totpSecret' => DatabaseSeeder::TOTP_SECRET, - 'recoveryCode' => DatabaseSeeder::RECOVERY_CODES[0], - // Without the XML declaration, to go straight into the page. - 'totpQr' => trim(substr($svg, strpos($svg, "\n") + 1)), - ], - ]); + return $page; } } diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index 214065c..ef30ab6 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -2,7 +2,7 @@ namespace App\Http\Middleware; -use App\Support\DemoLocator; +use App\Demo\DemoProps; // @monorepo-only use Illuminate\Http\Request; use Inertia\Middleware; use Keyring\Facades\Keyring; @@ -50,15 +50,7 @@ public function share(Request $request): array 'keyringAlerts' => fn () => $request->session()->get('keyring.alerts', []), // A recovery code has been used, so it's time to make a new set. 'replaceRecoveryCodes' => fn () => (bool) $request->user()?->keyring->shouldReplaceRecoveryCodes(), - // The login page's "Pretend to be in" picker, only with the demo - // locator (KEYRING_LOCATOR=demo). - 'demoLocation' => fn () => DemoLocator::enabled() ? [ - 'current' => DemoLocator::current($request), - 'places' => array_map(fn (array $place) => [ - 'city' => $place['city'], - 'country' => $place['country'], - ], DemoLocator::PLACES), - ] : null, + 'demoLocation' => fn () => DemoProps::location($request), // @monorepo-only 'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true', ]; } diff --git a/app/Notifications/Keyring/LaravelMail.php b/app/Notifications/Keyring/LaravelMail.php index e90d91f..478f51d 100644 --- a/app/Notifications/Keyring/LaravelMail.php +++ b/app/Notifications/Keyring/LaravelMail.php @@ -10,8 +10,8 @@ /** * Laravel's own email verification and password reset emails, which Keyring - * sends during registration and password resets, built from this app's - * Maizzle templates so they match the rest. KeyringServiceProvider hands + * sends during registration and password resets, in this app's email + * views so they match the rest. KeyringServiceProvider hands * these to VerifyEmail::toMailUsing() and ResetPassword::toMailUsing(). * * Each keeps its link as the message's action too, as Laravel's own email diff --git a/app/Notifications/Keyring/NoticeMail.php b/app/Notifications/Keyring/NoticeMail.php index d9fc1d6..bc59419 100644 --- a/app/Notifications/Keyring/NoticeMail.php +++ b/app/Notifications/Keyring/NoticeMail.php @@ -21,8 +21,8 @@ use Keyring\Notifications\SuspiciousActivity; /** - * The email of every security notice Keyring sends, from the one Maizzle - * template `npm run emails` builds into emails.keyring.notice. Keyring says + * The email of every security notice Keyring sends, from the one view, + * emails.keyring.notice. Keyring says * what happened; this gives each notice its look: an icon badge in a tone * (alerts in red or amber, confirmations in green), the details that * matter for it, and what to do if it wasn't you. @@ -69,9 +69,8 @@ public static function build(SecurityNotice $notice, object $notifiable): MailMe /** * How each notice looks. The icon is a badge in public/images/emails - * drawn in the tone, which colours nothing else (see - * resources/emails/images.mjs). A notice of the app's own falls back to - * a plain one. + * drawn in the tone, which colours nothing else. A notice of the app's + * own falls back to a plain one. * * @return array{tone: string, icon: string, advice: string, adviceTitle?: string, intro?: string, nameLabel?: string} */ diff --git a/app/Providers/KeyringServiceProvider.php b/app/Providers/KeyringServiceProvider.php index 1513226..56a92fd 100644 --- a/app/Providers/KeyringServiceProvider.php +++ b/app/Providers/KeyringServiceProvider.php @@ -15,7 +15,7 @@ use Illuminate\Contracts\Http\Kernel; use Illuminate\Support\ServiceProvider; use Keyring\Facades\Keyring; -use Keyring\Factors\EmailCode; +use Keyring\Factors\EmailCode; // @monorepo-only use Keyring\Factors\Password; use Keyring\Factors\RecoveryCodes; use Keyring\Factors\Totp; @@ -37,7 +37,7 @@ class KeyringServiceProvider extends ServiceProvider { public function boot(): void { - // Every way people can sign in to the demo. + // Every way people can sign in. Keyring::factors([ Password::class, WebAuthn::passkeys(), @@ -46,11 +46,12 @@ public function boot(): void // OWASP ASVS 6.5.5 asks. Keyring's default also takes the code // before and the one after, for a phone whose clock is off. fn (Application $app) => $app->make(Totp::class, ['window' => 0]), - // An emailed code is a step at sign in, not a second factor: - // whoever reads the inbox can reset the password too. A password - // and a code is still AAL1, and doesn't count as having a second - // factor. Keyring makes apps opt in, and the demo shows it. - EmailCode::asExtraStep(), + // Off: an emailed code is a step at sign in, not a second factor, + // since whoever reads the inbox can reset the password too. A + // password and a code is still AAL1, and doesn't count as having + // a second factor. Uncomment it to offer one anyway. + // \Keyring\Factors\EmailCode::asExtraStep(), + EmailCode::asExtraStep(), // @monorepo-only (The demo turns it on, to show what it is.) RecoveryCodes::class, ]); @@ -69,9 +70,9 @@ public function boot(): void Keyring::validateEmailChangesUsing(ValidateEmailChange::class); // Keyring sends its own security notices. This app only gives them - // its look: every one is built from one Maizzle template, - // resources/emails/keyring/notice.vue, with a tone, icon and - // details per notice from NoticeMail. + // its look: every one is the one view, emails.keyring.notice, with a + // tone, icon and details per notice from NoticeMail. + // @monorepo-only (The view is built with Maizzle from resources/emails/keyring/notice.vue.) SecurityNotice::toMailUsing(Notifications\NoticeMail::build(...)); // Laravel's own verification and password reset emails, which @@ -82,7 +83,7 @@ public function boot(): void // The five emails a flow needs each have a shape of their own, so // they're this app's classes, in app/Notifications/Keyring, with a // template each. The suspected clone is the one notice Keyring - // leaves off until it's asked for. The demo sends it. + // leaves off until it's asked for. This app sends it. Keyring::notifications([ 'verification_code' => Notifications\VerificationCode::class, 'confirm_email_change' => Notifications\ConfirmEmailChange::class, @@ -125,8 +126,8 @@ public function boot(): void // These two stay quiet until there's a locator (KEYRING_LOCATOR, // see config/keyring.php), so they're always on. A new country // and impossible travel together add up to 90, which refuses - // the sign in: on the demo locator, sign in from London and then - // from Tokyo to see it. + // the sign in. + // @monorepo-only (On the demo locator, sign in from London and then from Tokyo to see it.) NewCountry::class, ImpossibleTravel::class, // CredentialStuffing stays off: it scores failures on other @@ -153,7 +154,7 @@ public function boot(): void } /** - * Any security key, as the demo ships. With SECURITY_KEY_ATTESTATION set, + * Any security key, as the app ships. With SECURITY_KEY_ATTESTATION set, * only keys whose maker vouches for them, and with SECURITY_KEY_MODELS * only those models (see config/security_keys.php). Passkeys are left * alone: the ones that sync have no attestation worth checking. diff --git a/bin/export-kit.mjs b/bin/export-kit.mjs new file mode 100644 index 0000000..e299593 --- /dev/null +++ b/bin/export-kit.mjs @@ -0,0 +1,726 @@ +#!/usr/bin/env node +/** + * Exports one starter kit from this monorepo as a complete, standalone + * Laravel app: the shape `laravel new --using=keyringphp/starter-` + * installs, and what CI pushes to each kit's read-only repository. + * + * node bin/export-kit.mjs [--force] [--skip-lock] + * + * Driven by kits//kit.json. The steps, in order: + * + * 1. Copy every file git tracks, as it is in the working tree, minus the + * monorepo's own tooling and the kit's `exclude` list. Untracked files + * are never exported, and symlinks are copied as symlinks. + * 2. Inline the workspace packages the kit lists under `inline`: copy their + * files into the app, rewrite imports of the package to the app's paths, + * and add the package's dependencies to the app's package.json. + * 3. Copy the kit's `copy` entries over the result (a headless kit's + * frontend, or config that replaces the shared backend's). + * 4. Drop text tagged monorepo-only (see stripMonorepoOnly below), and + * run the files whose imports changed through the kit's `format` + * command (from the monorepo root, which has the node_modules). + * 5. Apply `composer` and `package` to composer.json and package.json as + * JSON merge patches (RFC 7396: null removes a key), and `env` to + * .env.example. + * 6. Prepend the kit's `readme` to the README. + * 7. Refuse to finish while any file still names a workspace package, or + * mentions anything in the kit's `forbid` list, in its text or its path: + * what it leaves out, like the monorepo's demo, which no exported file + * may still reach. + * 8. Update package-lock.json and composer.lock to match, without moving + * any version: packages the kit removed leave the locks, and nothing + * else changes (needs npm and composer; --skip-lock leaves them as + * copied). + */ + +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +const repositoryRoot = path.resolve(import.meta.dirname, '..'); + +// Never part of any kit: the kits' manifests and frontends (a kit copies its +// own), the shared packages (a kit inlines what it uses), the export tooling +// in bin/ and the monorepo's CI. +const MONOREPO_ONLY = ['kits/', 'packages/', 'bin/', '.github/']; + +// The marker, as its own token in a comment: after //, #, /*, |\*\/)/; + +export class ExportError extends Error {} + +function fail(message) { + throw new ExportError(message); +} + +export function listKits(root = repositoryRoot) { + const dir = path.join(root, 'kits'); + + if (!fs.existsSync(dir)) { + return []; + } + + return fs + .readdirSync(dir) + .filter((name) => fs.existsSync(path.join(dir, name, 'kit.json'))) + .sort(); +} + +function readJson(file) { + return JSON.parse(fs.readFileSync(file, 'utf8')); +} + +function writeJson(file, data) { + fs.writeFileSync(file, JSON.stringify(data, null, 4) + '\n'); +} + +/** Whether `file` is `entry`, or inside it when `entry` ends with a slash. */ +function matches(file, entry) { + return entry.endsWith('/') ? file.startsWith(entry) : file === entry; +} + +/** RFC 7396 JSON merge patch, keeping the target's key order. */ +export function mergePatch(target, patch) { + if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { + return patch; + } + + const result = + target !== null && typeof target === 'object' && !Array.isArray(target) + ? { ...target } + : {}; + + for (const [key, value] of Object.entries(patch)) { + if (value === null) { + delete result[key]; + } else { + result[key] = mergePatch(result[key], value); + } + } + + return result; +} + +/** + * Drops what only makes sense in the monorepo: a line whose comment holds + * the marker, and everything from a line whose comment holds the marker + * followed by ":start" through the one with ":end", both included. + */ +export function stripMonorepoOnly(text, file = 'file') { + if (!text.includes('@monorepo-only')) { + return text; + } + + const out = []; + let inBlock = false; + let closed = false; + + for (const line of text.split('\n')) { + const marker = line.match(MARKER); + + if (marker?.[1] === ':start') { + if (inBlock) { + throw new ExportError(`${file}: nested monorepo-only block`); + } + + inBlock = true; + } else if (marker?.[1] === ':end') { + if (!inBlock) { + throw new ExportError( + `${file}: monorepo-only block ends without a start`, + ); + } + + inBlock = false; + closed = true; + } else if (!inBlock && !marker) { + // A block set apart by blank lines leaves one blank line, not two. + if (!(closed && line.trim() === '' && out.at(-1)?.trim() === '')) { + out.push(line); + } + + closed = false; + } + } + + if (inBlock) { + throw new ExportError(`${file}: unclosed monorepo-only block`); + } + + return out.join('\n'); +} + +/** + * Sets each key in .env-style text: a string value becomes KEY=value, and + * { value, commented: true } becomes "# KEY=value", the form Laravel's own + * .env.example uses for the database lines the installer uncomments. A key + * that isn't there yet is added at the end. + */ +export function applyEnv(text, overrides) { + const lines = text.split('\n'); + + for (const [key, spec] of Object.entries(overrides)) { + const { value, commented = false } = + typeof spec === 'string' ? { value: spec } : spec; + const line = `${commented ? '# ' : ''}${key}=${value}`; + const pattern = new RegExp(`^(#\\s*)?${key}=`); + const index = lines.findIndex((existing) => pattern.test(existing)); + + if (index === -1) { + while (lines.length && lines.at(-1) === '') { + lines.pop(); + } + + lines.push(line, ''); + } else { + lines[index] = line; + } + } + + return lines.join('\n'); +} + +/** + * Rewrites module specifiers in quotes or backticks, so static, dynamic and + * template-literal imports and re-exports all move. A rule ending in a slash + * rewrites every specifier starting with it; any other rule only the exact + * specifier. The longest matching rule wins. + */ +export function rewriteImports(text, rules) { + const sorted = Object.entries(rules).sort( + ([a], [b]) => b.length - a.length, + ); + + return text.replace(/(['"`])([^'"`\s]+)\1/g, (match, quote, specifier) => { + for (const [from, to] of sorted) { + if ( + from.endsWith('/') + ? specifier.startsWith(from) + : specifier === from + ) { + return quote + to + specifier.slice(from.length) + quote; + } + } + + return match; + }); +} + +function isText(buffer) { + return !buffer.includes(0); +} + +function lstat(file) { + try { + return fs.lstatSync(file); + } catch { + return null; + } +} + +/** What git tracks, minus files deleted in the working tree. */ +function trackedFiles(root) { + const output = execFileSync('git', ['ls-files', '-z', '--cached'], { + cwd: root, + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024, + }); + + return [...new Set(output.split('\0').filter(Boolean))] + .filter((file) => lstat(path.join(root, file)) !== null) + .sort(); +} + +function copyFile(from, to) { + fs.mkdirSync(path.dirname(to), { recursive: true }); + fs.rmSync(to, { force: true }); + + const stat = fs.lstatSync(from); + + if (stat.isSymbolicLink()) { + fs.symlinkSync(fs.readlinkSync(from), to); + + return; + } + + fs.copyFileSync(from, to); + fs.chmodSync(to, stat.mode); +} + +/** + * Whether `dir` holds an earlier export, so --force may empty it: its + * composer.json carries one of the kits' package names. + */ +function looksLikeExport(dir, root) { + try { + const name = readJson(path.join(dir, 'composer.json')).name; + + return listKits(root).some( + (kit) => + readJson(path.join(root, 'kits', kit, 'kit.json')).composer + ?.name === name, + ); + } catch { + return false; + } +} + +function run(command, args, cwd) { + console.log(` $ ${command} ${args.join(' ')}`); + execFileSync(command, args, { cwd, stdio: 'inherit' }); +} + +/** + * Lists the files whose path or text still contains any of `names`, with + * the name. Binary files and symlinks are only checked by their path. + */ +function findLeftovers(out, files, names) { + const leftovers = []; + + for (const file of files) { + for (const name of names) { + if (file.includes(name)) { + leftovers.push(`${file} (${name}, in its path)`); + } + } + + const target = path.join(out, file); + + if (lstat(target)?.isFile() !== true) { + continue; + } + + const buffer = fs.readFileSync(target); + + if (!isText(buffer)) { + continue; + } + + const text = buffer.toString('utf8'); + + for (const name of names) { + if (text.includes(name)) { + leftovers.push(`${file} (${name})`); + } + } + } + + return leftovers; +} + +export function exportKit({ + root = repositoryRoot, + kit: kitName, + out: outArg, + force = false, + skipLock = false, + log = console.log, +}) { + const manifestPath = path.join(root, 'kits', kitName, 'kit.json'); + + if (!/^[a-z0-9-]+$/.test(kitName) || !fs.existsSync(manifestPath)) { + fail(`no kit called "${kitName}" (kits/${kitName}/kit.json)`); + } + + const kit = { + exclude: [], + forbid: [], + copy: [], + inline: [], + composer: {}, + package: {}, + env: {}, + ...readJson(manifestPath), + }; + + if (kit.name !== kitName) { + fail(`kits/${kitName}/kit.json says its name is "${kit.name}"`); + } + + const out = path.resolve(outArg); + + if ( + out === root || + root.startsWith(out + path.sep) || + out.startsWith(root + path.sep) + ) { + fail('the output directory has to be outside the repository'); + } + + if (fs.existsSync(out) && fs.readdirSync(out).length > 0) { + if (!force) { + fail(`${out} is not empty (--force empties an earlier export)`); + } + + if (!looksLikeExport(out, root)) { + fail( + `${out} doesn't look like an earlier export (no composer.json ` + + "with a kit's name), so --force leaves it alone", + ); + } + + fs.rmSync(out, { recursive: true, force: true }); + } + + fs.mkdirSync(out, { recursive: true }); + + log(`Exporting ${kit.name} to ${out}`); + + // 1. The app itself. + const files = trackedFiles(root); + const skip = [...MONOREPO_ONLY, ...kit.exclude]; + const written = new Set(); + + for (const file of files) { + if (!skip.some((entry) => matches(file, entry))) { + copyFile(path.join(root, file), path.join(out, file)); + written.add(file); + } + } + + // 2. Workspace packages, inlined. + const packagesDir = path.join(root, 'packages'); + const workspaceNames = fs.existsSync(packagesDir) + ? fs + .readdirSync(packagesDir) + .filter((dir) => + fs.existsSync(path.join(packagesDir, dir, 'package.json')), + ) + .map( + (dir) => + readJson(path.join(packagesDir, dir, 'package.json')) + .name, + ) + : []; + + const importRules = {}; + const inlined = new Set(); + const inlinedDependencies = {}; + + for (const entry of kit.inline) { + const sources = files.filter((file) => matches(file, entry.from)); + + if (sources.length === 0) { + fail(`inline: nothing tracked at ${entry.from}`); + } + + for (const file of sources) { + const target = entry.from.endsWith('/') + ? entry.to + file.slice(entry.from.length) + : entry.to; + + if (written.has(target)) { + fail(`inline: ${file} would overwrite the app's ${target}`); + } + + copyFile(path.join(root, file), path.join(out, target)); + written.add(target); + inlined.add(target); + } + + Object.assign(importRules, entry.imports ?? {}); + + const packageDir = path.join( + packagesDir, + path.relative('packages', entry.from).split(path.sep)[0], + ); + const manifest = readJson(path.join(packageDir, 'package.json')); + + if (manifest.name !== entry.package) { + fail( + `inline: ${entry.from} belongs to ${manifest.name}, not ${entry.package}`, + ); + } + + Object.assign(inlinedDependencies, manifest.dependencies ?? {}); + } + + // 3. The kit's own files, over the top. + for (const entry of kit.copy) { + const sources = files.filter( + (file) => + matches(file, entry.from) && + path.basename(file) !== 'kit.json' && + !(entry.exclude ?? []).some((skipped) => + matches(file, skipped), + ), + ); + + if (sources.length === 0) { + fail(`copy: nothing tracked at ${entry.from}`); + } + + for (const file of sources) { + const target = entry.from.endsWith('/') + ? entry.to + file.slice(entry.from.length) + : entry.to; + + copyFile(path.join(root, file), path.join(out, target)); + written.add(target); + } + } + + // 4. Imports of inlined packages, and monorepo-only text. + const rewritten = []; + + for (const file of written) { + const target = path.join(out, file); + + if (lstat(target)?.isFile() !== true) { + continue; + } + + const buffer = fs.readFileSync(target); + + if (!isText(buffer)) { + continue; + } + + const original = buffer.toString('utf8'); + let text = stripMonorepoOnly(original, file); + + if (/\.(c|m)?(j|t)sx?$|\.vue$|\.css$/.test(file)) { + const before = text; + text = rewriteImports(text, importRules); + + if (text !== before && !inlined.has(file)) { + rewritten.push(file); + } + } + + if (text !== original) { + fs.writeFileSync(target, text); + } + } + + // A rewritten import can change how a line wraps, so the files whose + // imports changed go through the kit's formatter. It runs from here, with + // the monorepo's node_modules, since the export has none yet. + if (kit.format && rewritten.length > 0) { + const [command, ...formatArgs] = kit.format; + + execFileSync( + command, + [...formatArgs, ...rewritten.map((file) => path.join(out, file))], + { cwd: root, stdio: ['ignore', 'ignore', 'inherit'] }, + ); + } + + // 5. composer.json, package.json and .env.example. + const composerPath = path.join(out, 'composer.json'); + const composerBefore = readJson(composerPath); + const composerAfter = mergePatch(composerBefore, kit.composer); + const removedPackages = ['require', 'require-dev'].flatMap((section) => + Object.keys(composerBefore[section] ?? {}).filter( + (name) => + !composerAfter.require?.[name] && + !composerAfter['require-dev']?.[name], + ), + ); + + writeJson(composerPath, composerAfter); + + const packagePath = path.join(out, 'package.json'); + const pkg = readJson(packagePath); + + delete pkg.workspaces; + + for (const section of [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + ]) { + for (const name of workspaceNames) { + delete pkg[section]?.[name]; + } + } + + pkg.dependencies ??= {}; + + for (const [name, range] of Object.entries(inlinedDependencies)) { + if (!pkg.dependencies[name] && !pkg.devDependencies?.[name]) { + pkg.dependencies[name] = range; + } + } + + pkg.dependencies = Object.fromEntries( + Object.entries(pkg.dependencies).sort(([a], [b]) => a.localeCompare(b)), + ); + + writeJson(packagePath, mergePatch(pkg, kit.package)); + + const envPath = path.join(out, '.env.example'); + + if (Object.keys(kit.env).length > 0) { + fs.writeFileSync( + envPath, + applyEnv(fs.readFileSync(envPath, 'utf8'), kit.env), + ); + } + + // 6. The README. + if (kit.readme) { + const intro = fs + .readFileSync(path.join(root, kit.readme), 'utf8') + .trimEnd(); + const readmePath = path.join(out, 'README.md'); + const body = fs.existsSync(readmePath) + ? fs.readFileSync(readmePath, 'utf8').trimStart() + : ''; + + fs.writeFileSync(readmePath, `${intro}\n\n${body}`.trimEnd() + '\n'); + written.add('README.md'); + } + + // 7. Nothing may still name a workspace package, in any form: quoted, + // in a template literal, in an unquoted CSS url(), or in prose. Nor may + // anything mention what the kit forbids, in its text or its path: what + // it excluded, which whatever still reaches for would break without. + const exported = [...written].filter( + (file) => !/\.lock$|-lock\.json$/.test(file), + ); + const leftovers = findLeftovers(out, exported, workspaceNames); + + if (leftovers.length > 0) { + fail( + 'these files still name workspace packages, so add an inline ' + + `entry or import rule for them:\n ${leftovers.join('\n ')}`, + ); + } + + const forbidden = findLeftovers(out, exported, kit.forbid); + + if (forbidden.length > 0) { + fail( + "these files still mention what the kit's forbid list leaves " + + 'out, so tag those lines @monorepo-only or exclude the ' + + `files:\n ${forbidden.join('\n ')}`, + ); + } + + for (const file of written) { + const target = path.join(out, file); + + if ( + lstat(target)?.isFile() && + !/\.lock$|-lock\.json$/.test(file) && + fs.readFileSync(target).includes('packages/') + ) { + log( + ` warning: ${file} mentions packages/, which the export doesn't have`, + ); + } + } + + // 8. Lockfiles to match. + if (!skipLock) { + log('Updating the lockfiles'); + run( + 'npm', + [ + 'install', + '--package-lock-only', + '--ignore-scripts', + '--no-audit', + '--no-fund', + ], + out, + ); + + // npm names the lockfile's root after the directory; name it after + // the kit's repository instead, so every export writes the same file. + const lockPath = path.join(out, 'package-lock.json'); + const lock = readJson(lockPath); + lock.name = (kit.repository ?? `starter-${kit.name}`).split('/').pop(); + writeJson(lockPath, lock); + + const lockLeftovers = findLeftovers( + out, + ['package-lock.json'], + workspaceNames, + ); + + if (lockLeftovers.length > 0) { + fail(`package-lock.json still links ${lockLeftovers.join(', ')}`); + } + + run( + 'composer', + [ + 'update', + '--lock', + '--no-install', + '--no-scripts', + '--no-plugins', + '--no-interaction', + ], + out, + ); + + // Packages the kit took out of composer.json leave the lock, with + // whatever only they needed. Nothing else changes version. + if (removedPackages.length > 0) { + run( + 'composer', + [ + 'remove', + '--unused', + '--no-install', + '--no-scripts', + '--no-plugins', + '--no-interaction', + ], + out, + ); + } + } + + log(`Done: ${out}`); + + return out; +} + +function main() { + const args = process.argv.slice(2); + const flags = new Set(args.filter((arg) => arg.startsWith('--'))); + const [kit, out] = args.filter((arg) => !arg.startsWith('--')); + const usage = + 'Usage: node bin/export-kit.mjs [--force] [--skip-lock]\n\n' + + `Kits: ${listKits().join(', ') || '(none)'}`; + + const unknown = [...flags].filter( + (flag) => !['--force', '--skip-lock'].includes(flag), + ); + + if (unknown.length > 0 || !kit || !out) { + if (unknown.length > 0) { + console.error(`export-kit: unknown option ${unknown[0]}\n`); + } + + console.error(usage); + process.exit(1); + } + + try { + exportKit({ + kit, + out, + force: flags.has('--force'), + skipLock: flags.has('--skip-lock'), + }); + } catch (error) { + if (error instanceof ExportError) { + console.error(`export-kit: ${error.message}`); + process.exit(1); + } + + throw error; + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === import.meta.filename) { + main(); +} diff --git a/bin/export-kit.test.mjs b/bin/export-kit.test.mjs new file mode 100644 index 0000000..9378935 --- /dev/null +++ b/bin/export-kit.test.mjs @@ -0,0 +1,511 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { + applyEnv, + ExportError, + exportKit, + mergePatch, + rewriteImports, + stripMonorepoOnly, +} from './export-kit.mjs'; + +void describe('mergePatch', () => { + void test('sets, replaces and removes keys, keeping their order', () => { + const result = mergePatch( + { name: 'a', require: { php: '^8.5', 'laravel/octane': '^2' } }, + { name: 'b', require: { 'laravel/octane': null }, extra: { x: 1 } }, + ); + + assert.deepEqual(result, { + name: 'b', + require: { php: '^8.5' }, + extra: { x: 1 }, + }); + assert.deepEqual(Object.keys(result), ['name', 'require', 'extra']); + }); + + void test('replaces arrays whole', () => { + assert.deepEqual(mergePatch({ a: [1, 2] }, { a: [3] }), { a: [3] }); + }); +}); + +void describe('stripMonorepoOnly', () => { + void test('drops tagged lines and blocks', () => { + const text = [ + 'keep 1', + 'drop // @monorepo-only', + '', + 'drop in block', + '', + 'keep 2', + ].join('\n'); + + assert.equal(stripMonorepoOnly(text), 'keep 1\nkeep 2'); + }); + + void test('leaves one blank line where a block was', () => { + const text = [ + 'a', + '', + '', + 'x', + '', + '', + 'b', + ].join('\n'); + + assert.equal(stripMonorepoOnly(text), 'a\n\nb'); + }); + + void test('refuses an end without a start, and a nested block', () => { + assert.throws( + () => stripMonorepoOnly('x\n// @monorepo-only:end'), + /ends without a start/, + ); + assert.throws( + () => + stripMonorepoOnly( + '# @monorepo-only:start\n# @monorepo-only:start\n# @monorepo-only:end', + ), + /nested/, + ); + }); + + void test('only takes the marker as its own word in a comment', () => { + const text = [ + 'mentions @monorepo-only outside a comment', + '// @monorepo-only:started is not a start', + '// @monorepo-onlyish is not the marker', + '/* @monorepo-only */ dropped, trailing text and all', + ' * @monorepo-only:start', + 'in a block comment', + ' * @monorepo-only:end', + 'kept', + ].join('\n'); + + assert.equal( + stripMonorepoOnly(text), + [ + 'mentions @monorepo-only outside a comment', + '// @monorepo-only:started is not a start', + '// @monorepo-onlyish is not the marker', + 'kept', + ].join('\n'), + ); + }); + + void test('leaves untagged text alone', () => { + assert.equal(stripMonorepoOnly('a\nb\n'), 'a\nb\n'); + }); + + void test('refuses an unclosed block', () => { + assert.throws( + () => stripMonorepoOnly('\nx', 'X.md'), + /X\.md: unclosed/, + ); + }); +}); + +void describe('applyEnv', () => { + void test('sets, comments out and appends keys', () => { + const env = [ + 'APP_URL=http://localhost:8000', + 'DB_CONNECTION=pgsql', + 'DB_HOST=127.0.0.1', + '# CACHE_STORE=redis', + '', + ].join('\n'); + + const result = applyEnv(env, { + APP_URL: 'http://localhost', + DB_CONNECTION: 'sqlite', + DB_HOST: { value: '127.0.0.1', commented: true }, + CACHE_STORE: 'database', + FRONTEND_URL: 'http://localhost:3000', + }); + + assert.equal( + result, + [ + 'APP_URL=http://localhost', + 'DB_CONNECTION=sqlite', + '# DB_HOST=127.0.0.1', + 'CACHE_STORE=database', + 'FRONTEND_URL=http://localhost:3000', + '', + ].join('\n'), + ); + }); + + void test('only matches the whole key', () => { + assert.equal( + applyEnv('REDIS_HOST=1\nDB_HOST=2\n', { DB_HOST: '3' }), + 'REDIS_HOST=1\nDB_HOST=3\n', + ); + }); +}); + +void describe('rewriteImports', () => { + const rules = { + '@keyringjs/theme': './theme.css', + '@keyringjs/ui-react/utils': '@/lib/utils', + '@keyringjs/ui-react/hooks/': '@/hooks/', + '@keyringjs/ui-react/': '@/components/ui/', + }; + + void test('rewrites exact and prefix rules, the longest first', () => { + const source = [ + "import { cn } from '@keyringjs/ui-react/utils';", + 'import { useIsMobile } from "@keyringjs/ui-react/hooks/use-mobile";', + "import { Button } from '@keyringjs/ui-react/button';", + "@import '@keyringjs/theme';", + ].join('\n'); + + assert.equal( + rewriteImports(source, rules), + [ + "import { cn } from '@/lib/utils';", + 'import { useIsMobile } from "@/hooks/use-mobile";', + "import { Button } from '@/components/ui/button';", + "@import './theme.css';", + ].join('\n'), + ); + }); + + void test('rewrites dynamic imports, re-exports and template literals', () => { + const source = [ + "const sheet = await import('@keyringjs/ui-react/sheet');", + "export { cn } from '@keyringjs/ui-react/utils';", + 'const lazy = (name) => import(`@keyringjs/ui-react/${name}`);', + ].join('\n'); + + assert.equal( + rewriteImports(source, rules), + [ + "const sheet = await import('@/components/ui/sheet');", + "export { cn } from '@/lib/utils';", + 'const lazy = (name) => import(`@/components/ui/${name}`);', + ].join('\n'), + ); + }); + + void test('leaves other specifiers alone', () => { + const source = + "import x from '@keyringjs/keyring';\nimport y from '@keyringjs/theme/fonts.css';"; + + assert.equal(rewriteImports(source, rules), source); + }); +}); + +void describe('exportKit', () => { + let tmp; + let root; + + function write(file, contents) { + fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + fs.writeFileSync( + path.join(root, file), + typeof contents === 'string' + ? contents + : JSON.stringify(contents, null, 4) + '\n', + ); + } + + function track() { + execFileSync('git', ['add', '-A', '.'], { cwd: root }); + } + + function exportTo(out, options = {}) { + return exportKit({ + root, + kit: 'demo', + out, + skipLock: true, + log: () => {}, + ...options, + }); + } + + function read(out, file) { + return fs.readFileSync(path.join(out, file), 'utf8'); + } + + before(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'export-kit-test-')); + root = path.join(tmp, 'repo'); + fs.mkdirSync(root); + execFileSync('git', ['init', '-q'], { cwd: root }); + + write('composer.json', { + name: 'fixture/monorepo', + require: { php: '^8.5', 'laravel/octane': '^2.0' }, + }); + write('package.json', { + private: true, + workspaces: ['packages/*', 'kits/*'], + dependencies: { '@fixture/ui': '0.0.0', react: '^19.0.0' }, + }); + write( + '.env.example', + 'APP_URL=http://localhost:8000\nDB_CONNECTION=pgsql\n', + ); + write( + 'README.md', + '\n# Monorepo\n\n\n## The app\n', + ); + write( + 'resources/js/app.ts', + [ + "import { Button } from '@fixture/ui/button';", + "export { cn } from '@fixture/ui/utils';", + 'export const load = (name: string) => import(`@fixture/ui/${name}`);', + '', + ].join('\n'), + ); + write('resources/js/e2e.ts', 'export {};\n'); + write('packages/ui/package.json', { + name: '@fixture/ui', + dependencies: { clsx: '^2.1.1' }, + }); + write( + 'packages/ui/src/components/ui/button.tsx', + "import { cn } from '../../lib/utils';\nexport const Button = cn;\n", + ); + write('packages/ui/src/lib/utils.ts', 'export const cn = () => "";\n'); + write('kits/demo/kit.json', { + name: 'demo', + repository: 'fixture/starter-demo', + readme: 'kits/demo/README.md', + exclude: ['resources/js/e2e.ts'], + inline: [ + { + package: '@fixture/ui', + from: 'packages/ui/src/', + to: 'resources/js/', + imports: { + '@fixture/ui/utils': '@/lib/utils', + '@fixture/ui/': '@/components/ui/', + }, + }, + ], + copy: [{ from: 'kits/demo/cors.php', to: 'config/cors.php' }], + composer: { + name: 'fixture/starter-demo', + require: { 'laravel/octane': null }, + }, + package: { scripts: { dev: 'vite' } }, + env: { APP_URL: 'http://localhost', DB_CONNECTION: 'sqlite' }, + }); + write('kits/demo/README.md', '# Demo kit\n'); + write('kits/demo/cors.php', ' { + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + void test('exports a standalone app', () => { + const out = exportTo(path.join(tmp, 'out')); + + // Tracked files only, minus the monorepo's own and the excluded. + assert.ok(fs.existsSync(path.join(out, 'resources/js/app.ts'))); + assert.ok(!fs.existsSync(path.join(out, 'untracked.txt'))); + assert.ok(!fs.existsSync(path.join(out, 'resources/js/e2e.ts'))); + assert.ok(!fs.existsSync(path.join(out, 'kits'))); + assert.ok(!fs.existsSync(path.join(out, 'packages'))); + assert.ok(fs.lstatSync(path.join(out, 'link.md')).isSymbolicLink()); + + // Inlined, with imports rewritten. + assert.ok(fs.existsSync(path.join(out, 'resources/js/lib/utils.ts'))); + assert.equal( + read(out, 'resources/js/components/ui/button.tsx'), + "import { cn } from '../../lib/utils';\nexport const Button = cn;\n", + ); + assert.equal( + read(out, 'resources/js/app.ts'), + [ + "import { Button } from '@/components/ui/button';", + "export { cn } from '@/lib/utils';", + 'export const load = (name: string) => import(`@/components/ui/${name}`);', + '', + ].join('\n'), + ); + + // Copied, patched and prepended. + assert.equal(read(out, 'config/cors.php'), ' { + write( + 'resources/css/app.css', + '@import url(@fixture/ui/styles.css);\n', + ); + track(); + + try { + assert.throws( + () => exportTo(path.join(tmp, 'leftover')), + (error) => + error instanceof ExportError && + error.message.includes( + 'resources/css/app.css (@fixture/ui)', + ), + ); + } finally { + execFileSync( + 'git', + ['rm', '-q', '--cached', 'resources/css/app.css'], + { + cwd: root, + }, + ); + fs.rmSync(path.join(root, 'resources/css'), { recursive: true }); + } + }); + + void test('refuses a file that still mentions what the kit forbids', () => { + const manifest = JSON.parse( + fs.readFileSync(path.join(root, 'kits/demo/kit.json'), 'utf8'), + ); + write('kits/demo/kit.json', { + ...manifest, + exclude: [...manifest.exclude, 'app/Demo/'], + forbid: ['App\\Demo\\'], + }); + write('app/Demo/Thing.php', ' exportTo(path.join(tmp, 'forbid-leftover')), + (error) => + error instanceof ExportError && + error.message.includes('app/Http/Kept.php (App\\Demo\\)'), + ); + } finally { + write('kits/demo/kit.json', manifest); + execFileSync( + 'git', + ['rm', '-q', '-r', '--cached', 'app/Demo', 'app/Http'], + { cwd: root }, + ); + fs.rmSync(path.join(root, 'app'), { recursive: true }); + track(); + } + }); + + void test('refuses a file whose path has what the kit forbids', () => { + const manifest = JSON.parse( + fs.readFileSync(path.join(root, 'kits/demo/kit.json'), 'utf8'), + ); + write('kits/demo/kit.json', { ...manifest, forbid: ['Demo'] }); + // Nothing in the text, and a binary file is only checked by its path. + write('resources/js/DemoBanner.tsx', 'export {};\n'); + fs.writeFileSync( + path.join(root, 'Demo.png'), + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00]), + ); + track(); + + try { + assert.throws( + () => exportTo(path.join(tmp, 'forbid-path')), + (error) => + error instanceof ExportError && + error.message.includes( + 'resources/js/DemoBanner.tsx (Demo, in its path)', + ) && + error.message.includes('Demo.png (Demo, in its path)'), + ); + } finally { + write('kits/demo/kit.json', manifest); + execFileSync( + 'git', + [ + 'rm', + '-q', + '--cached', + 'resources/js/DemoBanner.tsx', + 'Demo.png', + ], + { cwd: root }, + ); + fs.rmSync(path.join(root, 'resources/js/DemoBanner.tsx')); + fs.rmSync(path.join(root, 'Demo.png')); + track(); + } + }); + + void test('only writes outside the repository', () => { + assert.throws( + () => exportTo(path.join(root, 'build')), + /outside the repository/, + ); + assert.throws(() => exportTo(tmp), /outside the repository/); + }); + + void test('only empties an earlier export with --force', () => { + const other = path.join(tmp, 'other'); + fs.mkdirSync(other); + fs.writeFileSync(path.join(other, 'keep.txt'), 'mine\n'); + + assert.throws(() => exportTo(other), /not empty/); + assert.throws( + () => exportTo(other, { force: true }), + /doesn't look like an earlier export/, + ); + assert.ok(fs.existsSync(path.join(other, 'keep.txt'))); + + const out = path.join(tmp, 'again'); + exportTo(out); + fs.writeFileSync(path.join(out, 'stale.txt'), 'old\n'); + exportTo(out, { force: true }); + assert.ok(!fs.existsSync(path.join(out, 'stale.txt'))); + }); + + void test('refuses a kit name that is not a plain directory name', () => { + assert.throws( + () => exportTo(path.join(tmp, 'bad'), { kit: '../demo' }), + /no kit called/, + ); + }); +}); diff --git a/bootstrap/providers.php b/bootstrap/providers.php index 7fb84c5..40a0a9f 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -1,9 +1,11 @@ [ + // @monorepo-only (The browser tests turn it on, for the two pages nobody reaches without it: the "check your inbox" page and the one the emailed link opens for a signed-in user.) 'reveal_taken' => (bool) env('KEYRING_REVEAL_TAKEN', false), ], @@ -85,9 +84,8 @@ 'enrollment_url' => '/settings/security', - // The pages anyone can open stay open to them meanwhile, and so do the - // local-only links into each state of the app (example:links). - 'enrollment_except' => ['home', 'well-known.passkeys', 'demo.state'], + // The pages anyone can open stay open to them meanwhile. + 'enrollment_except' => ['home', 'well-known.passkeys'], /* |-------------------------------------------------------------------------- @@ -166,19 +164,21 @@ | Cloudflare: anyone who can reach the app directly can send those | headers themselves and say where they are. | - | "demo" is for playing with on your own machine, never for a real app. - | It puts every request wherever the login page's "Pretend to be in" - | picker says (London until you pick), so you can travel from London to - | Tokyo in a minute and watch the sign in get refused. Anyone can say - | where they are with it, so it's only taken when APP_ENV is local or - | testing: anywhere else, KEYRING_LOCATOR=demo means no locator. - | */ 'devices' => [ 'locator' => match (env('KEYRING_LOCATOR')) { 'cloudflare' => HeaderLocator::class, + // @monorepo-only:start + // "demo" is for playing with on your own machine, never for a + // real app. It puts every request wherever the login page's + // "Pretend to be in" picker says (London until you pick), so you + // can travel from London to Tokyo in a minute and watch the sign + // in get refused. Anyone can say where they are with it, so it's + // only taken when APP_ENV is local or testing: anywhere else, + // KEYRING_LOCATOR=demo means no locator. 'demo' => in_array(env('APP_ENV'), DemoLocator::ENVIRONMENTS, true) ? DemoLocator::class : NullLocator::class, + // @monorepo-only:end default => NullLocator::class, }, ], @@ -188,7 +188,7 @@ | Security Key Attestation |-------------------------------------------------------------------------- | - | The demo takes any security key. With SECURITY_KEY_ATTESTATION set (see + | The app takes any security key. With SECURITY_KEY_ATTESTATION set (see | config/security_keys.php) it only takes keys whose maker vouches for | them, and these are the makers' root certificates it trusts: full paths | to PEM files, separated by commas. diff --git a/config/security_keys.php b/config/security_keys.php index c4c662c..540cbfd 100644 --- a/config/security_keys.php +++ b/config/security_keys.php @@ -7,7 +7,7 @@ | Attestation |-------------------------------------------------------------------------- | - | Off, the demo takes any security key. On, a new key has to prove who + | Off, the app takes any security key. On, a new key has to prove who | made it: KeyringServiceProvider adds requireAttestation() to the | security key factor, and Keyring only takes keys whose certificates | chain to a root in keyring.webauthn.attestation_roots. diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index d66bab5..84c101f 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -4,60 +4,20 @@ use App\Models\User; use Illuminate\Database\Seeder; -use Keyring\Models\Authenticator; +// @monorepo-only (App\Demo\DemoServiceProvider runs Demo\DemoSeeder in this one's place) class DatabaseSeeder extends Seeder { /** - * The authenticator app secret for the two-factor demo account. Add it to - * any authenticator app. + * Seed the application's database. */ - public const TOTP_SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'; - - /** - * In the form Keyring makes them: 26 base32 characters (a-z and 2-7), - * typed with or without the dashes. Anything shorter is refused. - */ - public const RECOVERY_CODES = [ - 'demo-code-aaaa-aaaa-aaaa-aaaa-aa', - 'demo-code-bbbb-bbbb-bbbb-bbbb-bb', - 'demo-code-cccc-cccc-cccc-cccc-cc', - 'demo-code-dddd-dddd-dddd-dddd-dd', - ]; - public function run(): void { - // Password only. Everyone needs a second factor here, so signing in - // lands on Settings → Security until a passkey, a security key or an - // authenticator app is added. Both accounts are verified (the factory - // sees to that): an unverified one can't sign in at all. - User::factory()->create([ - 'name' => 'Demo User', - 'email' => 'demo@keyring.test', - ]); + // User::factory(10)->create(); - // Already has an authenticator app and recovery codes, so signing in - // asks for a second step. They're dated a month back: Keyring only - // lets a second factor stand in for the old address's confirmation - // of an email change once the account has had it a while - // (keyring.email_changes.established_after, a week by default). - $user = User::factory()->create([ - 'name' => 'Two-Factor User', - 'email' => '2fa@keyring.test', - ]); - - $established = ['created_at' => now()->subMonth()]; - - // Last used for yesterday's sign in in ActivitySeeder's history. - Authenticator::factory()->totp(self::TOTP_SECRET)->default()->for($user, 'authenticatable')->create([...$established, 'last_used_at' => now()->subDay()->setTime(10, 20)]); - Authenticator::factory()->recoveryCodes(self::RECOVERY_CODES)->for($user, 'authenticatable')->create($established); - - // A month of sign ins and changes for Settings → Security to show. - (new ActivitySeeder)->run($user); - - $this->command?->table(['Account', 'Password', 'Second factor'], [ - ['demo@keyring.test', 'password', 'none yet: signing in asks for one to be added'], - ['2fa@keyring.test', 'password', 'TOTP secret '.self::TOTP_SECRET.', recovery codes '.implode(' ', self::RECOVERY_CODES)], + User::factory()->create([ + 'name' => 'Test User', + 'email' => 'test@example.com', ]); } } diff --git a/database/seeders/ActivitySeeder.php b/database/seeders/Demo/ActivitySeeder.php similarity index 99% rename from database/seeders/ActivitySeeder.php rename to database/seeders/Demo/ActivitySeeder.php index 78b61d7..99d9a53 100644 --- a/database/seeders/ActivitySeeder.php +++ b/database/seeders/Demo/ActivitySeeder.php @@ -1,6 +1,6 @@ create([ + 'name' => 'Demo User', + 'email' => 'demo@keyring.test', + ]); + + // Already has an authenticator app and recovery codes, so signing in + // asks for a second step. They're dated a month back: Keyring only + // lets a second factor stand in for the old address's confirmation + // of an email change once the account has had it a while + // (keyring.email_changes.established_after, a week by default). + $user = User::factory()->create([ + 'name' => 'Two-Factor User', + 'email' => '2fa@keyring.test', + ]); + + $established = ['created_at' => now()->subMonth()]; + + // Last used for yesterday's sign in in ActivitySeeder's history. + Authenticator::factory()->totp(self::TOTP_SECRET)->default()->for($user, 'authenticatable')->create([...$established, 'last_used_at' => now()->subDay()->setTime(10, 20)]); + Authenticator::factory()->recoveryCodes(self::RECOVERY_CODES)->for($user, 'authenticatable')->create($established); + + // A month of sign ins and changes for Settings → Security to show. + (new ActivitySeeder)->run($user); + + $this->command?->table(['Account', 'Password', 'Second factor'], [ + ['demo@keyring.test', 'password', 'none yet: signing in asks for one to be added'], + ['2fa@keyring.test', 'password', 'TOTP secret '.self::TOTP_SECRET.', recovery codes '.implode(' ', self::RECOVERY_CODES)], + ]); + } +} diff --git a/kits/inertia-react/README.md b/kits/inertia-react/README.md new file mode 100644 index 0000000..b9d9b77 --- /dev/null +++ b/kits/inertia-react/README.md @@ -0,0 +1,36 @@ +# Keyring starter kit: Inertia + React + +A Laravel starter kit with [Keyring](https://github.com/keyringphp/keyring) for sign in, passkeys, second factors, sessions and security emails, and an Inertia and React frontend. + +This repository is built from [keyringphp/example](https://github.com/keyringphp/example) on every release and is read-only: send issues and pull requests there. + +## What's in it + +- A welcome page with links to log in and register, and a dashboard to build on. +- Every auth page: log in (with a password, a passkey from the email field's autofill or its own button), register, verify an email address, forgot and reset password, the second step of a sign in, and step-up confirmation. +- Settings: Profile (the name, and the email address through Keyring's confirmed change), Security (sign-in methods, the password, devices and sessions, and recent activity) and Appearance. +- Keyring's emails, and Laravel's verification and password reset emails, in one look. +- Everyone needs a second factor (a passkey, a security key or an authenticator app): until they've added one, every page sends them to Settings → Security. `App\Providers\KeyringServiceProvider` sets that up, with the factors, the risk signals and the emails. + +The UI uses the app's name, `APP_NAME` in `.env`. + +## Install + +```bash +laravel new my-app --using=keyringphp/starter-inertia-react +cd my-app +composer dev # http://localhost:8000 +``` + +Or without the Laravel installer: + +```bash +composer create-project keyringphp/starter-inertia-react my-app +cd my-app +npm install && npm run build +composer dev +``` + +Either way you get a `.env` with an app key and a migrated SQLite database. `php artisan db:seed` adds a test user, `test@example.com` with the password `password`, who is asked to add a second factor at their first sign in. + +`APP_URL` in `.env` has to be the address you open the app at: Keyring builds the passkey origin and every emailed link from it. `laravel new my-app` sets it (to `http://my-app.test` under Herd or Valet, `http://localhost:8000` otherwise), and `composer create-project` sets `http://localhost:8000`, where `composer dev` serves. After `laravel new .`, or to serve the app anywhere else, set it yourself. diff --git a/kits/inertia-react/components.json b/kits/inertia-react/components.json new file mode 100644 index 0000000..4a304d0 --- /dev/null +++ b/kits/inertia-react/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "resources/css/app.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "iconLibrary": "lucide" +} diff --git a/kits/inertia-react/kit.json b/kits/inertia-react/kit.json new file mode 100644 index 0000000..7e28455 --- /dev/null +++ b/kits/inertia-react/kit.json @@ -0,0 +1,130 @@ +{ + "name": "inertia-react", + "repository": "keyringphp/starter-inertia-react", + "readme": "kits/inertia-react/README.md", + "exclude": [ + "tests/e2e/", + "playwright.config.ts", + "config/octane.php", + "app/Demo/", + "routes/demo.php", + "database/seeders/Demo/", + "resources/js/demo/", + "resources/views/demo/", + "tests/Feature/Demo/", + "resources/emails/", + "maizzle.config.js" + ], + "forbid": [ + "demo", + "Demo", + "App\\Demo\\", + "Database\\Seeders\\Demo\\", + "@/demo/", + "routes/demo.php", + "/demo.php", + "resources/js/demo", + "resources/views/demo", + "demo.state", + "demo-location", + "demoAccounts", + "demoSettings", + "demoLocation", + "DemoLocator", + "example:reset", + "example:links", + "resources/emails", + "maizzle", + "Maizzle", + "keyring.test", + "Keyring Example" + ], + "copy": [ + { + "from": "kits/inertia-react/components.json", + "to": "components.json" + } + ], + "format": ["npx", "--no-install", "vp", "fmt"], + "inline": [ + { + "package": "@keyringjs/theme", + "from": "packages/theme/theme.css", + "to": "resources/css/theme.css", + "imports": { + "@keyringjs/theme": "./theme.css" + } + }, + { + "package": "@keyringjs/ui-react", + "from": "packages/ui-react/src/", + "to": "resources/js/", + "imports": { + "@keyringjs/ui-react/utils": "@/lib/utils", + "@keyringjs/ui-react/hooks/": "@/hooks/", + "@keyringjs/ui-react/": "@/components/ui/" + } + } + ], + "composer": { + "name": "keyringphp/starter-inertia-react", + "require": { + "bacon/bacon-qr-code": null, + "laravel/octane": null + }, + "description": "A Laravel starter kit with Keyring for sign in, passkeys, second factors and sessions, and an Inertia and React frontend.", + "keywords": [ + "laravel", + "starter-kit", + "keyring", + "inertia", + "react", + "passkeys" + ], + "support": { + "issues": "https://github.com/keyringphp/example/issues", + "source": "https://github.com/keyringphp/example" + } + }, + "package": { + "scripts": { + "test:browser": null, + "test:browser:octane": null, + "emails": null, + "emails:dev": null, + "emails:images": null + }, + "devDependencies": { + "@playwright/test": null, + "@maizzle/framework": null, + "playwright": null + } + }, + "env": { + "APP_NAME": "Laravel", + "APP_URL": "http://localhost", + "DB_CONNECTION": "sqlite", + "DB_HOST": { + "value": "127.0.0.1", + "commented": true + }, + "DB_PORT": { + "value": "3306", + "commented": true + }, + "DB_DATABASE": { + "value": "laravel", + "commented": true + }, + "DB_USERNAME": { + "value": "root", + "commented": true + }, + "DB_PASSWORD": { + "value": "", + "commented": true + }, + "CACHE_STORE": "database", + "MAIL_FROM_ADDRESS": "\"hello@example.com\"" + } +} diff --git a/package-lock.json b/package-lock.json index 96d1745..4169b23 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,39 +4,28 @@ "requires": true, "packages": { "": { + "workspaces": [ + "packages/*", + "kits/*" + ], "dependencies": { + "@inertiajs/core": "^3.0.0", "@inertiajs/react": "^3.0.0", "@inertiajs/vite": "^3.0.0", "@keyringjs/keyring": "^0.1.1", - "@radix-ui/react-avatar": "^1.1.3", - "@radix-ui/react-checkbox": "^1.1.4", - "@radix-ui/react-collapsible": "^1.1.3", - "@radix-ui/react-dialog": "^1.1.6", - "@radix-ui/react-dropdown-menu": "^2.1.6", - "@radix-ui/react-label": "^2.1.2", - "@radix-ui/react-navigation-menu": "^1.2.5", - "@radix-ui/react-select": "^2.1.6", - "@radix-ui/react-separator": "^1.1.2", - "@radix-ui/react-slot": "^1.2.3", - "@radix-ui/react-toggle": "^1.1.2", - "@radix-ui/react-toggle-group": "^1.1.2", - "@radix-ui/react-tooltip": "^1.1.8", + "@keyringjs/theme": "0.0.0", + "@keyringjs/ui-react": "0.0.0", "@tailwindcss/vite": "^4.1.11", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@vitejs/plugin-react": "^6.1.1", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", "concurrently": "^10.0.3", - "input-otp": "^1.4.2", "laravel-vite-plugin": "^3.0.0", "lucide-react": "^0.475.0", "react": "^19.2.0", "react-dom": "^19.2.0", "sonner": "^2.0.0", - "tailwind-merge": "^3.0.1", "tailwindcss": "^4.0.0", - "tw-animate-css": "^1.4.0", "typescript": "^5.7.2", "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0" }, @@ -47,6 +36,7 @@ "@rolldown/plugin-babel": "^0.2.3", "@types/node": "^22.13.5", "babel-plugin-react-compiler": "^1.0.0", + "playwright": "^1.65.0", "vite-plus": "1.4.0" }, "optionalDependencies": { @@ -657,6 +647,14 @@ } } }, + "node_modules/@keyringjs/theme": { + "resolved": "packages/theme", + "link": true + }, + "node_modules/@keyringjs/ui-react": { + "resolved": "packages/ui-react", + "link": true + }, "node_modules/@laravel/multiplex": { "version": "0.4.5", "resolved": "https://registry.npmjs.org/@laravel/multiplex/-/multiplex-0.4.5.tgz", @@ -10802,6 +10800,44 @@ "type": "github", "url": "https://github.com/sponsors/wooorm" } + }, + "packages/theme": { + "name": "@keyringjs/theme", + "version": "0.0.0", + "dependencies": { + "tw-animate-css": "^1.4.0" + }, + "peerDependencies": { + "tailwindcss": "^4.0.0" + } + }, + "packages/ui-react": { + "name": "@keyringjs/ui-react", + "version": "0.0.0", + "dependencies": { + "@radix-ui/react-avatar": "^1.1.3", + "@radix-ui/react-checkbox": "^1.1.4", + "@radix-ui/react-collapsible": "^1.1.3", + "@radix-ui/react-dialog": "^1.1.6", + "@radix-ui/react-dropdown-menu": "^2.1.6", + "@radix-ui/react-label": "^2.1.2", + "@radix-ui/react-navigation-menu": "^1.2.5", + "@radix-ui/react-select": "^2.1.6", + "@radix-ui/react-separator": "^1.1.2", + "@radix-ui/react-slot": "^1.2.3", + "@radix-ui/react-toggle": "^1.1.2", + "@radix-ui/react-toggle-group": "^1.1.2", + "@radix-ui/react-tooltip": "^1.1.8", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "input-otp": "^1.4.2", + "lucide-react": "^0.475.0", + "tailwind-merge": "^3.0.1" + }, + "peerDependencies": { + "react": "^19.2.0", + "react-dom": "^19.2.0" + } } } } diff --git a/package.json b/package.json index 373096b..444ad02 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,10 @@ { "$schema": "https://www.schemastore.org/package.json", "private": true, + "workspaces": [ + "packages/*", + "kits/*" + ], "type": "module", "scripts": { "build": "vp build", @@ -9,6 +13,7 @@ "check": "vp check", "check:fix": "vp check --fix", "types:check": "tsc --noEmit", + "test": "vp test", "emails": "maizzle build", "emails:dev": "maizzle serve", "test:browser": "playwright test", @@ -16,38 +21,23 @@ "emails:images": "node resources/emails/images.mjs" }, "dependencies": { + "@inertiajs/core": "^3.0.0", "@inertiajs/react": "^3.0.0", "@inertiajs/vite": "^3.0.0", "@keyringjs/keyring": "^0.1.1", - "@radix-ui/react-avatar": "^1.1.3", - "@radix-ui/react-checkbox": "^1.1.4", - "@radix-ui/react-collapsible": "^1.1.3", - "@radix-ui/react-dialog": "^1.1.6", - "@radix-ui/react-dropdown-menu": "^2.1.6", - "@radix-ui/react-label": "^2.1.2", - "@radix-ui/react-navigation-menu": "^1.2.5", - "@radix-ui/react-select": "^2.1.6", - "@radix-ui/react-separator": "^1.1.2", - "@radix-ui/react-slot": "^1.2.3", - "@radix-ui/react-toggle": "^1.1.2", - "@radix-ui/react-toggle-group": "^1.1.2", - "@radix-ui/react-tooltip": "^1.1.8", + "@keyringjs/theme": "0.0.0", + "@keyringjs/ui-react": "0.0.0", "@tailwindcss/vite": "^4.1.11", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@vitejs/plugin-react": "^6.1.1", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", "concurrently": "^10.0.3", - "input-otp": "^1.4.2", "laravel-vite-plugin": "^3.0.0", "lucide-react": "^0.475.0", "react": "^19.2.0", "react-dom": "^19.2.0", "sonner": "^2.0.0", - "tailwind-merge": "^3.0.1", "tailwindcss": "^4.0.0", - "tw-animate-css": "^1.4.0", "typescript": "^5.7.2", "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0" }, @@ -58,6 +48,7 @@ "@rolldown/plugin-babel": "^0.2.3", "@types/node": "^22.13.5", "babel-plugin-react-compiler": "^1.0.0", + "playwright": "^1.65.0", "vite-plus": "1.4.0" }, "optionalDependencies": { diff --git a/packages/theme/fonts.css b/packages/theme/fonts.css new file mode 100644 index 0000000..bed58fb --- /dev/null +++ b/packages/theme/fonts.css @@ -0,0 +1,8 @@ +/* + * Inter from Bunny Fonts, for kits that don't load it themselves. Import it + * before the theme, since a CSS @import has to come first: + * + * @import '@keyringjs/theme/fonts.css'; + * @import '@keyringjs/theme'; + */ +@import url('https://fonts.bunny.net/css?family=inter:400,500,600,700&display=swap'); diff --git a/packages/theme/package.json b/packages/theme/package.json new file mode 100644 index 0000000..5fd1975 --- /dev/null +++ b/packages/theme/package.json @@ -0,0 +1,21 @@ +{ + "name": "@keyringjs/theme", + "version": "0.0.0", + "private": true, + "description": "Keyring starter kits' Tailwind v4 theme: palette, shadcn tokens, dark mode and fonts.", + "type": "module", + "exports": { + ".": { + "style": "./theme.css", + "default": "./theme.css" + }, + "./theme.css": "./theme.css", + "./fonts.css": "./fonts.css" + }, + "dependencies": { + "tw-animate-css": "^1.4.0" + }, + "peerDependencies": { + "tailwindcss": "^4.0.0" + } +} diff --git a/packages/theme/theme.css b/packages/theme/theme.css new file mode 100644 index 0000000..2293a9f --- /dev/null +++ b/packages/theme/theme.css @@ -0,0 +1,328 @@ +/* + * Keyring starter kits' theme: Tailwind v4, the palette, the shadcn tokens, + * dark mode and the font stack. Dark mode follows a `dark` class on any + * ancestor (usually ). The font stack starts with Inter, which the app + * loads itself. + * @monorepo-only:start + * + * Every kit, React or Vue, imports this one file from its own stylesheet and + * adds its @source lines after it: + * + * @import '@keyringjs/theme'; + * @source '../views'; + * + * The Inertia kit loads Inter with laravel-vite-plugin's Bunny fonts. A kit + * without that can import '@keyringjs/theme/fonts.css' before this file. + * @monorepo-only:end + */ +@import 'tailwindcss'; + +@import 'tw-animate-css'; + +@custom-variant dark (&:is(.dark *)); + +/* + * The palette is entity/ui's: a warm gray, a blue accent, and deep-gray for + * dark mode. The shadcn tokens further down map onto it, so every component + * picks it up. + */ +@theme { + --font-sans: + 'Inter', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', + 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; + + --radius-lg: var(--radius); + --radius-md: calc(var(--radius) - 2px); + --radius-sm: calc(var(--radius) - 4px); + + --color-gray-50: oklch(98.26% 0.002 67); + --color-gray-100: oklch(96.87% 0.002 15.1); + --color-gray-150: oklch(95.42% 0.003 38.5); + --color-gray-200: oklch(92.22% 0.006 42.8); + --color-gray-250: oklch(89.17% 0.006 42.9); + --color-gray-300: oklch(85.95% 0.008 36.2); + --color-gray-350: oklch(83.62% 0.006 42.9); + --color-gray-400: oklch(79.58% 0.006 30.5); + --color-gray-450: oklch(74.66% 0.004 38.8); + --color-gray-500: oklch(61.31% 0.005 33.9); + --color-gray-550: oklch(54.44% 0.004 16.6); + --color-gray-600: oklch(43.65% 0.003 48.3); + --color-gray-700: oklch(34.13% 0.002 67.5); + --color-gray-750: oklch(30.08% 0.002 106.8); + --color-gray-800: oklch(25.3% 0.001 16.5); + --color-gray-900: oklch(20.58% 0.002 16.7); + --color-gray-950: oklch(17.42% 0.002 16.8); + + --color-deep-gray-500: #4a4b50; + --color-deep-gray-600: #3b3c40; + --color-deep-gray-700: #313338; + --color-deep-gray-800: #28292e; + --color-deep-gray-850: #232529; + --color-deep-gray-900: #1f2024; + --color-deep-gray-950: #1a1b1f; + --color-deep-gray-975: #17181c; + --color-deep-gray-1000: #131417; + + --color-accent-0: oklch(0.971 0.01 264); + --color-accent-50: oklch(0.9 0.035 264); + --color-accent-100: oklch(0.83 0.072 264); + --color-accent-200: oklch(0.74 0.105 265); + --color-accent-300: oklch(0.677 0.135 265); + --color-accent-400: oklch(0.62 0.15 266); + --color-accent-500: oklch(0.564 0.152 266); + --color-accent-600: oklch(0.501 0.14 267); + --color-accent-700: oklch(0.429 0.125 268); + --color-accent-800: oklch(0.351 0.1 270); + --color-accent-900: oklch(0.268 0.072 271); + + --ease-out-quart: cubic-bezier(0.165, 0.84, 0.44, 1); + --ease-out-quint: cubic-bezier(0.23, 1, 0.32, 1); +} + +/* Tokens that change with the theme, so the utilities read the variables. */ +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + + --color-primary: var(--primary); + --color-primary-hover: var(--primary-hover); + --color-primary-foreground: var(--primary-foreground); + + --color-secondary: var(--secondary); + --color-secondary-hover: var(--secondary-hover); + --color-secondary-foreground: var(--secondary-foreground); + + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + + --color-destructive: var(--destructive); + --color-destructive-hover: var(--destructive-hover); + --color-destructive-foreground: var(--destructive-foreground); + + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + + /* Surfaces: the ground under the panel, a tinted well, a raised control and a field. */ + --color-ground: var(--ground); + --color-tint: var(--tint); + --color-raised: var(--raised); + --color-field: var(--field); + + --color-chart-1: var(--chart-1); + --color-chart-2: var(--chart-2); + --color-chart-3: var(--chart-3); + --color-chart-4: var(--chart-4); + --color-chart-5: var(--chart-5); + + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); + + /* Elevation: a fine ring plus a short, crisp drop. Dark mode swaps the ring for a solid outline. */ + --shadow-raised: var(--elevation-raised); + --shadow-card: var(--elevation-card); + --shadow-panel: var(--elevation-panel); + --shadow-inset: var(--elevation-inset); + --shadow-field: var(--elevation-field); + --shadow-popover: var(--elevation-popover); + --shadow-dialog: var(--elevation-dialog); + --shadow-primary: var(--elevation-primary); + --shadow-danger: var(--elevation-danger); +} + +:root { + --background: #ffffff; + --foreground: var(--color-gray-950); + --card: #ffffff; + --card-foreground: var(--color-gray-950); + --popover: #ffffff; + --popover-foreground: var(--color-gray-950); + --primary: var(--color-accent-500); + --primary-hover: var(--color-accent-600); + --primary-foreground: #ffffff; + --secondary: var(--color-gray-100); + --secondary-hover: var(--color-gray-150); + --secondary-foreground: var(--color-gray-950); + --muted: var(--color-gray-100); + /* gray-550 rather than entity/ui's gray-500, which misses 4.5:1 on white. */ + --muted-foreground: var(--color-gray-550); + --accent: var(--color-gray-100); + --accent-foreground: var(--color-gray-950); + --destructive: oklch(61.93% 0.207 31.5); + --destructive-hover: oklch(55% 0.19 31.5); + --destructive-foreground: oklch(52% 0.18 31.6); + --border: var(--color-gray-200); + --input: var(--color-gray-250); + --ring: var(--color-accent-500); + --ground: var(--color-gray-50); + --tint: var(--color-gray-50); + --raised: #ffffff; + --field: #ffffff; + --chart-1: oklch(0.646 0.222 41.116); + --chart-2: oklch(0.6 0.118 184.704); + --chart-3: oklch(0.398 0.07 227.392); + --chart-4: oklch(0.828 0.189 84.429); + --chart-5: oklch(0.769 0.188 70.08); + --radius: 0.625rem; + --sidebar: var(--color-gray-50); + --sidebar-foreground: var(--color-gray-600); + --sidebar-primary: var(--color-gray-950); + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: oklch(92.22% 0.006 42.8 / 0.5); + --sidebar-accent-foreground: var(--color-gray-950); + --sidebar-border: var(--color-gray-200); + --sidebar-ring: var(--color-accent-500); + + --elevation-raised: + 0 0 0 1px oklch(17.42% 0.002 16.8 / 0.09), + 0 1px 2px 0 oklch(17.42% 0.002 16.8 / 0.08); + --elevation-card: + 0 0 0 1px oklch(25.3% 0.001 16.5 / 0.08), + 0 1px 2px 0 oklch(17.42% 0.002 16.8 / 0.05), + 0 4px 8px -4px oklch(17.42% 0.002 16.8 / 0.06); + --elevation-panel: + 0 0 0 1px oklch(25.3% 0.001 16.5 / 0.06), + 0 1px 3px 0 oklch(17.42% 0.002 16.8 / 0.05); + --elevation-inset: + inset 0 0 0 1px var(--color-gray-150), + 0 1px 2px 0 oklch(17.42% 0.002 16.8 / 0.04); + --elevation-field: + 0 0 0 1px oklch(17.42% 0.002 16.8 / 0.1), + 0 1px 2px 0 oklch(17.42% 0.002 16.8 / 0.06); + --elevation-popover: + 0 0 0 1px rgb(39 44 48 / 0.08), 0 4px 8px 0 rgb(39 44 48 / 0.1), + 0 14px 40px 0 rgb(39 44 48 / 0.06); + --elevation-dialog: + 0 0 0 1px rgb(1 33 57 / 0.12), 0 0 0 7px rgb(255 255 255 / 0.3), + 0 10px 13px 0 rgb(0 0 0 / 0.06), 0 17px 17px 0 rgb(0 0 0 / 0.05), + 0 28px 20px 0 rgb(0 0 0 / 0.03); + --elevation-primary: + inset 0 1px 0 0 rgb(255 255 255 / 0.18), + 0 0 0 1px var(--color-accent-600), + 0 1px 2px 0 oklch(0.268 0.072 271 / 0.3); + --elevation-danger: + inset 0 1px 0 0 rgb(255 255 255 / 0.18), 0 0 0 1px oklch(55% 0.19 31.5), + 0 1px 2px 0 oklch(34% 0.09 31.6 / 0.3); + + /* The soft wash behind hero and header cards. */ + --wash-1: oklch(0.93 0.045 264 / 0.75); + --wash-2: oklch(0.95 0.04 200 / 0.45); + --auth-glow: var(--color-accent-300); +} + +.dark { + --background: var(--color-deep-gray-975); + --foreground: oklch(0.96 0.003 270); + --card: var(--color-deep-gray-900); + --card-foreground: oklch(0.96 0.003 270); + --popover: var(--color-deep-gray-850); + --popover-foreground: oklch(0.96 0.003 270); + --primary: var(--color-accent-500); + --primary-hover: var(--color-accent-400); + --primary-foreground: #ffffff; + --secondary: var(--color-deep-gray-800); + --secondary-hover: var(--color-deep-gray-700); + --secondary-foreground: oklch(0.96 0.003 270); + --muted: var(--color-deep-gray-850); + --muted-foreground: oklch(0.7 0.008 270); + --accent: var(--color-deep-gray-800); + --accent-foreground: oklch(0.96 0.003 270); + --destructive: oklch(58% 0.19 29); + --destructive-hover: oklch(63% 0.19 29); + --destructive-foreground: oklch(0.74 0.15 27); + --border: var(--color-deep-gray-700); + --input: var(--color-deep-gray-600); + --ring: var(--color-accent-300); + --ground: var(--color-deep-gray-1000); + --tint: var(--color-deep-gray-950); + --raised: var(--color-deep-gray-800); + --field: var(--color-deep-gray-1000); + --chart-1: oklch(0.488 0.243 264.376); + --chart-2: oklch(0.696 0.17 162.48); + --chart-3: oklch(0.769 0.188 70.08); + --chart-4: oklch(0.627 0.265 303.9); + --chart-5: oklch(0.645 0.246 16.439); + --sidebar: var(--color-deep-gray-1000); + --sidebar-foreground: oklch(0.76 0.006 270); + --sidebar-primary: oklch(0.96 0.003 270); + --sidebar-primary-foreground: var(--color-deep-gray-1000); + --sidebar-accent: rgb(255 255 255 / 0.04); + --sidebar-accent-foreground: oklch(0.96 0.003 270); + --sidebar-border: var(--color-deep-gray-700); + --sidebar-ring: var(--color-accent-300); + + --elevation-raised: + 0 0 0 0.5px var(--color-deep-gray-500), 0 1px 2px 0 rgb(0 0 0 / 0.5); + --elevation-card: + 0 0 0 0.5px var(--color-deep-gray-700), 0 1px 2px 0 rgb(0 0 0 / 0.5), + 0 4px 8px -4px rgb(0 0 0 / 0.4); + --elevation-panel: + 0 0 0 0.5px var(--color-deep-gray-800), 0 1px 2px 0 rgb(0 0 0 / 0.5); + --elevation-inset: inset 0 0 0 0.5px var(--color-deep-gray-700); + --elevation-field: + 0 0 0 0.5px var(--color-deep-gray-600), + inset 0 1px 2px 0 rgb(0 0 0 / 0.3); + --elevation-popover: + 0 0 0 0.5px var(--color-deep-gray-600), 0 4px 8px -4px rgb(0 0 0 / 0.6), + 0 14px 40px 0 rgb(0 0 0 / 0.35); + --elevation-dialog: + 0 0 0 0.5px var(--color-deep-gray-600), + 0 0 0 7px rgb(255 255 255 / 0.03), 0 24px 48px -12px rgb(0 0 0 / 0.7); + --elevation-primary: + inset 0 1px 0 0 rgb(255 255 255 / 0.16), + 0 0 0 0.5px var(--color-accent-400), 0 1px 2px 0 rgb(0 0 0 / 0.5); + --elevation-danger: + inset 0 1px 0 0 rgb(255 255 255 / 0.16), 0 0 0 0.5px oklch(63% 0.19 29), + 0 1px 2px 0 rgb(0 0 0 / 0.5); + + --wash-1: oklch(0.42 0.11 266 / 0.32); + --wash-2: oklch(0.4 0.06 200 / 0.18); + --auth-glow: var(--color-accent-800); +} + +/* A soft colour wash, top left, for hero and header cards. */ +@utility bg-wash { + background-image: + radial-gradient(90% 120% at 0% 0%, var(--wash-1) 0%, transparent 60%), + radial-gradient(70% 90% at 100% 0%, var(--wash-2) 0%, transparent 65%); +} + +/* The sign-in pages' backdrop: blue at the top, fading to the page. */ +@utility bg-auth-backdrop { + background-color: var(--background); + background-image: radial-gradient( + 125% 125% at 50% 90%, + var(--background) 40%, + var(--auth-glow) 100% + ); +} + +@layer base { + * { + @apply border-border; + } + + html { + font-synthesis: none; + text-rendering: optimizeLegibility; + } + + body { + @apply bg-background text-foreground; + } +} diff --git a/packages/ui-react/package.json b/packages/ui-react/package.json new file mode 100644 index 0000000..78cf637 --- /dev/null +++ b/packages/ui-react/package.json @@ -0,0 +1,37 @@ +{ + "name": "@keyringjs/ui-react", + "version": "0.0.0", + "private": true, + "description": "The shadcn/ui primitives every React starter kit shares: no router or Inertia imports.", + "type": "module", + "sideEffects": false, + "exports": { + "./utils": "./src/lib/utils.ts", + "./hooks/*": "./src/hooks/*.ts", + "./*": "./src/components/ui/*.tsx" + }, + "dependencies": { + "@radix-ui/react-avatar": "^1.1.3", + "@radix-ui/react-checkbox": "^1.1.4", + "@radix-ui/react-collapsible": "^1.1.3", + "@radix-ui/react-dialog": "^1.1.6", + "@radix-ui/react-dropdown-menu": "^2.1.6", + "@radix-ui/react-label": "^2.1.2", + "@radix-ui/react-navigation-menu": "^1.2.5", + "@radix-ui/react-select": "^2.1.6", + "@radix-ui/react-separator": "^1.1.2", + "@radix-ui/react-slot": "^1.2.3", + "@radix-ui/react-toggle": "^1.1.2", + "@radix-ui/react-toggle-group": "^1.1.2", + "@radix-ui/react-tooltip": "^1.1.8", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "input-otp": "^1.4.2", + "lucide-react": "^0.475.0", + "tailwind-merge": "^3.0.1" + }, + "peerDependencies": { + "react": "^19.2.0", + "react-dom": "^19.2.0" + } +} diff --git a/resources/js/components/ui/alert.tsx b/packages/ui-react/src/components/ui/alert.tsx similarity index 98% rename from resources/js/components/ui/alert.tsx rename to packages/ui-react/src/components/ui/alert.tsx index a155fa0..e83a29b 100644 --- a/resources/js/components/ui/alert.tsx +++ b/packages/ui-react/src/components/ui/alert.tsx @@ -1,7 +1,7 @@ import { cva, type VariantProps } from "class-variance-authority" import * as React from "react" -import { cn } from "@/lib/utils" +import { cn } from "../../lib/utils" const alertVariants = cva( "relative w-full rounded-xl px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start inset-ring [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current", diff --git a/resources/js/components/ui/avatar.tsx b/packages/ui-react/src/components/ui/avatar.tsx similarity index 96% rename from resources/js/components/ui/avatar.tsx rename to packages/ui-react/src/components/ui/avatar.tsx index 5a6986a..b88f8a2 100644 --- a/resources/js/components/ui/avatar.tsx +++ b/packages/ui-react/src/components/ui/avatar.tsx @@ -1,7 +1,7 @@ import * as AvatarPrimitive from "@radix-ui/react-avatar" import * as React from "react" -import { cn } from "@/lib/utils" +import { cn } from "../../lib/utils" function Avatar({ className, diff --git a/resources/js/components/ui/badge.tsx b/packages/ui-react/src/components/ui/badge.tsx similarity index 98% rename from resources/js/components/ui/badge.tsx rename to packages/ui-react/src/components/ui/badge.tsx index 23c1433..4bac29b 100644 --- a/resources/js/components/ui/badge.tsx +++ b/packages/ui-react/src/components/ui/badge.tsx @@ -2,7 +2,7 @@ import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import * as React from "react" -import { cn } from "@/lib/utils" +import { cn } from "../../lib/utils" /* * Soft pills: a tint of the colour, its text in a deeper shade and a fine diff --git a/resources/js/components/ui/breadcrumb.tsx b/packages/ui-react/src/components/ui/breadcrumb.tsx similarity index 98% rename from resources/js/components/ui/breadcrumb.tsx rename to packages/ui-react/src/components/ui/breadcrumb.tsx index d3749b0..c1955df 100644 --- a/resources/js/components/ui/breadcrumb.tsx +++ b/packages/ui-react/src/components/ui/breadcrumb.tsx @@ -2,7 +2,7 @@ import { Slot } from "@radix-ui/react-slot" import { ChevronRight, MoreHorizontal } from "lucide-react" import * as React from "react" -import { cn } from "@/lib/utils" +import { cn } from "../../lib/utils" function Breadcrumb({ ...props }: React.ComponentProps<"nav">) { return