52 Commits
Author SHA1 Message Date
surtic86andClaude Opus 5 e051aa1aec Release 2.2.0
linter / quality (push) Successful in 58s
tests / ci (8.5) (push) Successful in 3m11s
docker / build-and-push (push) Successful in 7m10s
docker / test (8.5) (push) Successful in 3m10s
docker / release (push) Successful in 3s
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-19 06:13:04 +02:00
surtic86andClaude Opus 5 4530298398 Cut over-engineering found by a repo-wide audit
docker / test (8.5) (push) Successful in 3m10s
linter / quality (push) Successful in 1m5s
tests / ci (8.5) (push) Successful in 3m9s
docker / build-and-push (push) Successful in 21m5s
docker / release (push) Skipped
- Config: auth, services, logging, queue and database only repeated the
  framework's own files and are gone; the others keep only the keys that
  differ (app version, cache serializable_classes, session cookie name,
  Markdown mail theme, the shares disk, three Octane values, Livewire's
  pagination theme and payload guards).
- Email verification is removed: User never implemented MustVerifyEmail,
  so it was never enforced, and SealShare has a single admin and no
  registration. CreateNewUser goes with it.
- FileEncryptionService::encryptFile() and generateSalt() were only used
  by tests; tests build files with encryptTestFile() in tests/Pest.php.
- The expiration options are defined once, as Share::EXPIRATIONS. "30 Days"
  now lasts 30 days instead of a calendar month, and Admin settings only
  save a default expiration that is one of the options.
- One-caller helpers are inlined, the uploader reads chunk responses with
  XHR's responseType, and starter-kit leftovers are removed.
- Docker: PHP reads the PHP_* limits from the environment itself
  (${VAR:-default} in uploads.ini); both entrypoints stop writing the ini.
  docker-compose.yml shares the app and scheduler variables through one
  anchor. The dev image installs gd for the screenshot publisher and fake
  test images.
- Development runs in Docker only: the composer dev script, concurrently,
  laravel/pail, laravel/sail, autoprefixer and the shell-quote override
  are gone.
- phpunit.xml forces the test environment with <server> entries, so tests
  run in the dev container no longer use its real database.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 23:14:33 +02:00
surtic86andClaude Opus 5 a62edbcefb Update PHP and npm dependencies
Patch releases of laravel/boost, pestphp/pest, phpunit/phpunit and
filp/whoops, plus refreshed transitive npm packages. Boost's update
refreshed its laravel-best-practices skill.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 22:24:01 +02:00
surtic86andClaude Opus 5 026912f98a Run development on the production stack with a Vite dev server
docker-compose.dev.yml extends docker-compose.yml, so development runs the
scheduler too, and takes its settings from .env, which selects the file
through COMPOSE_FILE. The dev image is a stage of the Dockerfile and shares
the production image's PHP extensions; the app listens on port 80 as in
production.

A vite service runs the dev server with hot reload. No ports are published:
OrbStack serves https://app.sealshare.orb.local and
https://vite.sealshare.orb.local, with the ports pinned by label. Without
OrbStack, docker-compose.ports.yml publishes APP_PORT and VITE_PORT on
127.0.0.1. vite.config.js takes the dev server's address from
VITE_DEV_SERVER_URL and listens on IPv4 and IPv6, as OrbStack's proxy
connects over either.

Each start installs Composer packages, clears caches, migrates and links
storage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 22:17:36 +02:00
surtic86andClaude Opus 5 9bb144577b Stop reporting the scheduler container as unhealthy
The scheduler inherited the image's healthcheck, which asks the web server
that only the app container runs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 22:17:35 +02:00
surtic86andClaude Opus 5 0e362447db Name the npm package so the lock file stops flipping
Without a name, npm writes the folder's name into package-lock.json: "app" in
the dev container, "SealShare" on the host, so every install changed the file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 22:17:35 +02:00
surtic86andClaude Opus 5 82eeacea28 Show the SealShare version and links on the admin dashboard
A quiet line under the shares card reads "SealShare 2.1.0 · Release
notes · Website · Made by noNameWEB": the release notes link goes to the
installed version's Gitea release, the others to sealshare.nonameweb.ch
and nonameweb.ch, each in a new tab. It is page chrome, not content, so
it is a footer line rather than a card.

The image has neither .git nor CHANGELOG.md, so the version is a
constant in config/app.php, bumped with each release. AppVersionTest
fails while it differs from the newest released heading in
CHANGELOG.md, so a forgotten bump stops CI before the tag's image is
built. CHANGELOG (Unreleased) notes it.

The dashboard screenshots are unchanged: the line sits below their fold.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 21:13:19 +02:00
Andreas Reinhold / reiniandClaude Opus 5 5d9e72fd06 Move onto livewire-material 2.2.0 and choose the material pagination theme
Set pagination_theme explicitly now that the package would otherwise take
it over itself; boost:update refreshed the package's guideline and skill.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 16:53:03 +02:00
Andreas Reinhold / reiniandClaude Opus 5 5658ac148c Drop the Tailwind framing from a stale comment in app.css
The recovery-codes pulse comment still explained itself against
Tailwind's animate-pulse, which left the stack in 2.0.0. The reason
stands on its own: the package keeps no keyframe utility for a pulse
loop, so the loading state animates on the effects spring instead.

config/livewire.php:237 stays on Livewire's own "tailwind" default:
SealShare still installs livewire-material ^2.0 from Gitea, whose
vendor copy has no `pagination::material` view yet, so pointing
pagination_theme at it now would break pagination. The package takes
the theme over itself once 2.2.0 is tagged and pulled.
DesignLanguageTest carried no Tailwind wording to update.

Full suite (322) and Pint green, unchanged — run against the old
vendor copy, so the guard's new undeclared-class check is not
exercised here yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 21:23:47 +02:00
Andreas Reinhold / reiniandClaude Opus 5 845bf062ed Let the dashboard's sort dropdown span the shares card
The sort select above the admin dashboard's shares list was capped at
20rem by the admin-shares-sort wrapper. The wrapper and its rule in
app.css are gone, so the select stretches with the card's stack like
the other fields. CHANGELOG (Unreleased) notes it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:38:11 +02:00
Andreas Reinhold / reiniandClaude Opus 5 e057cada3d Count a share's download limit per recipient, not per file
With a download limit of 1, downloading one file of a share with
several files deleted the share and the files not yet downloaded.
ShareService::recordDownload() ran at the end of every download
request, one file or the ZIP alike, and deleted the share as soon as
download_count reached max_downloads. It has worked that way since
the first commit.

- One recipient's visit is one download. The first file or ZIP a
  session downloads is counted when it starts, in one conditional
  UPDATE that also checks the limit, so two recipients starting at
  once can't both take the last download. The session remembers the
  time, and for ShareService::DOWNLOAD_WINDOW_MINUTES (60) it may
  start more downloads of the share without counting them, even once
  the limit is reached. The claim happens in the controller before
  streaming, because the session is saved before the body is sent,
  and after the share key is resolved, so a request without the key
  uses nothing.
- A share at its limit is closed to everyone else at once. The hourly
  cleanup deletes it 24 hours after shares.last_downloaded_at (new
  column), since a ZIP opens each file only when it reaches it and a
  large download can outlast the hour.
- The download page of a limited share says how many downloads are
  left, switches to "You have 1 hour" on the first press (Alpine, as
  a download link does not render the page again), and shows the time
  left on the next visit.
- The admin dashboard shows "2 of 3 downloads", marks shares at their
  limit "Download limit reached" and leaves them out of Active Shares.
- Tests: the regression (3 files, limit 1: every file and the ZIP
  download, counted once), another recipient, the end of the hour,
  the last download going to one of two recipients, requests refused
  before streaming, unlimited shares, the page notes in PHP and in
  Chromium, the dashboard, and the cleanup at 23 and 25 hours. The
  tests of recordDownload() and of the instant deletion are gone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:35:13 +02:00
Andreas Reinhold / reiniandClaude Opus 5 c1906d2009 Stop the SQLite volume from hiding new migrations
Uploads on share.kadenpartner.ch failed with 409 on every chunk after
the update to 2.1. The example docker-compose.yml mounts the SQLite
volume over all of /app/database. Docker fills a volume from the image
only when it is created, so the container kept the 2.0 migrations and
never saw the 2.1 one. share_files.uploaded_chunks was never created,
so the chunk endpoint read null and answered 409. SQLite takes the
unknown "completed_at" in whereNull() as a string, so nothing failed
earlier.

- The image keeps a copy of its migrations in docker/migrations. On
  startup the entrypoint adds the ones missing from database/migrations
  before migrating, so installs with the old mount recover by pulling
  the new image.
- docker-compose.example.yml and docker-compose.yml mount
  sealshare_database at /app/database/sqlite and set DB_DATABASE to the
  file in it. An existing volume can be moved there without losing
  data: its database.sqlite lands at exactly that path.
- Tested with a locally built image: a volume created by 2.0.1 with the
  old mount gets the migration once (not again on restart) and keeps
  its settings; the same volume moved to the new path keeps its data;
  a fresh volume with the new layout starts healthy.
- README and CHANGELOG (Unreleased) describe the new path and how to
  switch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 10:53:27 +02:00
Andreas Reinhold / reiniandClaude Opus 5 7ffc1c1ead Give the website the app's Material 3 look
docker / test (8.5) (push) Successful in 3m29s
linter / quality (push) Successful in 1m21s
tests / ci (8.5) (push) Successful in 3m27s
docker / build-and-push (push) Successful in 7m38s
docker / release (push) Skipped
The site's tokens now carry the app's --md-sys-* names, with shape,
elevation, motion, state, type and spacing values copied from Livewire
Material 2.1 and the colours from the indigo profile, including its
high-contrast light and dark values for prefers-contrast: more. Cards
are outlined, the gallery uses a connected button group instead of
segmented buttons, buttons use M3 Expressive sizes, state layers and
pressed shapes, and layouts follow the M3 window classes with logical
properties. A Light/Dark/System toggle in the nav sets data-theme
before the first paint, and no text is dimmed with opacity.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 22:58:24 +02:00
Andreas Reinhold / reiniandClaude Opus 5 1bcb868897 Describe SealShare 2.1 on the website
The site now says files are encrypted in the browser and sent in chunks,
describes the password generator and its admin settings, explains why
uploads need HTTPS and how to serve it, and replaces the old PHP upload
cap with the admin's file size limits and the chunk size. The alt texts
and captions match the retaken screenshots. The README no longer lists
Tailwind CSS, and the website rules describe the encryption and the
copied colours accurately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 22:37:21 +02:00
Andreas Reinhold / reiniandClaude Opus 5 e833647768 Show the password generator in the website's screenshots
The desktop upload shot fills the password with Generate, and the share
created shot now comes from creating that share, so the password is
offered beside the link. The created share takes a fixed token, so its
link and QR code read the same on every run, and is deleted before the
dashboard shot, which no longer counts the unfinished upload in its disk
usage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 22:33:26 +02:00
Andreas Reinhold / reiniandClaude Opus 5 eb25631799 Release 2.1.0
linter / quality (push) Successful in 1m4s
tests / ci (8.5) (push) Successful in 3m24s
docker / build-and-push (push) Successful in 7m6s
docker / test (8.5) (push) Successful in 3m30s
docker / release (push) Successful in 4s
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 21:52:04 +02:00
Andreas Reinhold / reiniandClaude Opus 5 c552ee9f9d Update PHP and npm dependencies
Everything stays within its existing constraint: Laravel 13.32, Livewire
4.4.5, Livewire Material 2.1.0, Pest 5.2, Boost 2.9, Pint 1.32.1, Vite
8.3 and autoprefixer 10.6. Boost's copy of the guidelines and skills
follows Livewire Material 2.1, which is plain CSS without utilities.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 21:52:04 +02:00
Andreas Reinhold / reiniandClaude Opus 5 5853f1f7d6 Give every page the share pages' layout, at one width
The pages were built five ways: two layouts, seven widths from 28 to
64rem and four heading styles. Every page now looks like the share
pages: a centred heading over one 40rem column of outlined cards, with
the floating toolbar below.

- <x-page> (components/page.blade.php) is the root of every page. It
  draws the h1 and its line (`brand` takes the site's logo, title and
  description from Admin settings), an optional `mark` and `navigation`
  slot, then the content. It has no width prop: every page is the same
  <x-pane width="narrow">.
- The sign-in, password reset, confirm, verify email, two-factor
  challenge, setup and system password pages move onto layouts/app with
  the brand heading and their form in a card titled with the task.
  layouts/auth, auth-header and the settings heading partial are gone,
  and so is the per-page width CSS.
- Settings put their section nav under the heading; the admin pages get
  a description line each. FileUploader and ShareDownload no longer pass
  the branding to their views.
- The admin dashboard's table needed about 49rem, so its shares are a
  list: created above the token, which opens the share, then files,
  size, downloads and expiry on two lines that wrap instead of clipping,
  and one delete button. A "Sort by" select replaces the column headers
  (newest, oldest, expiring soonest with never-expiring last, largest,
  most downloads, most files) and resets the page. The stats stay two
  by two. table.css and sort-header.css are no longer imported.
- Branding hints in Admin settings name every page the title shows on.
- Tests: PageTemplateTest renders every page once and checks one page
  template, one h1 and the width, and the brand heading with its
  fallbacks. FrameTest measures the page column instead of the auth
  card and the 64rem main; dashboard tests follow the list and the sort
  select, including expiry order. .ai/rules/views.md records <x-page>,
  the CHANGELOG notes the change and the website screenshots are
  regenerated.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 21:42:04 +02:00
Andreas Reinhold / reiniandClaude Opus 5 40e35bab0e Encrypt uploads in the browser and send them in chunks
A 6 GB upload kept a customer waiting long after its progress bar
reached 100%. The server wrote every upload three times: PHP's
temporary file, Livewire's copy of it ("Processing files...") and the
encrypted file ("Create Share Link"), each a full rewrite of a slow
disk. The unencrypted copy also stayed behind in livewire-tmp.

Now the uploader's browser encrypts each file in 16 MB chunks with
WebCrypto and PUTs them one at a time; the server checks each chunk in
memory and writes it once, already encrypted. Creating the share only
wraps its key and saves the options. A 200 MB upload through the
Docker image took 2.8 s, and its download matched byte for byte.

- SEALCHK2: a 19-byte header (chunk size, 7-byte nonce prefix), then
  ciphertext and tag per chunk. Each nonce holds the chunk index and a
  last-chunk flag (the STREAM construction), so cut or reordered files
  fail to decrypt. SEALCHK1 and the single-block format still read.
- Envelope encryption: one random key per share. With a password it is
  wrapped with Argon2id (sodium, libsodium's interactive limits) in
  shares.wrapped_key, which names its parameters. Password shares from
  before keep their PBKDF2-derived key.
- The upload page registers each selection with FileUploader into a
  pending share of its own, lists the files with their progress, retries
  a failed chunk after 1-16 s, then offers Retry; Remove and Cancel
  abort. UploadChunkController only accepts chunks from the session that
  started the share: a repeat is acknowledged, a skip gets 409 with the
  count stored. Chunks go out as Blobs, which Chromium sends about eight
  times faster than ArrayBuffers.
- Uploads need a secure context: over plain HTTP the page says HTTPS is
  needed and takes no files. The Docker image gains AUTO_HTTPS, which
  serves Let's Encrypt on 443 for SERVER_NAME and redirects 80; without
  it the container stays on HTTP 80 behind a proxy. docker/Caddyfile was
  never loaded and is gone; docker/healthcheck.sh covers both modes.
- "Download all" streams the ZIP with maennchen/zipstream-php (STORE,
  ZIP64) instead of decrypting whole files into memory and writing the
  archive unencrypted to /tmp.
- Pending shares count towards the quota, stay out of the admin
  dashboard and 404 everywhere else. shares:cleanup deletes uploads idle
  for 4 hours and Livewire temporary files older than that.
- PHP's upload limits no longer cap the admin's max file size and
  default to 64M; LIVEWIRE_MAX_UPLOAD_TIME is gone and
  UPLOAD_CHUNK_SIZE_MB is new.
- Tests cover the format, key wrapping, registration limits, the chunk
  endpoint's answers, completing a share, the streamed ZIP, cleanup,
  and in Chromium a real chunked upload and the HTTPS warning; the
  selected-files overflow test runs again. README, website, CHANGELOG
  and .ai/rules follow.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 20:49:17 +02:00
Andreas Reinhold / reiniandClaude Opus 5 504971ad7f Generate share passwords and offer them again beside the new link
Uploaders no longer have to make up a share password. With "Password
protect" on, the upload page has Generate and Copy under the field, and
the page the upload leads to offers the password once more beside the
link: masked, with the same copy button at the end of the field as the
link's. The password also derives the share's encryption key and only
its hash is stored, so a lost one means files nobody can open.

- PasswordGeneratorService draws from Random\Randomizer's secure engine.
  Characters are drawn uniformly and redrawn until every chosen set
  appears; passphrases come from EFF's large word list (CC BY 3.0 US,
  credited in the README), without its four hyphenated words.
- Admin settings gain a "Share Passwords" card: mode (off, on request,
  prefilled as protection is switched on), kind (characters: length
  12–64, the sets, look-alikes left out; passphrase: 4–10 words and a
  separator), and an example with its estimated entropy that follows the
  form before saving. Fields the chosen mode or kind hides are excluded
  from validation and keep their saved value. The default is on
  request, 20 letters and numbers without look-alikes.
- FileUploader flashes the password encrypted with the share's token;
  ShareCreated shows it only when the token matches, so a reload or any
  other visitor sees nothing. Crypt covers installs without
  SESSION_ENCRYPT, which the Docker setup does not set.
- The symbol set leaves out what chat apps turn into formatting and
  what breaks inside quotes, so a pasted password arrives unchanged.
- app.css imports group.css for <x-group>; .ai/rules/views.md records
  that <x-group> drops data-test and other attributes.
- Tests cover the generator, the admin card's saving, validation and
  example, prefill and generate on the upload page, the flash, and in
  Chromium Generate and Copy on the upload page and the masked copy on
  the share page. The admin settings page now has six headed sections.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 11:00:11 +02:00
Andreas Reinhold / reiniandClaude Opus 5 a88a052d9a Move onto Livewire Material 2.0.0 and leave Tailwind behind
Livewire Material 2.0.0 aligns every component with Material 3
Expressive and carries no Tailwind anywhere, so SealShare drops
tailwindcss and its Vite plugin and writes its views in the package's
vocabulary: layout components (<x-pane>, <x-stack>, <x-row>, <x-grid>,
<x-form>) with M3's spacing tokens, the md-type-*/md-ink-* text classes,
and --md-sys-* tokens in its own small stylesheet.

- resources/css/app.css opens with the package's layer order, imports
  foundation.css and the stylesheet of each component the views render,
  then the scheme, regenerated with the 2025 colour rules at M3's three
  contrast levels. The app's own rules follow, one section per view,
  on tokens and on M3's breakpoints (600/840/1200/1600px) only.
- Every view is rewritten in that vocabulary while SealShare keeps the
  shape it had: the admin table, the admin settings, the recovery codes,
  the share options and the download page are cards, and their fields
  fill them rather than stopping at the 40rem bound a card already
  bounds. The user settings pages became cards too, to match the
  admin's, each with the sections that stand apart from its one subject
  — deleting the account, the recovery codes — in a card beside it.
  Material 3 decides how a component behaves, not whether a container
  survives: buttons keep their label's width, a form's actions end it,
  and each heading level keeps one type role.
- The layouts clear the floating toolbar by the --material-bottom-toolbar
  the package publishes, and the snackbar clears it by itself.
- The two-factor setup QR code comes from QrCodeService, so it keeps a
  white field and quiet zone in the dark theme and still scans.
- Browse Files is a real button that opens the file input, reachable
  and visibly focused from the keyboard.
- Tests: the design test scans views, JS, CSS and app/ and checks the
  CSS entry both ways (no missing, no unused import). New Chromium
  suites cover the frame, settings and admin, the share flow, and every
  page at M3's breakpoint edges (599/600, 839/840, 1199/1200, 1600px).
  The package's renamed data-md-* hooks replace the 1.x ones.
- Boost's update brings the material-3 guideline and skill and drops
  the Tailwind skill.

composer.json requires nonameweb/livewire-material ^2.0 from the Gitea
repository, resolved at the 2.0.0 tag. The CHANGELOG records the move as
2.1.0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 22:30:51 +02:00
Andreas Reinhold / reiniandClaude Opus 5 461bc23f0a Fix the Docker image not starting: update Livewire Material to 1.1.1
tests / ci (8.5) (push) Successful in 2m16s
linter / quality (push) Successful in 1m1s
docker / build-and-push (push) Successful in 7m5s
docker / test (8.5) (push) Successful in 2m16s
docker / release (push) Successful in 4s
The entrypoint's php artisan view:cache failed on the package's showcase
views, whose components were only registered with the showcase enabled.
1.1.1 registers them always. ProductionBootTest caches every view with
the showcase off, as the entrypoint does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 17:59:34 +02:00
Andreas Reinhold / reiniandClaude Opus 5 cd97612b4d Keep planning notes out of the repository
docker / test (8.5) (push) Successful in 2m22s
linter / quality (push) Successful in 1m7s
tests / ci (8.5) (push) Successful in 2m24s
docker / build-and-push (push) Successful in 7m26s
docker / release (push) Skipped
docs/plans is ignored from now on; the notes stay on the machine that
wrote them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 16:24:30 +02:00
Andreas Reinhold / reiniandClaude Opus 5 c95d0c43c2 Load the website's Plausible site script
linter / quality (push) Successful in 1m7s
tests / ci (8.5) (push) Successful in 2m16s
docker / build-and-push (push) Successful in 7m5s
docker / test (8.5) (push) Successful in 2m25s
docker / release (push) Successful in 5s
Plausible gives each new site its own script and an init call instead
of the generic script with data-domain.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 16:21:51 +02:00
Andreas Reinhold / reiniandClaude Opus 5 09e24ade14 Build the amd64 image with QEMU 9.2.2 and only emulate the final stage
docker / test (8.5) (push) Successful in 2m20s
linter / quality (push) Successful in 1m5s
tests / ci (8.5) (push) Successful in 2m16s
docker / build-and-push (push) Successful in 20m13s
docker / release (push) Skipped
QEMU 8.x crashes running x86_64 programs on an arm64 host (QEMU issue
2168), which the 8.1.5 pin walked into, and 10.2 segfaults on the runner
as well; 9.2.2 runs node, composer and install-php-extensions on the
runner's host. The Composer and npm stages now build on the build
machine's platform: their output is the same for every target, so a
multi-arch build runs them once and natively.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 15:52:58 +02:00
Andreas Reinhold / reiniandClaude Opus 5 21bea9646d Let the admin choose one of eight colour profiles
linter / quality (push) Successful in 1m3s
tests / ci (8.5) (push) Successful in 2m8s
docker / test (8.5) (push) Successful in 2m15s
docker / build-and-push (push) Failing after 7m22s
docker / release (push) Skipped
Indigo (the default), Blue, Teal, Green, Amber, Rose and Violet in the
Vibrant style and Graphite in the Neutral style are generated from
config into the stylesheet. Admin settings opens with a colour profile
card: a swatch previews the profile on the page, and Save Settings
stores it as color_profile, which AppServiceProvider hands to the
package's resolver, so every page, mail and error page wears it. An
unknown profile is refused, and a saved one that disappears falls back
to indigo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 15:06:47 +02:00
Andreas Reinhold / reiniandClaude Opus 5 27e322c352 Update Livewire Material to 1.1.0
It brings colour profiles: several generated schemes under
<html data-scheme>, a resolver for the active one, and a picker. Boost's
copy of the package guideline and skill follows.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 15:06:47 +02:00
Andreas Reinhold / reiniandClaude Opus 5 ca0dfa9396 Emulate the amd64 image with QEMU 8 on the arm64 runner
docker / test (8.5) (push) Successful in 2m9s
linter / quality (push) Successful in 1m4s
tests / ci (8.5) (push) Successful in 2m10s
docker / build-and-push (push) Failing after 9m53s
docker / release (push) Has been skipped
Recent QEMU segfaults compiling PHP extensions for amd64 on the runner's
6.8 kernel (docker/buildx#3170); QEMU 8.1.5 is the version reported to
work.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 14:31:45 +02:00
Andreas Reinhold / reiniandClaude Opus 5 d860a16551 Move SealShare from GitHub to Gitea only
docker / test (8.5) (push) Successful in 2m13s
linter / quality (push) Successful in 1m8s
tests / ci (8.5) (push) Successful in 2m7s
docker / build-and-push (push) Failing after 9m54s
docker / release (push) Has been skipped
The workflows live in .gitea/workflows. The Docker workflow logs in to
the Gitea container registry with REGISTRY_TOKEN (Gitea's job token cannot
publish packages yet), publishes gitea.nonameweb.ch/nonameweb/sealshare
with a registry build cache, and makes the release on Gitea with the
version's section of the changelog as its notes.

The README, the website's quick start, both compose files and the image
label point to Gitea; the changelog announces the new image name and
links Gitea. GiteaOnlyTest keeps GitHub and ghcr.io out.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 13:59:07 +02:00
Andreas Reinhold / reiniandClaude Opus 5 606cc766f2 Add the SealShare website for sealshare.nonameweb.ch
docker / test (8.5) (push) Successful in 2m5s
docker / build-and-push (push) Failing after 9m38s
docker / release (push) Has been skipped
linter / quality (push) Successful in 1m8s
tests / ci (8.5) (push) Successful in 2m4s
website/ is hand-written HTML and CSS, uploaded as it is, like the
MailifySMS site: SealShare as software a company installs for its own
upload platform, how it works, features, a desktop/phone and light/dark
gallery of the generated screenshots, a dated and sourced comparison with
hosted transfer services and self-hosted tools, the Docker quick start,
FAQ and a privacy page for Plausible. Colours come from the app's scheme,
Google Sans Flex is served locally, nothing else loads from other hosts.

The README shows three screenshots and no longer calls the encryption
end-to-end. WebsiteTest guards missing files, other hosts, the screenshot
set and the encryption wording.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 12:38:49 +02:00
Andreas Reinhold / reiniandClaude Opus 5 e49bdf3eb3 Take the website's screenshots with one command
composer screenshots runs Pest browser tests in tests/Screenshots, outside
every test suite: fixed demo data under a frozen clock, desktop (MacBook
14, 2x) and phone (iPhone 15 Pro, 3x) in light and dark, each capture
published at once as WebP at two widths into website/img/screenshots.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 12:30:53 +02:00
Andreas Reinhold / reiniandClaude Opus 5 4470c2ed87 Give the dev container its own node_modules
npm installs the build tools' native binaries for the platform it runs
on, so a folder shared with the host only ever held Linux's or macOS's.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 12:30:53 +02:00
Andreas Reinhold / reiniandClaude Opus 5 1352533667 Offer a new share as a QR code and through the share sheet
The share created page gets "Show QR code", a dialog with the link as a
QR code (black on white, full screen on a phone) that downloads as a PNG
drawn in the browser, with a password reminder for protected shares; and
"Share…", which opens the device's share sheet where there is one. Both
carry only the link.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:46:07 +02:00
Andreas Reinhold / reiniandClaude Opus 5 fbe358b2e5 Require Bacon QR Code directly and update Livewire Material to 1.0.1
Bacon QR Code stays at the v3.1.1 Fortify already installed; SealShare
now draws QR codes with it too. Livewire Material 1.0.1 compiles its
components to the same view on every machine and keeps a full-screen
dialog's subtitle on a phone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:46:07 +02:00
Andreas Reinhold / reiniandClaude Opus 5 9fd600571d Keep the dev container's compiled views out of the shared storage
The checkout is mounted at /app, so views compiled in the container and
on the host landed in one storage/framework/views, and each side read the
other's absolute paths.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:17:38 +02:00
Andreas Reinhold / reiniandClaude Opus 5 accbc17c1c Move the navigation into a floating toolbar at the bottom
The top app bar repeated the site's name, which already heads the upload
and download pages, and spread its actions to the window's far edge. A
floating toolbar centred above the bottom edge, as wide as its buttons,
now holds them: Upload and the admin pages with the current one filled,
and the account menu; guests get Upload, the theme toggle and Log in,
without tooltips. On a phone the sign-in card no longer stretches to the
full height, and the admin dashboard's empty state sits outside the
scrolling table.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:12:12 +02:00
Andreas Reinhold / reiniandClaude Opus 5 2a363defd1 Install Playwright before the Docker workflow's tests
Its test job runs the whole suite, browser tests included.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:02:28 +02:00
Andreas Reinhold / reiniandClaude Opus 5 3604005cc7 Describe 2.0.0 in the README and changelog
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:02:03 +02:00
Andreas Reinhold / reiniandClaude Opus 5 a86f035add Install Livewire Material's Boost guideline and skill, and record rules
The scheme is regenerated, never hand-edited; the download page stays
free of anchored components; the theme key stays sealshare-theme.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:02:03 +02:00
Andreas Reinhold / reiniandClaude Opus 5 eb33bf77cc Send Markdown mail in the Material theme
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:02:03 +02:00
Andreas Reinhold / reiniandClaude Opus 5 bc69066ead Add browser tests for the Material interface
Upload drop zone, copying a share link, unlocking a download on a phone,
sorting and deleting on the admin dashboard, and the system theme with
the Appearance picker.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 11:02:03 +02:00
Andreas Reinhold / reiniandClaude Opus 5 c4a17b65c8 Move SealShare onto Livewire Material
Replaces maryUI and daisyUI with nonameweb/livewire-material: the Vibrant
indigo scheme, a system/light/dark theme under sealshare-theme, one top
app bar with the account menu, the upload drop zone and link-ready
moments, M3 fields, dialogs instead of wire:confirm, snackbars instead of
flashed messages, a sortable admin table, and the starter-kit cleanup.
Docker builds assets after Composer; CI drops the Flux step.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 10:49:38 +02:00
Andreas Reinhold / reiniandClaude Opus 5 6d7120e8e2 Drop icons:cache from the Livewire Material adoption steps
docker / test (8.5) (push) Successful in 2m13s
linter / quality (push) Successful in 59s
tests / ci (8.5) (push) Successful in 1m21s
docker / build-and-push (push) Failing after 12m32s
docker / release (push) Has been skipped
The package draws its Material Symbols without blade-icons, so there is no icon manifest to cache.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 05:24:13 +02:00
Andreas Reinhold / reiniandClaude Opus 5 2eeaa7c139 Add the plan for moving SealShare onto Livewire Material
SealShare leaves maryUI and daisyUI for nonameweb/livewire-material, a
shared Material 3 Expressive component package, once it reaches 1.0.0.
This plan holds SealShare's decisions and its adoption steps; the
package's own plan lives in the package repository.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
2026-09-13 04:59:30 +02:00
Andreas Reinhold / reiniandClaude Opus 5 08667c617d Release 1.2.0
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017XYnWFt9pJEwvAmNFN38XD
2026-09-10 10:42:22 +02:00
Andreas Reinhold / reiniandClaude Opus 5 92b3b3de56 Regenerate Boost guidelines and skills
Generated by boost:update for Boost 2.8, which replaces the pest-testing
skill with testing-best-practices and adds infer-conventions.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017XYnWFt9pJEwvAmNFN38XD
2026-09-10 10:42:22 +02:00
Andreas Reinhold / reiniandClaude Opus 5 3638455167 Upgrade frontend dependencies
Alpine.js 3.17.2, DaisyUI 5.7.32, Vite 8.2.2, laravel-vite-plugin 3.2,
autoprefixer 10.5.5 and concurrently 10.0.5. npm audit reports 0
vulnerabilities.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017XYnWFt9pJEwvAmNFN38XD
2026-09-10 10:42:21 +02:00
Andreas Reinhold / reiniandClaude Opus 5 5be3cbc1a7 Upgrade PHP dependencies and move to Pest 5
Pest 5.1 brings PHPUnit 13.3; phpunit.xml and the tests needed no
changes. Everything else stays within its existing constraint: Laravel
13.31, Livewire 4.4.4, Octane 2.19.1, Fortify 1.39, Mary 2.9.10, Boost
2.8 and Pint 1.32. Guzzle moves to 8.2 as a transitive dependency.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017XYnWFt9pJEwvAmNFN38XD
2026-09-10 10:42:21 +02:00
Andreas Reinhold / reiniandClaude Opus 5 126c0a5cdb Fix uploads over 4 GB failing with a misleading size error
Livewire's temporary upload rule was hard-coded to max:4194304 (4 GB),
so /livewire/upload-file rejected any larger file no matter how high
PHP_UPLOAD_MAX_FILESIZE or the admin's max file size were set.
_uploadErrored() then replaced Livewire's actual message with "file
exceeds the maximum size of N MB", quoting the admin limit the file was
under.

The cap is removed: PHP's upload_max_filesize is the hard limit and the
admin setting is still enforced in updatedFiles() and createShare(). A
rejected upload now logs the real validation errors and tells the user
the server could not accept the file.

max_upload_time is configurable via LIVEWIRE_MAX_UPLOAD_TIME, and the
README documents every limit large uploads depend on.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017XYnWFt9pJEwvAmNFN38XD
2026-09-10 10:42:21 +02:00
Andreas Reinhold / reiniandClaude Opus 4.8 992f3da084 Add CHANGELOG and refresh stale README tech stack
Documents 1.0.0, 1.0.1 and the upcoming 1.1.0 in Keep a Changelog format.

The tech stack table still claimed Laravel 12 and listed
maennchen/zipstream-php, which was dropped in 1.0.1 when ZIP downloads
moved to native ZipArchive.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 11:46:50 +02:00
Andreas Reinhold / reiniandClaude Opus 4.8 d2e8a135c5 Fix upload UI stuck on "Processing files..."
The `uploading` flag was only cleared by `x-init="uploading = false"` on the
file list, which Alpine runs when the element is initialized. Adding a second
batch of files to the same share only patches that existing element, so the
flag stayed true forever: the spinner never went away, the drop zone stayed
disabled and the submit button stayed disabled, making the share impossible
to create.

`updatedFiles()` now dispatches `files-processed`, which runs for every batch,
and the form resets its upload state on that event instead.

Also fixes two adjacent bugs in the drag & drop path: `uploadMultiple()` was
called without callbacks so dropped files showed no progress at all, and
`relativePaths` was replaced instead of appended, shifting every earlier
file's path onto the wrong file on a second drop.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 11:44:35 +02:00
Andreas Reinhold / reiniandClaude Opus 4.8 084cefe023 Force patched shell-quote via npm override
Clears the last outstanding advisory (GHSA-395f-4hp3-45gv, quadratic
complexity DoS in shell-quote's parse()). npm audit now reports 0
vulnerabilities, down from 3 before this branch.

concurrently pins "shell-quote": "1.8.4" exactly, and the maintainers
patched only the 9.x line (9.2.4 ships shell-quote 1.9.0) while 10.x still
carries 1.8.4. npm's only offered remedy was therefore a downgrade to
concurrently@9.2.4. The override keeps concurrently at 10.0.3 and resolves
shell-quote to 1.10.0 instead.

Overriding a deliberate exact pin warrants checking concurrently still
works, so this was verified functionally in node:24-alpine rather than
assumed: quoted and escaped arguments parse correctly (the shell-quote
code path), named prefixes render, and --kill-others-on-fail still
propagates a non-zero exit. npm install, npm ci and npm run build all
succeed, build hashes are unchanged, and the PHP suite passes 123 tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 11:31:58 +02:00
253 changed files with 32106 additions and 7954 deletions
+9
View File
@@ -0,0 +1,9 @@
---
paths:
- config/livewire-material.php
---
# Config
## Theme storage key is sealshare-theme
The theme is stored in localStorage under `sealshare-theme` (default `system`). `mary-theme` stays in `theme.legacy_keys` so visitors from 1.x keep their choice once; don't rename the key or drop the legacy entry, or every returning visitor's theme resets.
+9
View File
@@ -0,0 +1,9 @@
---
paths:
- 'resources/css/material-scheme.*'
---
# Css
## Regenerate the colour profiles, never hand-edit the scheme
material-scheme.css and material-scheme.json are generated together by `php artisan material:scheme` (no seed) from the eight `profiles` in config/livewire-material.php — all Vibrant (chosen over Tonal Spot, which read washed out on indigo) except Graphite (Neutral); `profile` is the default, indigo. The JSON colours the Markdown mail theme and the fallback error pages and lists the profiles Admin settings offers and validates against, so a hand edit to the CSS alone leaves them out of step. Change the config and rerun the command; a profile only exists once generated. The admin's choice is the `color_profile` setting, read through `Scheme::resolveProfileUsing()` in AppServiceProvider.
+13
View File
@@ -0,0 +1,13 @@
# Project Rules Index
Before planning or editing, find the row whose globs match the file's path and read that rule file.
| Applies to | Rule file |
| --- | --- |
| config/livewire-material.php | .ai/rules/config.md |
| resources/css/material-scheme.* | .ai/rules/css.md |
| resources/views/livewire/share-download.blade.php | .ai/rules/livewire.md |
| tests/Screenshots/** | .ai/rules/screenshots.md |
| app/Services/** | .ai/rules/services.md |
| resources/views/** | .ai/rules/views.md |
| website/** | .ai/rules/website.md |
+9
View File
@@ -0,0 +1,9 @@
---
paths:
- resources/views/livewire/share-download.blade.php
---
# Livewire
## No anchored components on the download page
Recipients open share links on any phone, including iOS Safari below 18.4, where CSS anchor positioning is missing. Keep menus, tooltips, selects-as-menus, datepickers and other anchored/popover components off this page; use plain buttons with aria-label and native controls. tests/Browser/SealShareTest.php checks the page at 393px has no popovers.
+9
View File
@@ -0,0 +1,9 @@
---
paths:
- 'tests/Screenshots/**'
---
# Screenshots
## Screenshots come from composer screenshots, before a release
Run `composer screenshots` whenever the interface changes and before a release; it builds assets and runs tests/Screenshots (not part of any test suite or CI), publishing WebP files to website/img/screenshots. Demo data (DemoData) and the clock are fixed so runs are reproducible. Traps: Pest only starts its browser for a test whose body calls `visit(` after whitespace; the upload shot's files are registered through the page's `registerFiles` and their encrypted chunks stored server-side (the in-process server takes request bodies up to 128 KB only), then the list refreshed; the in-process server's random port is shown as https://files.example.com and the QR redrawn for it.
+9
View File
@@ -0,0 +1,9 @@
---
paths:
- 'app/Services/**'
---
# Services
## Uploads are encrypted in the browser, never on the server
Share files are encrypted chunk by chunk in the uploader's browser (resources/js/share-uploader.js, WebCrypto) in the SEALCHK2 format and PUT to UploadChunkController, which verifies each chunk in memory and writes it once. Never add a server-side upload path that puts plaintext on disk (Livewire temp uploads, multipart spooling): PHP spools every request body to upload_tmp_dir. ShareService::createShare() exists only for tests and demo data. Send chunk bodies as a Blob, not an ArrayBuffer: Chromium uploads an ArrayBuffer about 8x slower.
+12
View File
@@ -0,0 +1,12 @@
---
paths:
- 'resources/views/**'
---
# Views
## `<x-group>` drops data-test and other attributes
`<x-group>` (Livewire Material) keeps only class, style and wire:key on its fieldset and wire:model/x-model on its inputs; data-test, id and every other attribute are silently dropped. Tests reach a group through its binding instead, e.g. assertSeeHtml('wire:model.live="passwordGeneratorType"') or input[value="…"]. Rendering `<x-group>` also needs components/group.css imported in resources/css/app.css (DesignLanguageTest's missingStylesheets guards it).
## Every page renders <x-page>
Every page (Livewire page, settings SFC via pages/settings/layout, Fortify auth view) has <x-page> (resources/views/components/page.blade.php) at its root, inside layouts/app — the only layout. It draws the centred h1 header (`brand` for the site's logo/title/description on public and sign-in pages, or title/description, optional `mark` and `navigation` slots) over one centred column. Every page is the same 40rem column and <x-page> has no width prop: content that needs more room is rearranged to fit (the admin dashboard's shares are a list with a sort select, not a table). Content goes in outlined cards (`<x-card variant="outlined" heading="h2">`). Never give a page its own width class, h1 or header stack. tests/Feature/PageTemplateTest.php lists every page.
+9
View File
@@ -0,0 +1,9 @@
---
paths:
- 'website/**'
---
# Website
## website/ is the live site, uploaded by hand
website/ is a faithful copy of sealshare.nonameweb.ch (METANET hosting), hand-written HTML/CSS with no build step, uploaded wholesale when it changes. Colours in css/theme.css are copied from the indigo profile in resources/css/material-scheme.json: the standard light and dark values (profiles.indigo.light/dark) and the high-contrast light and dark values (profiles.indigo.contrast.high) — copy them again if indigo is regenerated differently; the site does not follow the admin's colour profile. Light or dark is <html data-theme>, written before the first paint by each page's inline head script from the nav's Light/Dark/System toggle (localStorage sealshare-website-theme); the high-contrast values apply under prefers-contrast: more. The comparison tables are dated and every competitor value has a source from the product's own site, docs or repo; an unsourced value is "—", never a guess. Never call SealShare's encryption end-to-end (files are encrypted in the browser with a key the server issues, and the server decrypts them for downloads). Nothing may load from another host except plausible.io. tests/Feature/WebsiteTest.php guards all of this.
+105
View File
@@ -0,0 +1,105 @@
---
name: infer-conventions
description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Only run this skill when the user explicitly asks for it; never start a sweep as part of another task. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."
disable-model-invocation: true
license: MIT
metadata:
author: laravel
---
# Infer Conventions
Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it.
## Ground Rules (read before you start)
- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer.
- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record.
- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule.
- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering.
- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped.
- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar.
- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details.
## Process
Each step ends on a checkable completion criterion. Do not advance until it holds.
Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output.
### Step 0: Orient
Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2.
This app ships a frontend stack, so the frontend checklist group applies. Sweep it.
Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents.
### Step 1: Predefined sweep
Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:
- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files.
- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled.
- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention.
- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most).
- Tooling-owned or Already-recorded. Skip per the ground rules.
Done when: every applicable dimension carries exactly one of those verdicts.
### Step 2: Open-ended pass
First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude.
Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal.
Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none).
### Step 3: Confirm
Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style.
Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo.
Done when: every candidate is approved, rejected, or (conflicts) decided.
### Step 4: Record
Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand.
Record this:
> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models.
Not this:
> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models.
Done when: every approved item has a successful tool response, and any failure is reported with its rule text.
### Step 5: Summarize
List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions.
## Glob mapping
Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path.
Examples:
- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.
- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer.
- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses.
- Tests: `tests/**`.
- Migrations and database: `database/migrations/**`.
- Truly app-wide (rare, e.g. auth retrieval): `app/**`.
`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there.
## Edge cases
- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4.
- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing.
- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything.
- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface.
- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths.
@@ -0,0 +1,139 @@
# Detection Checklist
Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`).
Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence.
---
## A. Validation & HTTP input
1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.
- Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`.
2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal.
- Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`.
3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties.
- Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.
4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.
- Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`.
## B. Controllers & routing
5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.
- Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes.
6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.
- Hint: read a few controller methods; `ls app/Actions app/Services`.
7. Route handler style: closures in `routes/*.php` vs controller classes.
- Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.
8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.
- Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.
9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`.
- Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`.
10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.
- Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.
## C. Authorization
11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.
- Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`.
12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade.
- Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.
## D. Eloquent & models
13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.
- Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.
14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain.
- Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.
15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.
- Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`.
16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings.
- Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models.
17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`).
- Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built.
18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.
- Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`.
19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.
- Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`.
20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture.
- Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.
## E. Architecture & organization
21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked.
- Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find.
22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.
- Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`.
23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.
- Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.
24. Decoupling: events + listeners vs direct service calls.
- Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`.
25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).
- Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.
26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).
- Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.
27. Enums: backed vs pure; case naming; where they live.
- Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`.
## F. Frontend & views
This app ships a frontend stack, so the items below apply.
28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA.
- Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`.
29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.
- Hint: `ls app/View/Components`; grep `<x-`, `@include` in `resources/views`.
30. Livewire component format: Volt functional/class components, native Livewire 4 single-file (SFC), multi-file (MFC), view-based, or class-based components. Evaluate full-page vs nested separately because it is an independent usage choice.
- Hint: check the installed Livewire major and `livewire/volt`; inspect `app/Livewire`, `resources/views/livewire`, and Livewire 4 component/page directories for `@volt`, SFC, MFC, view-based, and class-based formats.
32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).
- Hint: `ls lang`; grep dotted `__('` vs sentence keys.
## G. Database & migrations
33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.
- Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.
34. `down()` methods: real reverse logic vs omitted / one-way migrations.
- Hint: grep `function down` vs the migration count.
35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.
- Hint: grep `->enum(` in migrations vs string columns cast to enums.
36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.
- Hint: grep `DB::transaction`, `beginTransaction` in `app/`.
37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.
- Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`.
## H. Testing
38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.
- Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`.
39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.
- Hint: grep those trait names in `tests/`.
40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories.
- Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide.
41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery.
- Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`.
42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.
- Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.
## I. Responses & API resources
43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.
- Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.
44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately.
- Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`.
45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority.
- Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them.
46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`.
- Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views.
## J. Strings, collections & dates
47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.
- Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.
48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).
- Hint: grep `Str::of(` vs `Str::` vs native string funcs.
49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting.
- Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy.
---
Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from.
@@ -48,7 +48,7 @@ Cross-cutting changes often need more than one rule file.
| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) |
| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) |
| Environment values and application configuration | [`rules/config.md`](rules/config.md) |
| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) |
| Tests: coverage, factories, fakes, and assertions | the `testing-best-practices` skill |
| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |
| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |
@@ -1,8 +1,8 @@
# Advanced Query Patterns
# Advanced Query Best Practices
## Use `addSelect()` Subqueries for Single Values from Has-Many
## Select Single Relationship Values with Subqueries
Instead of eager-loading an entire has-many relationship for a single value (like the latest timestamp), use a correlated subquery via `addSelect()`. This pulls the value directly in the main SQL query — zero extra queries.
When only one value from a has-many relationship is needed, consider a correlated subquery with `addSelect()` instead of loading the entire relationship. This selects the value as part of the main query without an additional relationship query.
```php
public function scopeWithLastLoginAt($query): void
@@ -16,14 +16,14 @@ public function scopeWithLastLoginAt($query): void
}
```
## Create Dynamic Relationships via Subquery FK
## Create Dynamic Relationships with a Subquery Foreign Key
Extend the `addSelect()` pattern to fetch a foreign key via subquery, then define a `belongsTo` relationship on that virtual attribute. This provides a fully-hydrated related model without loading the entire collection.
The same pattern can select a foreign key and expose the selected model through a `belongsTo` relationship. Eager loading that relationship still executes a separate query, but it avoids loading the full has-many collection.
```php
public function lastLogin(): BelongsTo
{
return $this->belongsTo(Login::class);
return $this->belongsTo(Login::class, 'last_login_id');
}
public function scopeWithLastLogin($query): void
@@ -37,9 +37,9 @@ public function scopeWithLastLogin($query): void
}
```
## Use Conditional Aggregates Instead of Multiple Count Queries
## Combine Related Counts with Conditional Aggregates
Replace N separate `count()` queries with a single query using `CASE WHEN` inside `selectRaw()`. Use `toBase()` to skip model hydration when you only need scalar values.
Combine several counts over the same filtered data set into one query by using conditional aggregates. Use `toBase()` when only scalar values are needed and model hydration provides no benefit. Confirm the expression syntax against the application's database engine.
```php
$statuses = Feature::toBase()
@@ -49,50 +49,50 @@ $statuses = Feature::toBase()
->first();
```
## Use `setRelation()` to Prevent Circular N+1
## Reuse Loaded Parent Models with `setRelation()`
When a parent model is eager-loaded with its children, and the view also needs `$child->parent`, use `setRelation()` to inject the already-loaded parent rather than letting Eloquent fire N additional queries.
When a parent and its children are already loaded and code also accesses `$child->parent`, set the inverse relationship to the existing parent instance. This avoids an additional lazy-loading query for each child.
```php
$feature->load('comments.user');
$feature->comments->each->setRelation('feature', $feature);
```
## Prefer `whereIn` + Subquery Over `whereHas`
## Compare `whereHas()` with an `IN` Subquery
`whereHas()` emits a correlated `EXISTS` subquery that re-executes per row. Using `whereIn()` with a `select('id')` subquery lets the database use an index lookup instead, without loading data into PHP memory.
`whereHas()` typically produces an `EXISTS` subquery, while `whereIn()` can express the same filter with an `IN` subquery. Either form may be faster depending on the database engine, indexes, cardinality, and query plan. Measure both forms with representative data; neither subquery loads its result set into PHP memory.
Incorrect (correlated EXISTS re-executes per row):
Option using `EXISTS`:
```php
$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term));
```
Correct (index-friendly subquery, no PHP memory overhead):
Option using `IN`:
```php
$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
```
## Sometimes Two Simple Queries Beat One Complex Query
## Measure Two Simple Queries Against One Complex Query
Running a small, targeted secondary query and passing its results via `whereIn` is often faster than a single complex correlated subquery or join. The additional round-trip is worthwhile when the secondary query is highly selective and uses its own index.
Two targeted queries can outperform one complex correlated subquery or join when the first query is highly selective. They also add a database round trip, can transfer a large identifier list, and do not provide a single-query consistency snapshot. Decide from query plans and production-like measurements.
## Use Compound Indexes Matching `orderBy` Column Order
## Design Composite Indexes for the Query
When ordering by multiple columns, create a single compound index in the same column order as the `ORDER BY` clause. Individual single-column indexes cannot combine for multi-column sorts — the database will filesort without a compound index.
For common multi-column sorts, consider a composite index whose column order supports the query's filters and ordering. Database engines may combine indexes or choose an explicit sort, so matching the `ORDER BY` list alone does not guarantee that an index will be used. Verify the query plan.
```php
// Migration
$table->index(['last_name', 'first_name']);
// Query — column order must match the index
// Query that this index may support
User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
```
## Use Correlated Subqueries for Has-Many Ordering
## Consider a Correlated Subquery for Has-Many Ordering
When sorting by a value from a has-many relationship, avoid joins (they duplicate rows). Use a correlated subquery inside `orderBy()` instead, paired with an `addSelect` scope for eager loading.
When sorting by one value from a has-many relationship, a direct join can duplicate parent rows unless it first reduces the related table to one row per parent. A correlated subquery in `orderBy()` is often simpler, but its performance depends on the query plan and supporting indexes.
```php
public function scopeOrderByLastLogin($query): void
@@ -1,8 +1,8 @@
# Architecture Best Practices
## Single-Purpose Action Classes
## Extract Focused Business Operations
Extract discrete business operations into invokable Action classes.
Extract a discrete business operation into an action class when doing so makes the operation easier to reuse or test. An action class has no special meaning to Laravel; follow the project's naming and invocation conventions.
```php
class CreateOrderAction
@@ -19,11 +19,12 @@ class CreateOrderAction
}
```
## Use Dependency Injection
## Inject Required Dependencies
Always use constructor injection. Avoid `app()` or `resolve()` inside classes.
Prefer constructor injection for dependencies required throughout an object's lifetime. Method injection is appropriate for dependencies needed by one controller action, listener, job handler, or other container-invoked method. Avoid `app()` and `resolve()` when normal injection can make a dependency explicit.
Hidden dependency:
Incorrect:
```php
class OrderController extends Controller
{
@@ -36,24 +37,24 @@ class OrderController extends Controller
}
```
Correct:
Injected dependency:
```php
class OrderController extends Controller
{
public function __construct(private OrderService $service) {}
public function store(StoreOrderRequest $request)
public function store(StoreOrderRequest $request, OrderService $service)
{
return $this->service->create($request->validated());
return $service->create($request->validated());
}
}
```
## Code to Interfaces
## Depend on Contracts at Boundaries
Depend on contracts at system boundaries (payment gateways, notification channels, external APIs) for testability and swappability.
Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction.
Concrete boundary dependency:
Incorrect (concrete dependency):
```php
class OrderService
{
@@ -61,7 +62,8 @@ class OrderService
}
```
Correct (interface dependency):
Contract boundary dependency:
```php
interface PaymentGateway
{
@@ -80,86 +82,99 @@ Bind in a service provider:
$this->app->bind(PaymentGateway::class, StripeGateway::class);
```
## Default Sort by Descending
## Specify a Deterministic Sort Order
When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.
Without an explicit `ORDER BY`, row order is undefined. Choose an order that matches the feature, and add a unique tie-breaker when stable pagination matters.
Unspecified order:
Incorrect:
```php
$posts = Post::paginate();
```
Correct:
Newest first with a stable tie-breaker:
```php
$posts = Post::latest()->paginate();
$posts = Post::query()
->orderByDesc('created_at')
->orderByDesc('id')
->paginate();
```
## Use Atomic Locks for Race Conditions
Prevent race conditions with `Cache::lock()` or `lockForUpdate()`.
Use a lock when concurrent execution must be serialized. `Cache::lock()` provides an atomic lock when the configured cache store supports locks. `lockForUpdate()` locks selected database rows and must run inside a database transaction. These mechanisms solve different coordination problems.
```php
Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
$order->process();
});
// Or at query level
$product = Product::where('id', $id)->lockForUpdate()->first();
// Or at query level, inside a transaction
DB::transaction(function () use ($id) {
$product = Product::where('id', $id)->lockForUpdate()->first();
// Read and update the product while the database lock is held.
});
```
## Use `mb_*` String Functions
When no Laravel helper exists, prefer `mb_strlen`, `mb_strtolower`, etc. for UTF-8 safety. Standard PHP string functions count bytes, not characters.
When no Laravel helper exists, prefer multibyte-aware functions such as `mb_strlen()` and `mb_strtolower()` for UTF-8 text. For example, `strlen()` counts bytes, while `strtolower()` is not multibyte-aware.
Incorrect:
```php
strlen('José'); // 5 (bytes, not characters)
strtolower('MÜNCHEN'); // 'mÜnchen' — fails on multibyte
strlen('José'); // 5 bytes, not 4 characters
strtolower('MÜNCHEN'); // Does not lowercase Ü
```
Correct:
```php
mb_strlen('José'); // 4 (characters)
mb_strtolower('MÜNCHEN'); // 'münchen'
mb_strlen('José'); // 4 characters
mb_strtolower('MÜNCHEN'); // 'münchen'
// Prefer Laravel's Str helpers when available
Str::length('José'); // 4
Str::lower('MÜNCHEN'); // 'münchen'
Str::length('José'); // 4
Str::lower('MÜNCHEN'); // 'münchen'
```
## Use `defer()` for Post-Response Work
For lightweight tasks that don't need to survive a crash (logging, analytics, cleanup), use `defer()` instead of dispatching a job. The callback runs after the HTTP response is sent — no queue overhead.
For lightweight work that does not need retries or crash durability, consider `defer()` instead of dispatching a job. During an HTTP request, the callback normally runs after the response has been sent but remains in the same PHP process.
Queued and durable:
Incorrect (job overhead for trivial work):
```php
dispatch(new LogPageView($page));
```
Correct (runs after response, same process):
Deferred in the current process:
```php
defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()]));
```
Use jobs when the work must survive process crashes or needs retry logic. Use `defer()` for fire-and-forget work.
Use a queued job when the work needs retries, queue controls, or durability across process failures.
## Use `Context` for Request-Scoped Data
The `Context` facade passes data through the entire request lifecycle — middleware, controllers, jobs, logs — without passing arguments manually.
The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer.
```php
// In middleware
Context::add('tenant_id', $request->header('X-Tenant-ID'));
// Anywhere later — controllers, jobs, log context
// Later in the same execution lifecycle
$tenantId = Context::get('tenant_id');
```
Context data automatically propagates to queued jobs and is included in log entries. Use `Context::addHidden()` for sensitive data that should be available in queued jobs but excluded from log context. If data must not leave the current process, do not store it in `Context`.
Visible context is added to log context, and both visible and hidden context are captured and restored for queued jobs. Use `Context::addHidden()` for data that should propagate to queued jobs without appearing in logs. Do not place secrets in context unless that propagation is intended.
## Use `Concurrency::run()` for Parallel Execution
Run independent operations in parallel using child processes — no async libraries needed.
Run independent operations concurrently through Laravel's configured concurrency driver.
```php
use Illuminate\Support\Facades\Concurrency;
@@ -170,13 +185,14 @@ use Illuminate\Support\Facades\Concurrency;
]);
```
Each closure runs in a separate process with full Laravel access. Use for independent database queries, API calls, or computations that would otherwise run sequentially.
With a process-based driver, each closure runs in a separate PHP process that boots the application. Use concurrency when independent database queries, HTTP client calls, or computations benefit enough to offset process and serialization overhead. The `sync` driver executes closures sequentially and is useful primarily during testing.
## Convention Over Configuration
## Follow Framework Conventions
Follow Laravel conventions. Don't override defaults unnecessarily.
Follow Laravel conventions unless the domain or an existing schema requires an override.
Customized schema:
Incorrect:
```php
class Customer extends Model
{
@@ -190,7 +206,8 @@ class Customer extends Model
}
```
Correct:
Conventional schema:
```php
class Customer extends Model
{
@@ -1,8 +1,8 @@
# Blade & Views Best Practices
# Blade and View Best Practices
## Use `$attributes->merge()` in Component Templates
Hardcoding classes prevents consumers from adding their own. `merge()` combines class attributes cleanly.
Use the component attribute bag so callers can add attributes. `merge()` combines default attributes with caller-provided values; class values receive special merging behavior.
```blade
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
@@ -12,25 +12,25 @@ Hardcoding classes prevents consumers from adding their own. `merge()` combines
## Use `@pushOnce` for Per-Component Scripts
If a component renders inside a `@foreach`, `@push` inserts the script N times. `@pushOnce` guarantees it's included exactly once.
If a component renders repeatedly, `@push` adds its script on every render. Use a consistently named `@pushOnce` block to add that content once per rendered response.
## Prefer Blade Components Over `@include`
## Prefer Components for Explicit Interfaces
`@include` shares all parent variables implicitly (hidden coupling). Components have explicit props, attribute bags, and slots.
Use a Blade component when a reusable interface benefits from explicit props, an attribute bag, or slots. An include remains suitable for a small partial that intentionally uses the current view data; pass an explicit data array when implicit variable sharing would obscure its dependencies.
## Use View Composers for Shared View Data
## Share Compatible View Data with a View Composer
If every controller rendering a sidebar must pass `$categories`, that's duplicated code. A View Composer centralizes it.
Use a view composer to centralize data needed whenever one or more named Blade views are rendered. Keep the composer compatible with every view it targets, and avoid broad wildcards when views require different data shapes. A view composer runs when Laravel renders the matching view; it does not supply data to JSON, streamed, or other non-view responses.
## Use Blade Fragments for Partial Re-Renders (htmx/Turbo)
## Return Blade Fragments for Partial Rendering
A single view can return either the full page or just a fragment, keeping routing clean.
A route can return either a full view or a named fragment for clients such as htmx or Turbo.
```php
return view('dashboard', compact('users'))
->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
```
## Use `@aware` for Deeply Nested Component Props
## Share Parent Component Props with `@aware`
Avoids re-passing parent props through every level of nested components.
Use `@aware` when a nested component needs a prop explicitly passed to an ancestor component. It does not expose an ancestor's default prop value unless that value was passed through the attribute bag.
@@ -1,10 +1,13 @@
# Caching Best Practices
## Use `Cache::remember()` Instead of Manual Get/Put
## Use `Cache::remember()` for Cache-Aside Reads
Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.
`Cache::remember()` implements a cache-aside read without a separate truthiness check. It does not prevent concurrent requests from computing the same missing value; use an atomic lock when duplicate computation must be prevented.
The manual version below incorrectly treats valid falsy values, such as `false` or `0`, as cache misses.
Incorrect:
```php
$val = Cache::get('stats');
if (! $val) {
@@ -14,27 +17,42 @@ if (! $val) {
```
Correct:
```php
$val = Cache::remember('stats', 60, fn () => $this->computeStats());
```
## Use `Cache::flexible()` for Stale-While-Revalidate
## Consider `Cache::flexible()` for Stale-While-Revalidate
On high-traffic keys, one user always gets a slow response when the cache expires. `flexible()` serves slightly stale data while refreshing in the background.
For frequently read keys, `Cache::flexible()` can serve stale data during a defined stale period and register a deferred refresh. During an HTTP request, that refresh normally runs after the response; it is not a durable background job. Once the stale period has elapsed, the request recomputes the value synchronously.
Incorrect: `Cache::remember('users', 300, fn () => User::all());`
Synchronous expiration:
Correct: `Cache::flexible('users', [300, 600], fn () => User::all());` — fresh for 5 min, stale-but-served up to 10 min, refreshes via deferred function.
```php
Cache::remember('users', 300, fn () => User::all());
```
## Use `Cache::memo()` to Avoid Redundant Hits Within a Request
Stale-while-revalidate tradeoff:
If the same cache key is read multiple times per request (e.g., a service called from multiple places), `memo()` stores the resolved value in memory.
```php
Cache::flexible('users', [300, 600], fn () => User::all());
```
`Cache::memo()->get('settings');` — 5 calls = 1 Redis round-trip instead of 5.
This value is fresh for five minutes and may be served stale until ten minutes after it was cached.
## Use `Cache::memo()` to Avoid Redundant Hits Within an Execution
If the same cache key is read repeatedly during one request or job, `memo()` decorates a cache store and retains resolved values in memory for that execution.
```php
$settings = Cache::memo()->get('settings');
```
Repeated reads through the same memoized store avoid additional store lookups. Writes through the memoized store update or invalidate its in-memory values as appropriate.
## Use Cache Tags to Invalidate Related Groups
Without tags, invalidating a group of entries requires tracking every key. Tags let you flush atomically. Only works with `redis`, `memcached`, `dynamodb` — not `file` or `database`.
Tags group related entries for invalidation without tracking each key. Cache tags are not supported by the `file`, `dynamodb`, or `database` drivers; confirm support before choosing a store.
```php
Cache::tags(['user-1'])->flush();
@@ -42,15 +60,27 @@ Cache::tags(['user-1'])->flush();
## Use `Cache::add()` for Atomic Conditional Writes
`add()` only writes if the key does not exist — atomic, no race condition between checking and writing.
`add()` atomically writes a value only when the key does not already exist.
Incorrect: `if (! Cache::has('lock')) { Cache::put('lock', true, 10); }`
Incorrect:
Correct: `Cache::add('lock', true, 10);`
```php
if (! Cache::has('lock')) {
Cache::put('lock', true, 10);
}
```
## Use `once()` for Per-Request Memoization
Correct:
`once()` memoizes a function's return value for the lifetime of the object (or request for closures). Unlike `Cache::memo()`, it doesn't hit the cache store at all — pure in-memory.
```php
Cache::add('lock', true, 10);
```
Use `Cache::lock()` rather than an ordinary cache key when lock ownership and safe release are required.
## Use `once()` for In-Process Memoization
`once()` memoizes a callback's return value for the current request or job. Calls made from an object instance are scoped to that instance. Unlike `Cache::memo()`, `once()` does not read from an external cache store.
```php
public function roles(): Collection
@@ -59,11 +89,11 @@ public function roles(): Collection
}
```
Multiple calls return the cached result without re-executing. Use `once()` for expensive computations called multiple times per request. Use `Cache::memo()` when you also want cross-request caching.
Repeated calls return the memoized result without rerunning the callback. Use `once()` for repeated computation within one execution. Use `Cache::memo()` to memoize access to an underlying store that can also persist values across executions.
## Configure Failover Cache Stores in Production
If Redis goes down, the app falls back to a secondary store automatically.
The failover driver tries each configured store in order when a store operation throws an exception. It does not consult later stores for an ordinary cache miss, and data is not replicated between stores.
```php
'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
@@ -2,41 +2,69 @@
## Use Higher-Order Messages for Simple Operations
Incorrect:
Explicit closure:
```php
$users->each(function (User $user) {
$user->markAsVip();
});
```
Correct: `$users->each->markAsVip();`
Concise equivalent:
Works with `each`, `map`, `sum`, `filter`, `reject`, `contains`, etc.
```php
$users->each->markAsVip();
```
## Choose `cursor()` vs. `lazy()` Correctly
Higher-order messages are available for supported collection methods such as `each`, `map`, `filter`, and `sum`. Use an explicit closure when arguments or nontrivial logic would be clearer.
- `cursor()` — one model in memory, but cannot eager-load relationships (N+1 risk).
- `lazy()` — chunked pagination returning a flat LazyCollection, supports eager loading.
## Choose Between `cursor()` and `lazy()`
Incorrect: `User::with('roles')->cursor()` — eager loading silently ignored.
`cursor()` executes one query and hydrates models individually, but it cannot eager load relationships. The database driver's result buffering can still consume substantial memory for very large results. Use it for low-memory, attribute-only iteration when one long-running query is acceptable.
Correct: `User::with('roles')->lazy()` for relationship access; `User::cursor()` for attribute-only work.
`lazy()` executes multiple chunked queries and returns a flat `LazyCollection`. It supports eager loading relationships for each chunk and avoids holding one database cursor open for the entire iteration.
With relationships:
```php
User::with('roles')->lazy()->each(function (User $user) {
// The roles for this chunk have been eager loaded.
});
```
Without relationships:
```php
User::cursor()->each(function (User $user) {
// Process model attributes.
});
```
## Use `lazyById()` When Updating Records While Iterating
`lazy()` uses offset pagination — updating records during iteration can skip or double-process. `lazyById()` uses `id > last_id`, safe against mutation.
`lazy()` uses offset pagination, so updates to columns that affect the query can shift rows and cause records to be skipped or processed twice. `lazyById()` paginates by a monotonic key and is safer when updating other columns during iteration. Do not change the pagination key itself while iterating.
## Use `toQuery()` for Bulk Operations on Collections
Avoids manual `whereIn` construction.
Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause.
Incorrect: `User::whereIn('id', $users->pluck('id'))->update([...]);`
Manual query:
Correct: `$users->toQuery()->update([...]);`
```php
User::whereIn('id', $users->modelKeys())->update(['active' => false]);
```
Collection query:
```php
$users->toQuery()->update(['active' => false]);
```
`toQuery()` requires a non-empty Eloquent collection whose models are of the same type. Like other bulk Eloquent updates, it does not dispatch per-model update events, so use it only when those events are not required.
## Use `#[CollectedBy]` for Custom Collection Classes
More declarative than overriding `newCollection()`.
The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override.
```php
#[CollectedBy(UserCollection::class)]
@@ -1,73 +1,85 @@
# Configuration Best Practices
## `env()` Only in Config Files
## Read Environment Variables in Configuration Files
Direct `env()` calls may return `null` when config is cached.
Call `env()` only from configuration files. After configuration is cached, Laravel does not load the application's `.env` file, so application code should read configuration values through `config()`.
Incorrect:
```php
$key = env('API_KEY');
```
Correct:
```php
// config/services.php
'key' => env('API_KEY'),
return [
'key' => env('API_KEY'),
];
// Application code
$key = config('services.key');
```
## Use Encrypted Env or External Secrets
## Protect Production Secrets
Never store production secrets in plain `.env` files in version control.
Do not commit plaintext production secrets. Laravel can encrypt an environment file so its encrypted form can be stored safely, while deployment platforms can supply secrets through their native secret stores.
Incorrect:
```bash
# .env committed to repo or shared in Slack
STRIPE_SECRET=sk_live_abc123
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI
# A plaintext .env file committed to the repository
STRIPE_SECRET=<your-stripe-secret>
AWS_SECRET_ACCESS_KEY=<your-aws-secret>
```
Correct:
Encrypted environment file:
```bash
php artisan env:encrypt --env=production --readable
php artisan env:decrypt --env=production
```
For cloud deployments, prefer the platform's native secret store (AWS Secrets Manager, Vault, etc.) and inject at runtime.
For hosted deployments, consider the platform's native secret store, such as AWS Secrets Manager or Vault, and inject secrets at runtime.
## Use `App::environment()` for Environment Checks
Incorrect:
```php
if (env('APP_ENV') === 'production') {
// ...
}
```
Correct:
```php
if (app()->isProduction()) {
// or
// ...
}
if (App::environment('production')) {
// ...
}
```
## Use Constants and Language Files
## Name Repeated Domain Values
Use class constants instead of hardcoded magic strings for model states, types, and statuses.
Use an enum or class constant when a domain value is repeated or represents a constrained set. A one-off string literal does not always need a named constant.
```php
// Incorrect
// Repeated literal
return $this->type === 'normal';
// Correct
// Named domain value
return $this->type === self::TYPE_NORMAL;
```
If the application already uses language files for localization, use `__()` for user-facing strings too. Do not introduce language files purely for English-only apps — simple string literals are fine there.
If the application supports localization, put user-facing strings in language files and retrieve them with `__()`. Simple literals are reasonable for applications that intentionally do not support multiple languages.
```php
// Only when lang files already exist in the project
// In a localized application
return back()->with('message', __('app.article_added'));
```
@@ -1,10 +1,11 @@
# Database Performance Best Practices
## Always Eager Load Relationships
## Eager Load Relationships Before Iterating
Lazy loading causes N+1 query problems — one query per loop iteration. Always use `with()` to load relationships upfront.
When a relationship will be accessed for many models, eager load it with `with()` to avoid running one initial query plus one relationship query per model, commonly called an N+1 query pattern. Lazy loading is reasonable when the relationship may not be needed or only one model is involved.
Lazy-loaded version:
Incorrect (N+1 — executes 1 + N queries):
```php
$posts = Post::all();
foreach ($posts as $post) {
@@ -12,7 +13,8 @@ foreach ($posts as $post) {
}
```
Correct (2 queries total):
Eager-loaded version:
```php
$posts = Post::with('author')->get();
foreach ($posts as $post) {
@@ -20,7 +22,7 @@ foreach ($posts as $post) {
}
```
Constrain eager loads to select only needed columns (always include the foreign key):
Constrain eager loads when large columns are unnecessary. Include the related model's primary key and every column Eloquent needs to match the relationship. In this example, `users.id` and `posts.user_id` match posts to users, while selecting `posts.id` preserves each related model's primary key:
```php
$users = User::with(['posts' => function ($query) {
@@ -42,31 +44,34 @@ public function boot(): void
}
```
Throws `LazyLoadingViolationException` when a relationship is accessed without being eager-loaded.
By default, accessing an unloaded relationship then throws a `LazyLoadingViolationException`. Applications can customize violation handling with `handleLazyLoadingViolationUsing()`.
## Select Only Needed Columns
Avoid `SELECT *` — especially when tables have large text or JSON columns.
Select only the columns the operation needs when omitting large text, binary, or JSON columns provides a meaningful benefit.
All columns:
Incorrect:
```php
$posts = Post::with('author')->get();
```
Correct:
Selected columns:
```php
$posts = Post::select('id', 'title', 'user_id', 'created_at')
->with(['author:id,name,avatar'])
->get();
```
When selecting columns on eager-loaded relationships, always include the foreign key column or the relationship won't match.
When limiting selected columns, retain every key Eloquent needs for matching. A `belongsTo` relationship needs its foreign key on the parent query and the owner's key on the related query. A `hasMany` relationship needs the parent's local key and the related model's foreign key.
## Chunk Large Datasets
## Process Large Data Sets Incrementally
Never load thousands of records at once. Use chunking for batch processing.
Use chunking or lazy iteration when loading an entire result set would exceed the application's practical memory budget.
Loads the complete result set:
Incorrect:
```php
$users = User::all();
foreach ($users as $user) {
@@ -74,7 +79,8 @@ foreach ($users as $user) {
}
```
Correct:
Processes bounded chunks:
```php
User::where('subscribed', true)->chunk(200, function ($users) {
foreach ($users as $user) {
@@ -83,7 +89,7 @@ User::where('subscribed', true)->chunk(200, function ($users) {
});
```
Use `chunkById()` when modifying records during iteration — standard `chunk()` uses OFFSET which shifts when rows change:
Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, whose result positions can shift as rows change:
```php
User::where('active', false)->chunkById(200, function ($users) {
@@ -91,11 +97,14 @@ User::where('active', false)->chunkById(200, function ($users) {
});
```
## Add Database Indexes
For read-only, attribute-only iteration, `cursor()` hydrates models individually from one query, although some database drivers still buffer raw results. Use `lazy()` when relationships must be eager loaded in chunks, and use `lazyById()` or `chunkById()` when updates can affect query membership. See the collection rules for detailed tradeoffs.
Index columns that appear in `WHERE`, `ORDER BY`, `JOIN`, and `GROUP BY` clauses.
## Add Indexes for Measured Query Patterns
Design indexes around frequent, performance-sensitive query patterns. A column's presence in `WHERE`, `ORDER BY`, `JOIN`, or `GROUP BY` does not by itself justify an index; selectivity, write cost, existing indexes, and the database query plan all matter.
Schema without an application-specific query index:
Incorrect:
```php
Schema::create('orders', function (Blueprint $table) {
$table->id();
@@ -105,24 +114,26 @@ Schema::create('orders', function (Blueprint $table) {
});
```
Correct:
Schema optimized for `WHERE status = ? ORDER BY created_at`:
```php
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->index()->constrained();
$table->string('status')->index();
$table->foreignId('user_id')->constrained();
$table->string('status');
$table->timestamps();
$table->index(['status', 'created_at']);
});
```
Add composite indexes for common query patterns (e.g., `WHERE status = ? ORDER BY created_at`).
Confirm composite index column order and effectiveness with production-like data and the database's query-plan tools. Also check whether the database already created an index to support a foreign key before adding another one.
## Use `withCount()` for Counting Relations
## Count Relationships Without Loading Them
Never load entire collections just to count them.
Use `withCount()` when only relationship counts are needed; loading and hydrating every related model wastes memory.
Loads related models:
Incorrect:
```php
$posts = Post::all();
foreach ($posts as $post) {
@@ -130,7 +141,8 @@ foreach ($posts as $post) {
}
```
Correct:
Selects relationship counts:
```php
$posts = Post::withCount('comments')->get();
foreach ($posts as $post) {
@@ -149,39 +161,24 @@ $posts = Post::withCount([
])->get();
```
## Use `cursor()` for Memory-Efficient Iteration
## Keep Queries Out of Blade Templates
For read-only iteration over large result sets, `cursor()` loads one record at a time via a PHP generator.
Prepare data before rendering a Blade template, such as in a controller, query service, or view composer. This keeps query behavior visible and testable.
Incorrect:
```php
$users = User::where('active', true)->get();
```
Query in the template:
Correct:
```php
foreach (User::where('active', true)->cursor() as $user) {
ProcessUser::dispatch($user->id);
}
```
Use `cursor()` for read-only iteration. Use `chunk()` / `chunkById()` when modifying records.
## No Queries in Blade Templates
Never execute queries in Blade templates. Pass data from controllers.
Incorrect:
```blade
@foreach (User::all() as $user)
{{ $user->profile->name }}
@endforeach
```
Correct:
Data prepared before rendering:
```php
// Controller
$users = User::with('profile')->get();
return view('users.index', compact('users'));
```
@@ -1,8 +1,8 @@
# Eloquent Best Practices
## Use Correct Relationship Types
## Define Precise Relationship Types
Use `hasMany`, `belongsTo`, `morphMany`, etc. with proper return type hints.
Define the relationship that matches the database association, and declare its concrete return type.
```php
public function comments(): HasMany
@@ -20,7 +20,8 @@ public function author(): BelongsTo
Extract reusable query constraints into local scopes to avoid duplication.
Incorrect:
Duplicated constraints:
```php
$active = User::where('verified', true)->whereNotNull('activated_at')->get();
$articles = Article::whereHas('user', function ($q) {
@@ -28,9 +29,11 @@ $articles = Article::whereHas('user', function ($q) {
})->get();
```
Correct:
Reusable local scope:
```php
public function scopeActive(Builder $query): Builder
#[Scope]
protected function active(Builder $query): Builder
{
return $query->where('verified', true)->whereNotNull('activated_at');
}
@@ -44,7 +47,8 @@ $articles = Article::whereHas('user', fn ($q) => $q->active())->get();
Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy.
Incorrect (global scope for a conditional filter):
Global scope tradeoff:
```php
class PublishedScope implements Scope
{
@@ -53,12 +57,15 @@ class PublishedScope implements Scope
$builder->where('published', true);
}
}
// Now admin panels, reports, and background jobs all silently skip drafts
// Admin panels, reports, and jobs now omit drafts unless the scope is removed.
```
Correct (local scope you opt into):
Explicit local scope:
```php
public function scopePublished(Builder $query): Builder
#[Scope]
protected function published(Builder $query): Builder
{
return $query->where('published', true);
}
@@ -82,16 +89,18 @@ protected function casts(): array
}
```
## Cast Date Columns Properly
## Cast Date and Time Attributes
Always cast date columns. Use Carbon instances in templates instead of formatting strings manually.
Cast a date or timestamp attribute when application code should treat it as a Carbon instance. Eloquent already casts the conventional `created_at` and `updated_at` timestamps.
Manual parsing in the template:
Incorrect:
```blade
{{ Carbon::createFromFormat('Y-d-m H-i', $order->ordered_at)->toDateString() }}
{{ Carbon::parse($order->ordered_at)->toDateString() }}
```
Correct:
Model cast:
```php
protected function casts(): array
{
@@ -108,24 +117,27 @@ protected function casts(): array
## Use `whereBelongsTo()` for Relationship Queries
Cleaner than manually specifying foreign keys.
`whereBelongsTo()` expresses the relationship constraint without manually specifying its foreign key.
Foreign key constraint:
Incorrect:
```php
Post::where('user_id', $user->id)->get();
```
Correct:
Relationship-aware constraint:
```php
Post::whereBelongsTo($user)->get();
Post::whereBelongsTo($user, 'author')->get();
```
## Avoid Hardcoded Table Names in Queries
## Keep Application Queries Model-Aware
Never use string literals for table names in raw queries, joins, or subqueries. Hardcoded table names make it impossible to find all places a model is used and break refactoring (e.g., renaming a table requires hunting through every raw string).
Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL legitimately require table names, so use them when their lower-level behavior is intentional.
Lower-level alternatives:
Incorrect:
```php
DB::table('users')->where('active', true)->get();
@@ -134,15 +146,13 @@ $query->join('companies', 'companies.id', '=', 'users.company_id');
DB::select('SELECT * FROM orders WHERE status = ?', ['pending']);
```
Correct — reference the model's table:
```php
DB::table((new User)->getTable())->where('active', true)->get();
Model-aware queries:
// Even better — use Eloquent or the query builder instead of raw SQL
```php
User::where('active', true)->get();
Order::where('status', 'pending')->get();
```
Prefer Eloquent queries and relationships over `DB::table()` whenever possible — they already reference the model's table. When `DB::table()` or raw joins are unavoidable, always use `(new Model)->getTable()` to keep the reference traceable.
When a query builder operation should follow a model's configured table name, use `(new User)->getTable()`. For complex joins or raw SQL, explicit table names may be clearer; keep those references covered by tests when schema changes are possible.
**Exception — migrations:** In migrations, hardcoded table names via `DB::table('settings')` are acceptable and preferred. Models change over time but migrations are frozen snapshots — referencing a model that is later renamed or deleted would break the migration.
In migrations, use explicit table names rather than application models. Migrations are historical snapshots, while models and their scopes can change after a migration is deployed.
@@ -1,15 +1,18 @@
# Error Handling Best Practices
## Exception Reporting and Rendering
## Choose Where to Report and Render Exceptions
There are two valid approaches — choose one and apply it consistently across the project.
Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern already established by the project.
**Co-location on the exception class** — keeps behavior alongside the exception definition, easier to find:
Exception methods keep behavior beside the exception definition:
```php
class InvalidOrderException extends Exception
{
public function report(): void { /* custom reporting */ }
public function report(): void
{
// Send the exception to a custom reporter.
}
public function render(Request $request): Response
{
@@ -18,38 +21,40 @@ class InvalidOrderException extends Exception
}
```
**Centralized in `bootstrap/app.php`** — all exception handling in one place, easier to see the full picture:
Centralized callbacks in `bootstrap/app.php` keep the application's exception policy together:
```php
->withExceptions(function (Exceptions $exceptions) {
$exceptions->report(function (InvalidOrderException $e) { /* ... */ });
$exceptions->report(function (InvalidOrderException $e) {
// Send the exception to a custom reporter.
});
$exceptions->render(function (InvalidOrderException $e, Request $request) {
return response()->view('errors.invalid-order', status: 422);
});
})
```
Check the existing codebase and follow whichever pattern is already established.
An exception's `report()` method suppresses Laravel's default reporting unless it returns `false`. A report callback allows default reporting unless it returns `false` or is chained with `stop()`. Use `ShouldntReport` or `dontReport()` when the handler should not report an exception at all. By contrast, returning `false` from a `render()` method or render callback defers to Laravel's default rendering.
## Use `ShouldntReport` for Exceptions That Should Never Log
## Mark Exceptions the Handler Should Not Report
More discoverable than listing classes in `dontReport()`.
Implementing `ShouldntReport` prevents Laravel's exception handler from reporting that exception type and keeps the policy visible on the class. It does not prevent application code from logging the exception explicitly.
```php
class PodcastProcessingException extends Exception implements ShouldntReport {}
```
## Throttle High-Volume Exceptions
## Throttle High-Volume Exception Reports
A single failing integration can flood error tracking. Use `throttle()` to rate-limit per exception type.
A failing integration can flood logs or error tracking. Configure `throttle()` with a `Lottery` or `Limit` result to sample or rate-limit matching exception reports. Choose keys deliberately when separate exception classes, tenants, or integrations need independent limits.
## Enable `dontReportDuplicates()`
## Prevent Duplicate Reports of One Exception Instance
Prevents the same exception instance from being logged multiple times when `report($e)` is called in multiple catch blocks.
Enable `dontReportDuplicates()` when the same exception object may pass through multiple `report($exception)` calls. It deduplicates by object identity, not by exception class or message.
## Force JSON Error Rendering for API Routes
## Define JSON Rendering for API Routes
Laravel auto-detects `Accept: application/json` but API clients may not set it. Explicitly declare JSON rendering for API routes.
Laravel normally uses request content negotiation to decide whether to render an exception as JSON. If the application's API contract requires JSON regardless of the `Accept` header, define that policy explicitly for the relevant routes.
```php
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
@@ -59,7 +64,7 @@ $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
## Add Context to Exception Classes
Attach structured data to exceptions at the source via a `context()` method — Laravel includes it automatically in the log entry.
Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it.
```php
class InvalidOrderException extends Exception
@@ -1,24 +1,24 @@
# Events & Notifications Best Practices
# Events and Notifications Best Practices
## Rely on Event Discovery
Laravel auto-discovers listeners by reading `handle(EventType $event)` type-hints. No manual registration needed in `AppServiceProvider`.
Laravel discovers listeners in the configured listener directories by inspecting type-hinted event arguments on `handle()` or `__invoke()` methods. Register listeners manually only when discovery is disabled, the listener is outside those directories, or explicit registration is clearer.
## Run `event:cache` in Production Deploy
## Cache Event Discovery During Production Deployment
Event discovery scans the filesystem per-request in dev. Cache it in production: `php artisan optimize` or `php artisan event:cache`.
Cache discovered listeners during production deployment with `php artisan optimize` or `php artisan event:cache`. Rebuild the cache whenever listener definitions change.
## Use `ShouldDispatchAfterCommit` Inside Transactions
Without it, a queued listener may process before the DB transaction commits, reading data that doesn't exist yet.
When an event is dispatched inside a database transaction, `ShouldDispatchAfterCommit` delays dispatch until all open database transactions commit. If a transaction rolls back, Laravel discards the event. This affects synchronous and queued listeners; it is not limited to queue timing.
```php
class OrderShipped implements ShouldDispatchAfterCommit {}
```
## Always Queue Notifications
## Queue Slow Notifications
Notifications often hit external APIs (email, SMS, Slack). Without `ShouldQueue`, they block the HTTP response.
Queue notifications that call external services, such as email, text messaging, or Slack, when they do not need to complete before the response. Keep a notification synchronous when immediate completion or failure feedback is part of the operation.
```php
class InvoicePaid extends Notification implements ShouldQueue
@@ -27,9 +27,9 @@ class InvoicePaid extends Notification implements ShouldQueue
}
```
## Use `afterCommit()` on Notifications in Transactions
## Dispatch Queued Notifications After Commit
Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.
A queued notification sent inside a database transaction can run before the transaction commits. Call `afterCommit()` on the queued notification, or enable the queue connection's `after_commit` option, when its delivery depends on committed data. This setting has no scheduling effect on a synchronous notification.
```php
$user->notify((new InvoicePaid($invoice))->afterCommit());
@@ -37,7 +37,7 @@ $user->notify((new InvoicePaid($invoice))->afterCommit());
## Route Notification Channels to Dedicated Queues
Mail and database notifications have different priorities. Use `viaQueues()` to route them to separate queues.
Different notification channels can have different latency and priority requirements. Implement `viaQueues()` when channels should use separate queues.
## Use On-Demand Notifications for Non-User Recipients
@@ -49,4 +49,4 @@ Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
## Implement `HasLocalePreference` on Notifiable Models
Laravel automatically uses the user's preferred locale for all notifications and mailables — no per-call `locale()` needed.
Implement `HasLocalePreference::preferredLocale()` on a notifiable model when notifications and mailables should use the recipient's locale. Laravel also preserves that locale for queued delivery. An explicit `locale()` call can still override the preference for an individual notification.
@@ -1,86 +1,100 @@
# HTTP Client Best Practices
## Always Set Explicit Timeouts
## Set Explicit Timeouts
The default timeout is 30 seconds — too long for most API calls. Always set explicit `timeout` and `connectTimeout` to fail fast.
Laravel's HTTP client has a 30-second response timeout by default. Choose response and connection timeouts that fit the service and the calling request or job. Remember that retries can multiply the total elapsed time.
Less resilient:
Incorrect:
```php
$response = Http::get('https://api.example.com/users');
```
Correct:
Preferred:
```php
$response = Http::timeout(5)
->connectTimeout(3)
$response = Http::connectTimeout(3)
->timeout(5)
->get('https://api.example.com/users');
```
For service-specific clients, define timeouts in a macro:
Define shared settings in a macro or a dedicated client:
```php
Http::macro('github', function () {
return Http::baseUrl('https://api.github.com')
->timeout(10)
->connectTimeout(3)
->timeout(10)
->withToken(config('services.github.token'));
});
$response = Http::github()->get('/repos/laravel/framework');
```
## Use Retry with Backoff for External APIs
## Retry Only Safe Operations
External APIs have transient failures. Use `retry()` with increasing delays.
Retry transient connection failures, rate-limit responses, and server errors with an appropriate delay. Retry idempotent requests such as `GET` when the operation can safely run more than once. Retry a state-changing request only when the remote API supports an idempotency key or provides equivalent duplicate protection.
Incorrect:
```php
$response = Http::post('https://api.stripe.com/v1/charges', $data);
Unsafe without an idempotency guarantee:
if ($response->failed()) {
throw new PaymentFailedException('Charge failed');
}
```
Correct:
```php
$response = Http::retry([100, 500, 1000])
->timeout(10)
->post('https://api.stripe.com/v1/charges', $data);
->post('https://api.example.com/v1/charges', $data);
```
Only retry on specific errors:
Safe for an idempotent request:
```php
$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
return $exception instanceof ConnectionException
|| ($exception instanceof RequestException && $exception->response->serverError());
})->post('https://api.example.com/data');
$response = Http::connectTimeout(3)
->timeout(10)
->retry([100, 500, 1000], 0, function (Throwable $exception) {
return $exception instanceof ConnectionException
|| ($exception instanceof RequestException
&& ($exception->response->serverError() || $exception->response->status() === 429));
})
->get('https://api.example.com/data');
```
For a supported state-changing API, send a stable idempotency key for every attempt:
```php
$response = Http::withHeaders(['Idempotency-Key' => $paymentAttempt->uuid])
->connectTimeout(3)
->timeout(10)
->retry([100, 500, 1000], 0, function (Throwable $exception) {
return $exception instanceof ConnectionException
|| ($exception instanceof RequestException
&& ($exception->response->serverError() || $exception->response->status() === 429));
})
->post('https://api.example.com/v1/charges', $data);
```
## Handle Errors Explicitly
The HTTP Client does not throw on 4xx/5xx by default. Always check status or use `throw()`.
The HTTP client returns responses for `4xx` and `5xx` status codes instead of throwing by default. Inspect the expected statuses or call `throw()` before consuming a success payload.
Unsafe when a success payload is expected:
Incorrect:
```php
$response = Http::get('https://api.example.com/users/1');
$user = $response->json(); // Could be an error body
$user = Http::get('https://api.example.com/users/1')->json();
```
Correct:
Preferred:
```php
$response = Http::timeout(5)
$user = Http::connectTimeout(3)
->timeout(5)
->get('https://api.example.com/users/1')
->throw();
$user = $response->json();
->throw()
->json();
```
For graceful degradation:
Handle expected alternatives explicitly when graceful degradation is required:
```php
$response = Http::get('https://api.example.com/users/1');
$response = Http::connectTimeout(3)
->timeout(5)
->get('https://api.example.com/users/1');
if ($response->successful()) {
return $response->json();
@@ -93,46 +107,30 @@ if ($response->notFound()) {
$response->throw();
```
## Use Request Pooling for Concurrent Requests
## Pool Independent Requests
When making multiple independent API calls, use `Http::pool()` instead of sequential calls.
Use `Http::pool()` when several independent requests can run concurrently. Pooling changes execution time, not error handling; inspect or throw for each response as needed.
Incorrect:
```php
$users = Http::get('https://api.example.com/users')->json();
$posts = Http::get('https://api.example.com/posts')->json();
$comments = Http::get('https://api.example.com/comments')->json();
```
Correct:
```php
use Illuminate\Http\Client\Pool;
$responses = Http::pool(fn (Pool $pool) => [
$pool->as('users')->get('https://api.example.com/users'),
$pool->as('posts')->get('https://api.example.com/posts'),
$pool->as('comments')->get('https://api.example.com/comments'),
$pool->as('users')->connectTimeout(3)->timeout(5)
->get('https://api.example.com/users'),
$pool->as('posts')->connectTimeout(3)->timeout(5)
->get('https://api.example.com/posts'),
]);
$users = $responses['users']->json();
$posts = $responses['posts']->json();
$users = $responses['users']->throw()->json();
$posts = $responses['posts']->throw()->json();
```
## Fake HTTP Calls in Tests
## Fake HTTP Requests in Tests
Never make real HTTP requests in tests. Use `Http::fake()` and `preventStrayRequests()`.
Use `Http::fake()` for external integrations, and use `Http::preventStrayRequests()` when an unexpected real request should fail the test. Also test timeouts, connection failures, and error responses that the application handles.
Incorrect:
```php
it('syncs user from API', function () {
$service = new UserSyncService;
$service->sync(1); // Hits the real API
});
```
Correct:
```php
it('syncs user from API', function () {
it('syncs a user from the API', function () {
Http::preventStrayRequests();
Http::fake([
@@ -142,16 +140,15 @@ it('syncs user from API', function () {
]),
]);
$service = new UserSyncService;
$service->sync(1);
(new UserSyncService)->sync(1);
Http::assertSent(function (Request $request) {
return $request->url() === 'https://api.example.com/users/1';
});
Http::assertSent(fn (Request $request) =>
$request->url() === 'https://api.example.com/users/1'
);
});
```
Test failure scenarios too:
For example, fake a connection failure when testing the integration's failure path:
```php
Http::fake([
@@ -1,27 +1,54 @@
# Mail Best Practices
## Implement `ShouldQueue` on the Mailable Class
## Queue Slow Mail Delivery
Makes queueing the default regardless of how the mailable is dispatched. No need to remember `Mail::queue()` at every call site — `Mail::send()` also queues it.
Implement `ShouldQueue` on a mailable when delivery should normally happen in the background. Laravel queues that mailable even when the call site uses `Mail::send()`.
## Use `afterCommit()` on Mailables Inside Transactions
```php
class OrderShipped extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
}
```
A queued mailable dispatched inside a transaction may process before the commit. Use `$this->afterCommit()` in the constructor.
Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available.
## Use `assertQueued()` Not `assertSent()` for Queued Mailables
## Dispatch Queued Mail After Commit
`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.
A queued mailable dispatched during a database transaction can be processed before the transaction commits. Call `afterCommit()` on the mailable, or enable the queue connection's `after_commit` option, when the mail depends on committed records.
Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.
```php
Mail::to($user)->send(
(new OrderShipped($order))->afterCommit()
);
```
Correct: `Mail::assertQueued(OrderShipped::class);`
If the transaction rolls back, an after-commit mailable is not dispatched. This setting affects queued mail only; it does not defer synchronous delivery.
## Use Markdown Mailables for Transactional Emails
## Assert the Delivery Mode
Markdown mailables auto-generate both HTML and plain-text versions, use responsive components, and allow global style customization. Generate with `--markdown` flag.
Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables.
## Separate Content Tests from Sending Tests
Incorrect for a mailable that implements `ShouldQueue`:
Content tests: instantiate the mailable directly, call `assertSeeInHtml()`.
Sending tests: use `Mail::fake()` and `assertSent()`/`assertQueued()`.
Don't mix them — it conflates concerns and makes tests brittle.
```php
Mail::assertSent(OrderShipped::class);
```
Correct:
```php
Mail::assertQueued(OrderShipped::class);
```
## Use Markdown Mailables When They Fit
Markdown mailables render HTML and plain-text versions from Laravel's mail components and support publishable themes. They are useful for conventional transactional messages, but a custom HTML and text pair may be more appropriate for a specialized design.
```bash
php artisan make:mail OrderShipped --markdown=mail.orders.shipped
```
## Separate Content and Delivery Tests
Test rendered content by instantiating the mailable and using assertions such as `assertSeeInHtml()` and `assertSeeInText()`. Test delivery separately with `Mail::fake()` and `assertSent()` or `assertQueued()` so failures identify the affected behavior.
@@ -2,76 +2,51 @@
## Generate Migrations with Artisan
Always use `php artisan make:migration` for consistent naming and timestamps.
Use `php artisan make:migration` to generate the timestamped filename and migration structure.
Incorrect (manually created file):
```php
// database/migrations/posts_migration.php ← wrong naming, no timestamp
```
Correct (Artisan-generated):
```bash
php artisan make:migration create_posts_table
php artisan make:migration add_slug_to_posts_table
```
## Use `constrained()` for Foreign Keys
## Define Foreign-Key Constraints Deliberately
Automatic naming and referential integrity.
Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not.
```php
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
// Non-standard names
$table->foreignId('author_id')->constrained('users');
```
## Never Modify Deployed Migrations
Do not add a duplicate single-column index without checking the database driver's treatment of foreign-key indexes and the indexes already created by the migration.
Once a migration has run in production, treat it as immutable. Create a new migration to change the table.
## Treat Deployed Migrations as Immutable
After a migration has run in a shared or production environment, create a new migration for subsequent changes. Editing the old file makes fresh installations differ from upgraded installations.
For a local migration that has not been shared or deployed, editing and rerunning it may be simpler.
## Design Indexes for Real Queries
Add indexes based on query patterns, selectivity, write cost, and the database's ability to use composite indexes. A column appearing in `WHERE`, `ORDER BY`, or `JOIN` does not automatically need its own index.
Declare each selected index in the schema migration that creates or changes the relevant table. Confirm important indexes with representative data and the database's query plan, and avoid redundant indexes whose leading columns duplicate an existing index without serving a distinct query. See the database performance and advanced query rules for index selection and column-order guidance.
## Stage Changes That Affect Existing Rows
Adding a required or unique column to a populated table often needs multiple deployment-safe steps. Add a nullable column, deploy code that can handle both states, backfill existing rows in bounded chunks, then add the required constraint or index after the data is valid.
Do not assume this migration is safe on a populated table:
Incorrect (editing a deployed migration):
```php
// 2024_01_01_create_posts_table.php — already in production
$table->string('slug')->unique(); // ← added after deployment
$table->string('slug')->unique();
```
Correct (new migration to alter):
```php
// 2024_03_15_add_slug_to_posts_table.php
Schema::table('posts', function (Blueprint $table) {
$table->string('slug')->unique()->after('title');
});
```
Large backfills are usually better implemented as an observable, restartable command or job than inside a schema migration. Small deterministic data changes may be reasonable in a migration when their locking, transaction, and deployment behavior is understood.
## Add Indexes in the Migration
## Mirror Defaults Only When Unsaved Models Need Them
Add indexes when creating the table, not as an afterthought. Columns used in `WHERE`, `ORDER BY`, and `JOIN` clauses need indexes.
Incorrect:
```php
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('status');
$table->timestamps();
});
```
Correct:
```php
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->index();
$table->string('status')->index();
$table->timestamp('shipped_at')->nullable()->index();
$table->timestamps();
});
```
## Mirror Defaults in Model `$attributes`
When a column has a database default, mirror it in the model so new instances have correct values before saving.
A database default is applied when a row is inserted, not when a model is instantiated. Mirror the value in the model's `$attributes` only when application code must observe that default before persistence, and keep both definitions synchronized.
```php
// Migration
@@ -83,39 +58,10 @@ protected $attributes = [
];
```
## Write Reversible `down()` Methods by Default
## Make Rollbacks Honest
Implement `down()` for schema changes that can be safely reversed so `migrate:rollback` works in CI and failed deployments.
```php
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('slug');
});
}
```
For intentionally irreversible migrations (e.g., destructive data backfills), leave a clear comment and require a forward fix migration instead of pretending rollback is supported.
Implement `down()` when the change can be safely reversed. A rollback that drops populated columns or cannot restore transformed data is destructive even if it is syntactically reversible; document that limitation and prefer a forward-fix migration in production.
## Keep Migrations Focused
One concern per migration. Never mix DDL (schema changes) and DML (data manipulation).
Incorrect (partial failure creates unrecoverable state):
```php
public function up(): void
{
Schema::create('settings', function (Blueprint $table) { ... });
DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
}
```
Correct (separate migrations):
```php
// Migration 1: create_settings_table
Schema::create('settings', function (Blueprint $table) { ... });
// Migration 2: seed_default_settings
DB::table('settings')->insert(['key' => 'version', 'value' => '1.0']);
```
Keep each migration small enough to reason about, deploy, and reverse. Separate long-running backfills from schema changes when doing so reduces locks and supports phased deployment, but do not split related operations merely to enforce a blanket separation between data definition and data manipulation.
@@ -1,82 +1,82 @@
# Queue & Job Best Practices
# Queue and Job Best Practices
## Set `retry_after` Greater Than `timeout`
## Keep Reservation Time Longer Than Execution Time
If `retry_after` is shorter than the job's `timeout`, the queue worker re-dispatches the job while it's still running, causing duplicate execution.
For queue drivers that use Laravel's `retry_after` setting, configure it to exceed the longest worker or job timeout by a safety margin. When a reservation expires, another worker can reserve the same job while the first process is still running. Keep the worker's `--timeout` several seconds shorter than `retry_after`.
Incorrect (`retry_after` ≤ `timeout`):
```php
class ProcessReport implements ShouldQueue
{
public $timeout = 120;
}
// Job
public $timeout = 120;
// config/queue.php — retry_after: 90 ← job retried while still running!
// config/queue.php for the connection
'retry_after' => 150,
```
Correct (`retry_after` > `timeout`):
```php
class ProcessReport implements ShouldQueue
{
public $timeout = 120;
}
Amazon Simple Queue Service uses its visibility timeout instead of Laravel's `retry_after`; configure that timeout at the queue level. Because workers can also stop after side effects but before acknowledging a job, make important jobs idempotent even with correct timeout settings.
// config/queue.php — retry_after: 180 ← safely longer than any job timeout
```
## Back Off Transient Failures
## Use Exponential Backoff
Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures.
Use progressively longer delays between retries to avoid hammering failing services.
Incorrect (fixed retry interval):
```php
class SyncWithStripe implements ShouldQueue
{
public $tries = 3;
// Default: retries immediately, overwhelming the API
}
```
public $tries = 4;
Correct (exponential backoff):
```php
class SyncWithStripe implements ShouldQueue
{
public $tries = 3;
public $backoff = [1, 5, 10];
}
```
## Implement `ShouldBeUnique`
Rate-limiting and exception-throttling middleware can release jobs back to the queue. Released attempts may still count toward the maximum attempt limit, so configure `$tries` or `retryUntil()` to allow the intended retry window.
Prevent duplicate job processing.
## Use Unique Jobs for Dispatch Deduplication
Implement `ShouldBeUnique` when only one queued instance of a logical job should exist. Uniqueness uses a cache lock and is not a substitute for idempotent processing or a database constraint.
```php
class GenerateInvoice implements ShouldQueue, ShouldBeUnique
{
public $uniqueFor = 3600;
public function uniqueId(): string
{
return $this->order->id;
return (string) $this->order->id;
}
public $uniqueFor = 3600;
}
```
## Always Implement `failed()`
All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches.
Handle errors explicitly — don't rely on silent failure.
Use `ShouldBeUniqueUntilProcessing` only when the lock should be released immediately before processing begins, allowing another instance to be dispatched while the first is running:
```php
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
{
// ...
}
```
## Handle Terminal Failure When Needed
Implement `failed()` when the application must update state, alert an operator, or record domain-specific context after all attempts are exhausted. Logging every failure in each job may duplicate the queue system's failure reporting.
Laravel invokes `failed()` on a new job instance, so mutations made to the job during `handle()` are not available there.
```php
public function failed(?Throwable $exception): void
{
$this->podcast->update(['status' => 'failed']);
Log::error('Processing failed', ['id' => $this->podcast->id, 'error' => $exception->getMessage()]);
Log::error('Podcast processing failed', [
'podcast_id' => $this->podcast->id,
'exception' => $exception,
]);
}
```
## Rate Limit External API Calls in Jobs
## Rate Limit External Calls
Use `RateLimited` middleware to throttle jobs calling third-party APIs.
Use queue middleware such as `RateLimited` when jobs share a third-party API quota. Define the named limiter and choose release delays and attempt limits together.
```php
public function middleware(): array
@@ -85,60 +85,33 @@ public function middleware(): array
}
```
## Batch Related Jobs
## Batch Jobs for Group Coordination
Use `Bus::batch()` when jobs should succeed or fail together.
Use `Bus::batch()` to monitor a group of jobs and run callbacks when the batch completes or encounters failures. A batch is not a database transaction: completed jobs are not rolled back when another job fails. By default, one failed job cancels the batch; call `allowFailures()` only when partial failure is acceptable.
```php
Bus::batch([
new ImportCsvChunk($chunk1),
new ImportCsvChunk($chunk2),
])
->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed'))
->dispatch();
->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
->catch(fn (Batch $batch, Throwable $exception) => Log::error('Import batch failed', [
'exception' => $exception,
]))
->dispatch();
```
## `retryUntil()` Needs `$tries = 0`
## Configure Time-Based Retry Limits Deliberately
When using time-based retry limits, set `$tries = 0` to avoid premature failure.
Use `retryUntil()` as the time-based alternative to a maximum attempt count. Laravel may attempt the job any number of times until this deadline, subject to other failure conditions such as maximum exceptions. The method takes precedence over attempt-based limits, so setting `$tries = 0` is not required.
```php
public $tries = 0;
public function retryUntil(): \DateTimeInterface
public function retryUntil(): DateTimeInterface
{
return now()->addHours(4);
}
```
## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release
## Use Horizon for Redis Queue Operations
`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue.
```php
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
{
// Lock releases when processing begins, not when it finishes
}
```
## Use Horizon for Complex Queue Scenarios
Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.
```php
// config/horizon.php
'environments' => [
'production' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['high', 'default', 'low'],
'balance' => 'auto',
'minProcesses' => 1,
'maxProcesses' => 10,
'tries' => 3,
],
],
],
```
Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers.
@@ -1,99 +1,106 @@
# Routing & Controllers Best Practices
# Routing and Controller Best Practices
## Use Implicit Route Model Binding
Let Laravel resolve models automatically from route parameters.
Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint.
Instead of manual lookup:
Incorrect:
```php
public function show(int $id)
public function show(int $id): View
{
$post = Post::findOrFail($id);
return view('posts.show', ['post' => $post]);
}
```
Correct:
Use route model binding:
```php
public function show(Post $post)
public function show(Post $post): View
{
return view('posts.show', ['post' => $post]);
}
```
## Use Scoped Bindings for Nested Resources
## Scope Nested Bindings
Enforce parent-child relationships automatically.
Use scoped bindings when a nested resource must belong to its parent. This constrains model resolution; it does not replace authorization.
```php
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
// $post is automatically scoped to $user
// The resolved post belongs to the resolved user.
})->scopeBindings();
```
## Use Resource Controllers
## Use Resource Routes for Resourceful Actions
Use `Route::resource()` or `apiResource()` for RESTful endpoints.
Use `Route::resource()` or `Route::apiResource()` when the endpoint follows Laravel's resource-controller actions. Define explicit routes when the behavior does not fit that vocabulary.
```php
Route::resource('posts', PostController::class);
// In routes/api.php — the /api prefix is applied automatically
Route::apiResource('posts', Api\PostController::class);
// Alternatively, for an API-only resource:
Route::apiResource('posts', ApiPostController::class);
```
## Keep Controllers Thin
`apiResource()` omits the HTML-oriented `create` and `edit` routes. It does not itself add an `/api` prefix; that prefix comes from the application's API route configuration.
Aim for under 10 lines per method. Extract business logic to action or service classes.
## Organize Controllers Around Resources
As a general default, organize each controller around one resource and use Laravel's standard resource actions: `index`, `show`, `create`, `store`, `edit`, `update`, and `destroy`. This keeps routes predictable and prevents controllers from accumulating unrelated behavior.
When a controller needs a custom action such as `publish`, `approve`, or `archive`, first consider whether that behavior represents a separate resource. A focused resource controller gives the behavior its own authorization, validation, and middleware boundary.
Custom action on the primary controller:
Incorrect:
```php
public function store(Request $request)
Route::post('/podcasts/{podcast}/publish', [PodcastController::class, 'publish']);
```
The published podcast modeled as a resource:
```php
Route::post('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'store'])
->name('published-podcasts.store');
Route::delete('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'destroy'])
->name('published-podcasts.destroy');
```
```php
class PublishedPodcastController extends Controller
{
$validated = $request->validate([...]);
if ($request->hasFile('image')) {
$request->file('image')->move(public_path('images'));
public function store(Podcast $podcast): RedirectResponse
{
$podcast->publish();
return back();
}
public function destroy(Podcast $podcast): RedirectResponse
{
$podcast->unpublish();
return back();
}
$post = Post::create($validated);
$post->tags()->sync($validated['tags']);
event(new PostCreated($post));
return redirect()->route('posts.show', $post);
}
```
Correct:
Treat a custom verb as a design signal, not proof that another controller is required. Use query parameters for simple filtering, and keep an explicit action route when modeling the operation as a resource would obscure the domain or conflict with established project conventions.
## Keep Controllers Focused on HTTP Concerns
Controllers should coordinate HTTP input, authorization, validation, an application operation, and the response. Extract substantial or reusable business logic, but do not introduce an action or service merely to satisfy an arbitrary line limit.
```php
public function store(StorePostRequest $request, CreatePostAction $create)
public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse
{
$post = $create->execute($request->validated());
$post = $create->handle($request->validated());
return redirect()->route('posts.show', $post);
}
```
## Type-Hint Form Requests
Type-hinting Form Requests triggers automatic validation and authorization before the method executes.
Incorrect:
```php
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'title' => ['required', 'max:255'],
'body' => ['required'],
]);
Post::create($validated);
return redirect()->route('posts.index');
}
```
Correct:
```php
public function store(StorePostRequest $request): RedirectResponse
{
Post::create($request->validated());
return redirect()->route('posts.index');
}
```
A form request can perform validation and authorization before the controller runs. Do not repeat its rules in the controller. Keep simple, endpoint-specific validation inline when extraction would not improve reuse or clarity; see the validation rules for detailed guidance.
@@ -1,32 +1,50 @@
# Task Scheduling Best Practices
## Use `withoutOverlapping()` on Variable-Duration Tasks
## Prevent Unwanted Overlap
Without it, a long-running task spawns a second instance on the next tick, causing double-processing or resource exhaustion.
## Use `onOneServer()` on Multi-Server Deployments
Without it, every server runs the same task simultaneously. Requires a shared cache driver (Redis, database, Memcached).
## Use `runInBackground()` for Concurrent Long Tasks
By default, tasks at the same tick run sequentially. A slow first task delays all subsequent ones. `runInBackground()` runs them as separate processes.
## Use `environments()` to Restrict Tasks
Prevent accidental execution of production-only tasks (billing, reporting) on staging.
Use `withoutOverlapping()` when a second run must not begin while the previous run holds the lock. This is appropriate for variable-duration tasks that are not safe to run concurrently.
```php
Schedule::command('billing:charge')->monthly()->environments(['production']);
Schedule::command('reports:generate')
->everyFifteenMinutes()
->withoutOverlapping(30);
```
## Use `takeUntilTimeout()` for Time-Bounded Processing
The optional value is the lock expiration time in minutes, not the task timeout. Choose it carefully: the default is 24 hours, stale locks can be cleared with `php artisan schedule:clear-cache`, and an expiration that is too short can permit overlap while the first task still runs. The task itself should still tolerate retries and partial execution where practical.
A task running every 15 minutes that processes an unbounded cursor can overlap with the next run. Bound execution time.
## Run a Task on One Server
## Use Schedule Groups for Shared Configuration
Use `onOneServer()` when only one scheduler node should run an eligible task. Scheduler nodes must use the same default cache store, and that store must support atomic locks. Supported stores include `database`, `memcached`, `dynamodb`, and `redis`.
Avoid repeating `->onOneServer()->timezone('America/New_York')` across many tasks.
```php
Schedule::command('billing:charge')->daily()->onOneServer();
```
Name scheduled closures before applying `onOneServer()`, especially when scheduling the same closure with different parameters, so each task has a distinct lock identity.
## Run Eligible Commands in the Background
Tasks due at the same time run sequentially by default. Use `runInBackground()` when an independent, long-running scheduled command should not delay later tasks.
```php
Schedule::command('analytics:process')->hourly()->runInBackground();
```
Laravel restricts `runInBackground()` to tasks scheduled with `command()` and `exec()`; it is not available for scheduled closures. Ensure background processes have appropriate logging and failure monitoring.
## Restrict Tasks by Environment
Use `environments()` when a task should run only in named application environments. Treat this as an operational safeguard, not an authorization control.
```php
Schedule::command('billing:charge')
->monthly()
->environments(['production']);
```
## Group Shared Configuration
Use schedule groups when several tasks genuinely share frequency or constraints.
```php
Schedule::daily()
@@ -37,3 +55,7 @@ Schedule::daily()
Schedule::command('emails:prune');
});
```
## Bound Work Inside the Task
The scheduler does not provide a `takeUntilTimeout()` event method or terminate arbitrary tasks at a deadline. Bound work in the command or job itself by processing finite chunks, checking a deadline, or dispatching queue jobs with suitable timeouts. Use operating-system or process controls when hard termination is required.
@@ -1,18 +1,9 @@
# Security Best Practices
## Mass Assignment Protection
## Control Mass Assignment
Every model must define `$fillable` (whitelist) or `$guarded` (blacklist).
Define `$fillable` when a model is populated from request-derived arrays, or deliberately guard attributes by another consistent model convention. Laravel models guard all attributes by default; `$guarded = []` opts out of that protection.
Incorrect:
```php
class User extends Model
{
protected $guarded = []; // All fields are mass assignable
}
```
Correct:
```php
class User extends Model
{
@@ -24,82 +15,71 @@ class User extends Model
}
```
Never use `$guarded = []` on models that accept user input.
Do not pass untrusted request data to a model with `$guarded = []`. Mass-assignment protection controls which attributes `create()`, `fill()`, and `update()` may set; it does not validate values or authorize the operation.
## Authorize Every Action
## Authorize Protected Actions
Use policies or gates in controllers. Never skip authorization.
Use policies, gates, or form request authorization for actions that depend on the current user's permissions. Authentication alone does not establish permission, and validation is not authorization.
Incorrect:
```php
public function update(UpdatePostRequest $request, Post $post)
{
$post->update($request->validated());
}
```
Correct:
```php
public function update(UpdatePostRequest $request, Post $post)
public function update(UpdatePostRequest $request, Post $post): RedirectResponse
{
Gate::authorize('update', $post);
$post->update($request->validated());
return redirect()->route('posts.show', $post);
}
```
Or via Form Request:
Authorization may instead live in the form request:
```php
public function authorize(): bool
{
return $this->user()->can('update', $this->route('post'));
return $this->user()?->can('update', $this->route('post')) ?? false;
}
```
## Prevent SQL Injection
Public actions intentionally available to everyone do not need a redundant authorization check.
Always use parameter binding. Never interpolate user input into queries.
## Bind Query Parameters
Use Eloquent, the query builder, or explicit bindings instead of interpolating untrusted values into Structured Query Language (SQL). Bindings protect values, not identifiers such as column names or sort directions; map user-selected identifiers to an allow-list.
Incorrect:
```php
DB::select("SELECT * FROM users WHERE name = '{$request->name}'");
```
Correct:
```php
User::where('name', $request->name)->get();
// Raw expressions with bindings
User::whereRaw('LOWER(name) = ?', [strtolower($request->name)])->get();
User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();
```
## Escape Output to Prevent XSS
## Escape Output in Its Context
Use `{{ }}` for HTML escaping. Only use `{!! !!}` for trusted, pre-sanitized content.
Blade's `{{ }}` syntax HTML-escapes output. Use `{!! !!}` only for content that has been sanitized for the exact HTML context in which it is rendered. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets.
Incorrect for untrusted content:
Incorrect:
```blade
{!! $user->bio !!}
```
Correct:
```blade
{{ $user->bio }}
```
## CSRF Protection
## Apply Cross-Site Request Forgery Protection
Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.
Include `@csrf` in state-changing Blade forms handled by Laravel's `web` middleware. Routes intentionally excluded from cross-site request forgery (CSRF) verification, such as validated third-party webhooks, need their own authenticity check.
Incorrect:
```blade
<form method="POST" action="/posts">
<input type="text" name="title">
</form>
```
Correct:
```blade
<form method="POST" action="/posts">
@csrf
@@ -107,21 +87,27 @@ Correct:
</form>
```
## Rate Limit Auth and API Routes
Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. Confirm equivalent configuration when using another HTTP client. Do not disable CSRF protection merely to fix a token mismatch.
Apply `throttle` middleware to authentication and API routes.
## Rate Limit Sensitive Endpoints
Apply suitable rate limits to login attempts, password recovery, verification messages, and expensive or abuse-prone application programming interface (API) routes. Choose the limiter key deliberately; an Internet Protocol (IP) address alone can unfairly group users behind a shared network, while an account identifier alone can enable targeted denial of service.
```php
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->ip());
return Limit::perMinute(5)->by(Str::transliterate(
Str::lower($request->string('email')).'|'.$request->ip()
));
});
Route::post('/login', LoginController::class)->middleware('throttle:login');
```
## Validate File Uploads
Rate limiting reduces abuse; it does not replace authentication, authorization, or upstream denial-of-service protection.
Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.
## Validate and Store Uploads Safely
Validate expected content type, dimensions where relevant, and size. Laravel's `mimes` rule reads the file contents and guesses a Multipurpose Internet Mail Extensions (MIME) type corresponding to the listed extensions; it does not validate the user-assigned filename extension. The `extensions` rule checks that extension and should not be used by itself.
```php
public function rules(): array
@@ -132,56 +118,28 @@ public function rules(): array
}
```
Store with generated filenames:
Use Laravel's storage methods to generate a filename, and store untrusted files outside a publicly executable location. Public files can require additional controls, such as image re-encoding, content-disposition headers, and explicit blocking of active formats.
```php
$path = $request->file('avatar')->store('avatars', 'public');
$path = $request->file('avatar')->store('avatars');
```
## Keep Secrets Out of Code
## Keep Secrets Out of Application Code
Never commit `.env`. Access secrets via `config()` only.
Incorrect:
```php
$key = env('API_KEY');
```
Correct:
```php
// config/services.php
'api_key' => env('API_KEY'),
// In application code
$key = config('services.api_key');
```
Do not commit populated environment files or hard-code credentials. Read environment variables in configuration files, then use `config()` in application code so configuration caching works correctly. See the configuration rules for encrypted environment files and external secret stores.
## Audit Dependencies
Run `composer audit` periodically to check for known vulnerabilities in dependencies. Automate this in CI to catch issues before deployment.
Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.
```bash
composer audit
```
## Encrypt Sensitive Database Fields
## Encrypt Sensitive Attributes When Appropriate
Use `encrypted` cast for API keys/tokens and mark the attribute as `hidden`.
Use an `encrypted` cast for sensitive values that must be recoverable, and use `$hidden` to omit them from array and JavaScript Object Notation (JSON) serialization. Hidden attributes remain accessible in PHP, and encryption does not replace access control. Encrypted values cannot be meaningfully queried and should use a `TEXT` or larger column because ciphertext length is variable.
Incorrect:
```php
class Integration extends Model
{
protected function casts(): array
{
return [
'api_key' => 'string',
];
}
}
```
Correct:
```php
class Integration extends Model
{
@@ -1,125 +1,110 @@
# Conventions & Style
# Convention and Style Best Practices
## Follow Laravel Naming Conventions
## Follow Project Naming Conventions
| What | Convention | Good | Bad |
|------|-----------|------|-----|
| Controller | singular | `ArticleController` | `ArticlesController` |
| Model | singular | `User` | `Users` |
| Table | plural, snake_case | `article_comments` | `articleComments` |
| Pivot table | singular alphabetical | `article_user` | `user_article` |
| Column | snake_case, no model name | `meta_title` | `article_meta_title` |
| Foreign key | singular model + `_id` | `article_id` | `articles_id` |
| Route | plural | `articles/1` | `article/1` |
| Route name | snake_case with dots | `users.show_active` | `users.show-active` |
| Method | camelCase | `getAll` | `get_all` |
| Variable | camelCase | `$articlesWithAuthor` | `$articles_with_author` |
| Collection | descriptive, plural | `$activeUsers` | `$data` |
| Object | descriptive, singular | `$activeUser` | `$users` |
| View | kebab-case | `show-filtered.blade.php` | `showFiltered.blade.php` |
| Config | snake_case | `google_calendar.php` | `googleCalendar.php` |
| Enum | singular | `UserType` | `UserTypes` |
Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.
## Prefer Shorter Readable Syntax
| Element | Convention | Example |
| --- | --- | --- |
| Controller | Singular resource name | `ArticleController` |
| Model | Singular StudlyCase | `User` |
| Table | Plural snake_case | `article_comments` |
| Pivot table | Singular model names in alphabetical order, in snake_case | `article_user` |
| Column | snake_case | `meta_title` |
| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` |
| Resource URI | Plural resource | `articles/1` |
| Route name | Dotted segments; snake_case within a segment when needed | `users.show_active` |
| Method | camelCase | `getAll` |
| Variable | camelCase | `$articlesWithAuthor` |
| Collection | Descriptive and plural | `$activeUsers` |
| Object | Descriptive and singular | `$activeUser` |
| View | kebab-case | `show-filtered.blade.php` |
| Configuration file | snake_case | `google_calendar.php` |
| Enumeration | Singular StudlyCase | `UserType` |
| Verbose | Shorter |
|---------|---------|
## Prefer Clear, Idiomatic Syntax
Use Laravel helpers and query methods when they communicate intent more directly. Do not shorten code when the result is ambiguous or loses useful type information.
| More verbose | Idiomatic alternative |
| --- | --- |
| `Session::get('cart')` | `session('cart')` |
| `$request->session()->get('cart')` | `session('cart')` |
| `$request->input('name')` | `$request->name` |
| `return Redirect::back()` | `return back()` |
| `Carbon::now()` | `now()` |
| `App::make('Class')` | `app('Class')` |
| `->where('column', '=', 1)` | `->where('column', 1)` |
| `->orderBy('created_at', 'desc')` | `->latest()` |
| `->orderBy('created_at', 'asc')` | `->oldest()` |
| `->first()->name` | `->value('name')` |
| `->first()?->name` | `->value('name')` when only that value is needed |
## Use Laravel String & Array Helpers
Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation.
Laravel provides `Str`, `Arr`, `Number`, and `Uri` helper classes that are more readable, chainable, and UTF-8 safe than raw PHP functions. Always prefer them.
## Use Utilities When They Clarify Intent
Laravel's `Str`, `Arr`, `Number`, and `Uri` utilities provide expressive operations and framework-consistent behavior. Prefer them when they are clearer or safer than an equivalent PHP operation, not as an unconditional replacement for every built-in function.
Strings — use `Str` and fluent `Str::of()` over raw PHP:
```php
// Incorrect
$slug = strtolower(str_replace(' ', '-', $title));
$short = substr($text, 0, 100) . '...';
$class = substr(strrchr('App\Models\User', '\\'), 1);
// Correct
$slug = Str::slug($title);
$short = Str::limit($text, 100);
$class = class_basename('App\Models\User');
```
Fluent strings — chain operations for complex transformations:
```php
// Incorrect
$result = strtolower(trim(str_replace('_', '-', $input)));
// Correct
$class = class_basename(User::class);
$result = Str::of($input)->trim()->replace('_', '-')->lower();
```
Key `Str` methods to prefer: `Str::slug()`, `Str::limit()`, `Str::contains()`, `Str::before()`, `Str::after()`, `Str::between()`, `Str::camel()`, `Str::snake()`, `Str::kebab()`, `Str::headline()`, `Str::squish()`, `Str::mask()`, `Str::uuid()`, `Str::ulid()`, `Str::random()`, `Str::is()`.
Use `Arr` for dot notation and common transformations:
Arrays — use `Arr` over raw PHP:
```php
// Incorrect
$name = isset($array['user']['name']) ? $array['user']['name'] : 'default';
// Correct
$name = Arr::get($array, 'user.name', 'default');
$public = Arr::only($attributes, ['name', 'email']);
```
Key `Arr` methods: `Arr::get()`, `Arr::has()`, `Arr::only()`, `Arr::except()`, `Arr::first()`, `Arr::flatten()`, `Arr::pluck()`, `Arr::where()`, `Arr::wrap()`.
Use `Number` for localized display formatting rather than values that will be stored or calculated:
Numbers — use `Number` for display formatting:
```php
Number::format(1000000); // "1,000,000"
Number::currency(1500, 'USD'); // "$1,500.00"
Number::abbreviate(1000000); // "1M"
Number::fileSize(1024 * 1024); // "1 MB"
Number::percentage(75.5); // "75.5%"
Number::format(1000000);
Number::currency(1500, 'USD');
Number::fileSize(1024 * 1024);
```
URIs — use `Uri` for URL manipulation:
Use `Uri` when constructing or transforming a uniform resource identifier (URI) benefits from a structured API:
```php
$uri = Uri::of('https://example.com/search')
->withQuery(['q' => 'laravel', 'page' => 1]);
```
Use `$request->string('name')` to get a fluent `Stringable` directly from request input for immediate chaining.
Check the documentation for the Laravel version supported by the project before using newer utility classes or methods.
Use `search-docs` for the full list of available methods — these helpers are extensive.
## Keep Presentation Code Maintainable
## No Inline JS/CSS in Blade
Prefer the project's asset pipeline, components, and existing conventions for substantial JavaScript and Cascading Style Sheets (CSS). Small page-specific scripts or styles can be reasonable in Blade layouts or stacks; avoid mixing large behavior and style blocks into templates.
Do not put JS or CSS in Blade templates. Do not put HTML in PHP classes.
Pass server data with an encoding mechanism appropriate to its context. For example, Blade's `Js::from()` safely formats data for JavaScript:
Incorrect:
```blade
let article = `{{ json_encode($article) }}`;
<script>
const article = {{ Js::from($article) }};
</script>
```
Correct:
```blade
<button class="js-fav-article" data-article='@json($article)'>{{ $article->name }}</button>
```
Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.
Pass data to JS via data attributes or use a dedicated PHP-to-JS package.
## Write Comments That Explain Why
## No Unnecessary Comments
Prefer clear names and small units of code over comments that merely restate an operation. Add concise comments for non-obvious constraints, tradeoffs, workarounds, regular expressions, or external behavior that the code cannot express by itself. Keep comments accurate when behavior changes.
Code should be readable on its own. Use descriptive method and variable names instead of comments. The only exception is config files, where descriptive comments are expected.
Unhelpful:
Incorrect:
```php
// Check if there are any joins
if (count((array) $builder->getQuery()->joins) > 0)
// Check whether the query has joins.
if (count((array) $builder->getQuery()->joins) > 0) {
// ...
}
```
Correct:
Clearer:
```php
if ($this->hasJoins())
if ($this->hasJoins()) {
// ...
}
```
@@ -1,43 +0,0 @@
# Testing Best Practices
## Use `LazilyRefreshDatabase` Over `RefreshDatabase`
`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date.
## Use Model Assertions Over Raw Database Assertions
Incorrect: `$this->assertDatabaseHas('users', ['id' => $user->id]);`
Correct: `$this->assertModelExists($user);`
More expressive, type-safe, and fails with clearer messages.
## Use Factory States and Sequences
Named states make tests self-documenting. Sequences eliminate repetitive setup.
Incorrect: `User::factory()->create(['email_verified_at' => null]);`
Correct: `User::factory()->unverified()->create();`
## Use `Exceptions::fake()` to Assert Exception Reporting
Instead of `withoutExceptionHandling()`, use `Exceptions::fake()` to assert the correct exception was reported while the request completes normally.
## Call `Event::fake()` After Factory Setup
Model factories rely on model events (e.g., `creating` to generate UUIDs). Calling `Event::fake()` before factory calls silences those events, producing broken models.
Incorrect: `Event::fake(); $user = User::factory()->create();`
Correct: `$user = User::factory()->create(); Event::fake();`
## Use `recycle()` to Share Relationship Instances Across Factories
Without `recycle()`, nested factories create separate instances of the same conceptual entity.
```php
Ticket::factory()
->recycle(Airline::factory()->create())
->create();
```
@@ -1,75 +1,89 @@
# Validation & Forms Best Practices
# Validation and Forms Best Practices
## Use Form Request Classes
## Extract Validation When It Improves the Boundary
Extract validation from controllers into dedicated Form Request classes.
Use a form request when validation or authorization is substantial, reused, or clearer outside the controller. Inline `$request->validate()` remains appropriate for a small, endpoint-specific rule set.
Incorrect:
```php
public function store(Request $request)
public function store(StorePostRequest $request): RedirectResponse
{
$request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
$post = Post::create($request->validated());
return redirect()->route('posts.show', $post);
}
```
Correct:
```php
public function store(StorePostRequest $request)
{
Post::create($request->validated());
}
```
A form request's `authorize()` method can enforce access to the operation. Validation establishes the shape and values of input; it does not itself authorize the user.
## Array vs. String Notation for Rules
## Prefer Readable Rule Syntax
Array syntax is more readable and composes cleanly with `Rule::` objects. Prefer it in new code, but check existing Form Requests first and match whatever notation the project already uses.
Array syntax composes cleanly with rule objects and avoids delimiter issues. Prefer it in new code when it improves readability, while following a consistent local style.
```php
// Preferred for new code
'email' => ['required', 'email', Rule::unique('users')],
```
// Follow existing convention if the project uses string notation
String syntax remains valid for simple rules:
```php
'email' => 'required|email|unique:users',
```
## Always Use `validated()`
## Use Only Intended Validated Data
Get only validated data. Never use `$request->all()` for mass operations.
Use `validated()` or `safe()` instead of `$request->all()` when passing request data onward. Then select the fields intended for the operation when the validation rules also cover control fields or nested data.
Unsafe:
Incorrect:
```php
Post::create($request->all());
```
Correct:
Preferred:
```php
Post::create($request->validated());
$post = Post::create($request->safe()->only(['title', 'body']));
```
## Use `Rule::when()` for Conditional Validation
Validated data is not automatically safe for mass assignment. Keep model `$fillable` or `$guarded` rules aligned with the operation, and never add a sensitive attribute to validation merely to make mass assignment convenient.
## Express Conditional Rules Clearly
Use conditional rules such as `Rule::when()`, `required_if`, or `exclude_unless` when they make the condition explicit. Choose the simplest form that remains easy to test.
```php
'company_name' => [
Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),
'string',
'max:255',
Rule::when(
$this->input('account_type') === 'business',
['required'],
['nullable'],
),
],
```
## Use the `after()` Method for Custom Validation
## Add Cross-Field Validation After Base Rules
Use `after()` instead of `withValidator()` for custom validation logic that depends on multiple fields.
Use a form request's `after()` method for validation that depends on multiple fields or application state. Avoid expensive queries when prerequisite fields have already failed validation.
```php
public function after(): array
{
return [
function (Validator $validator) {
if ($this->quantity > Product::find($this->product_id)?->stock) {
if ($validator->errors()->hasAny(['product_id', 'quantity'])) {
return;
}
$stock = Product::find($this->integer('product_id'))?->stock;
if ($stock !== null && $this->integer('quantity') > $stock) {
$validator->errors()->add('quantity', 'Not enough stock.');
}
},
];
}
```
Validation against mutable state does not prevent a race between validation and persistence. Enforce inventory, uniqueness, and similar invariants with database constraints, atomic updates, or a database transaction as appropriate.
+1 -12
View File
@@ -17,35 +17,24 @@ Use `search-docs` for detailed Livewire 4 patterns and documentation.
### Creating Components
```bash
# Single-file component (SFC - default in v4)
# Creates: resources/views/components/⚡create-post.blade.php
php artisan make:livewire create-post
# Page component (SFC - Full Page in v4)
# Creates: resources/views/pages/⚡create-post.blade.php
php artisan make:livewire pages::create-post
# Multi-file component (MFC)
# Creates: resources/views/components/⚡create-post/create-post.php
# resources/views/components/⚡create-post/create-post.blade.php
php artisan make:livewire create-post --mfc
# Class-based component (v3 style)
# Creates: app/Livewire/CreatePost.php AND resources/views/livewire/create-post.blade.php
php artisan make:livewire create-post --class
# With namespace
php artisan make:livewire Posts/CreatePost
```
@@ -136,7 +125,7 @@ These things changed in Livewire 4, but may not have been updated in this applic
- Always use `wire:key` in loops
- Use `wire:loading` for loading states
- Use `wire:model.live` for instant updates (default is debounced)
- Use `wire:model.live` for live updates; `wire:model` is deferred by default
- Validate and authorize in actions (treat like HTTP requests)
## Configuration
File diff suppressed because it is too large Load Diff
+293
View File
@@ -0,0 +1,293 @@
---
name: material-3-design
description: Material 3 Expressive's design system as Livewire Material implements it — colour roles and surface containers, elevation, shape, type, motion, states and targets, window size classes, spacing, icons, accessibility — each M3 name beside the class, prop or token that draws it and Google's source page, for deciding how a screen should look and behave before writing it.
---
# Material 3 design
## When to use this skill
Use this skill when deciding how a screen, panel or control should look or behave — which colour, container, corner, type style, motion, breakpoint or spacing — in an application that requires `nonameweb/livewire-material`, and when reviewing a view against Material 3. The props and slots of each component are in the `livewire-material-development` skill; this one is the design language they implement. The rules an agent must always follow are in the `material-3` guideline; the tables here are what those rules compress.
Every table pairs the M3 name with what the library gives for it. The library is plain CSS with no utility classes, so that is one of three things: a component or layout component prop (`color="error"`, `<x-surface level="surface-container">`, `gap="space200"`), one of the fixed text and interaction classes (`md-type-*`, `md-ink-*`, `md-state-layer`, `md-focus-ring`, `md-touch-target`, `md-link`), or a token the application's own CSS reads with `var()`. The tokens are CSS custom properties (`--md-sys-color-*`, `--md-sys-typescale-*`, `--md-sys-shape-*`, `--md-sys-elevation-*`, `--md-sys-motion-*`, `--md-sys-state-*`, `--md-sys-measurement-*`, `--md-ref-typeface-*`), so a stylesheet names a token and never a value.
## Colour
A colour scheme is generated from one seed by Google's colour science (`php artisan material:scheme`); every role below is a slot in that scheme, light and dark, at three contrast levels. A view names a role and nothing else — never a hex, a palette tone or an opacity — because only a role follows the theme, the contrast level and a colour profile.
### Roles
| Role | Purpose | Its `on-` pair | In this library |
| --- | --- | --- | --- |
| primary | High-emphasis fills, text and icons: the key action on a screen | on-primary | `var(--md-sys-color-primary)`, `md-ink-primary`, `<x-button variant="filled">` |
| primary-container | A standout fill for key components (FAB, an emphasised panel) | on-primary-container | `var(--md-sys-color-primary-container)` |
| primary-dim | A darker primary for a pressed or contrasting fill (2025 spec) | on-primary | `var(--md-sys-color-primary-dim)` |
| secondary | Less prominent fills, text and icons | on-secondary | `var(--md-sys-color-secondary)` |
| secondary-container | The recessive fill: tonal buttons, selected navigation, selected chips | on-secondary-container | `var(--md-sys-color-secondary-container)`, `<x-button variant="tonal">` |
| tertiary | A complementary accent, used sparingly for contrast | on-tertiary | `var(--md-sys-color-tertiary)`, `color="tertiary"` |
| tertiary-container | The complementary fill | on-tertiary-container | `var(--md-sys-color-tertiary-container)` |
| error | Urgency and errors; static, does not follow dynamic colour | on-error | `md-ink-error`, `var(--md-sys-color-error)`, `color="error"` |
| error-container | An error panel | on-error-container | `var(--md-sys-color-error-container)`, `<x-alert color="error">` |
| success, warning, info | This library's custom state colours, built like error on the 2025 spec, with `-container` and `on-` pairs | on-success … | `md-ink-success`, `var(--md-sys-color-warning-container)`, `color="info"` |
| surface | The page background | on-surface | the page itself (the foundation paints it), `<x-surface level="surface">` |
| on-surface-variant | Lower-emphasis text and icons on any surface | — | `md-ink-variant` |
| outline | A boundary that must be read: a text field, a target's edge (3:1 against surface) | — | `md-ink-quiet`, `var(--md-sys-color-outline)` |
| outline-variant | Decorative lines: dividers, card edges | — | `<x-divider>`, `<x-surface outlined>`, `var(--md-sys-color-outline-variant)` |
| inverse-surface | A surface that contrasts with its surroundings (the snackbar) | inverse-on-surface | `var(--md-sys-color-inverse-surface)` with `md-ink-inverse` |
| inverse-primary | An action on an inverse surface (the snackbar's action) | — | `var(--md-sys-color-inverse-primary)` |
| scrim | Behind a modal, at 32% | — | `color-mix(in srgb, var(--md-sys-color-scrim) 32%, transparent)` |
| shadow | The shadow colour, inside every `--md-sys-elevation-*` | — | — |
| surface-dim, surface-bright | Add-on surfaces that keep their relative brightness in both themes | on-surface | `<x-surface level="surface-dim">`, `<x-surface level="surface-bright">` |
| primary-fixed, primary-fixed-dim, on-primary-fixed, on-primary-fixed-variant (and secondary, tertiary) | Add-on roles with the same tone in light and dark; for a colour that must not change with the theme; never where contrast matters | — | `var(--md-sys-color-primary-fixed)` with `var(--md-sys-color-on-primary-fixed)` |
Pairing: a role's `on-` pair is the only combination whose contrast is guaranteed at every contrast level. A `primary` fill under `on-primary` text and a `secondary-container` fill under `on-secondary-container` are right; `primary-container` under `on-surface`, or `secondary-container` under `primary`, are not, and break as the contrast level rises. A component sets its own pair; the application's CSS writes both halves (`background-color: var(--md-sys-color-primary); color: var(--md-sys-color-on-primary)`). Google: "Pair and layer color roles only as intended … Don't mix roles improperly."
### Surface containers
A hierarchy of emphasis, not of height: the tone separates panels before any shadow does, and a region keeps its role at every breakpoint (body always `surface`, navigation always `surface-container`).
| Role | Use | In this library |
| --- | --- | --- |
| surface | The page | the page itself, `<x-surface level="surface">` |
| surface-container-lowest | The most recessed panel; an elevated card's body in dark themes | `<x-surface level="surface-container-lowest">` |
| surface-container-low | An elevated card, a modal bottom or side sheet, the full-screen search view | `<x-surface level="surface-container-low">` |
| surface-container | Navigation bar and rail, docked and floating toolbars, menus, the segmented list | `<x-surface>` (the default level) |
| surface-container-high | Dialogs, the search bar, date and time pickers, a rich tooltip | `<x-surface level="surface-container-high">` |
| surface-container-highest | A filled card, a filled text field, a filled chip's selected state | `<x-surface level="surface-container-highest">` |
In the application's CSS each is `var(--md-sys-color-surface-container-low)` and so on; the ink on every one of them is `on-surface`.
### Emphasis and lines
- Default ink is `on-surface` (`md-ink`); lower emphasis is `on-surface-variant` (`md-ink-variant`); decoration is `outline` (`md-ink-quiet`). Emphasis is never an opacity: M3 reserves 38% (`--md-sys-state-disabled-content-opacity`) for disabled content and 12% (`--md-sys-state-disabled-container-opacity`) for a disabled container.
- `outline` for a boundary that has to be perceived (a text field's edge, a target's edge — 3:1 against the surface); `outline-variant` for dividers and the edge of a card or any component holding several elements. Google: "Don't use the outline color for dividers … use outline variant instead." `outline-variant` may edge a chip or a button only because the content inside already carries the contrast.
- A hyperlink in running text is `primary` (or `tertiary` for a quieter link) **and** underlined: `md-link` with `md-ink-primary`.
### Contrast
| Level | Target | How |
| --- | --- | --- |
| Standard | Hierarchy from high- and low-contrast elements together; text 4.5:1, large text and icons 3:1, grouped non-text controls 3:1 | the default scheme |
| Medium | 3:1 minimum everywhere, without halation | `<html data-contrast="medium">` |
| High | 7:1 | `<html data-contrast="high">`, or the visitor's OS setting (`theme.contrast.default` = `system`) |
Every role changes with the level automatically; a component built from roles needs nothing else. Disabled states are exempt from contrast. A colour outside the roles (a hex, white, black) does not change and is the one thing that breaks a contrast level.
Sources: https://m3.material.io/styles/color/roles · https://m3.material.io/styles/color/system/how-the-system-works · https://m3.material.io/styles/color/advanced/apply-colors · https://m3.material.io/foundations/designing/color-contrast
## Surfaces and elevation
M3 separates surfaces by tone first; a shadow says that something floats over the content or is being interacted with. "When it comes to applying shadows, less is more."
| Level | Shadow | Rests here | In this library |
| --- | --- | --- | --- |
| 0 | none | The page, cards (filled, outlined), buttons (filled, tonal, outlined), button groups, icon buttons, lists, chips, tabs, sliders, the rail, a docked side sheet, a carousel, a full-screen dialog, a FAB inside the rail, an app bar at rest | — |
| 1 | 1dp | Elevated cards, elevated buttons and chips, modal bottom and side sheets, a banner | `box-shadow: var(--md-sys-elevation-1)` |
| 2 | 3dp | Menus, the navigation bar, a scrolled app bar, toolbars, rich tooltips | `var(--md-sys-elevation-2)` |
| 3 | 6dp | FAB and extended FAB, the FAB menu's close button, dialogs, date and time pickers, the search bar | `var(--md-sys-elevation-3)` |
| 4 | 8dp | Interaction only: a level-3 element on hover or while dragged | `var(--md-sys-elevation-4)` |
| 5 | 12dp | Interaction only | `var(--md-sys-elevation-5)` |
- Hover lifts an element one level (a FAB 3 → 4, an elevated card 1 → 2); focus and selection may too; a raised element lowers when something higher appears.
- Overlapping panels take different surface-container roles to show separation; the roles are not tied to the levels.
- A scrim (`scrim` at 32%) brings focus to a modal over a large surface; it is never a substitute for a shadow on a small floating element.
- On a dark surface a shadow is nearly invisible, so the tone does the work there.
Sources: https://m3.material.io/styles/elevation/overview · https://m3.material.io/styles/elevation/applying-elevation · https://m3.material.io/styles/elevation/tokens
## Shape
### The corner scale
| Style | Value | In this library |
| --- | --- | --- |
| None | 0 | `var(--md-sys-shape-corner-none)`, `corner="none"` |
| Extra small | 4px | `var(--md-sys-shape-corner-xs)`, `corner="xs"` |
| Small | 8px | `var(--md-sys-shape-corner-sm)`, `corner="sm"` |
| Medium | 12px | `var(--md-sys-shape-corner-md)`, `corner="md"` |
| Large | 16px | `var(--md-sys-shape-corner-lg)`, `corner="lg"` |
| Large increased | 20px | `var(--md-sys-shape-corner-lg-increased)`, `corner="lg-increased"` |
| Extra large | 28px | `var(--md-sys-shape-corner-xl)`, `corner="xl"` |
| Extra large increased | 32px | `var(--md-sys-shape-corner-xl-increased)`, `corner="xl-increased"` |
| Extra extra large | 48px | `var(--md-sys-shape-corner-xxl)`, `corner="xxl"` |
| Full | a stadium or circle | `var(--md-sys-shape-corner-full)`, `corner="full"` |
`corner` is `<x-surface>`'s prop. In the application's CSS a corner is `border-radius` on a token, and one side at a time a logical longhand (`border-start-start-radius` and `border-start-end-radius` for a bottom sheet's top); a length of your own is off the scale.
### Corner by component
| Component | Corner | Note |
| --- | --- | --- |
| Buttons, icon buttons, split button (outer), FAB menu items | full | a press morphs to `md` (xs/sm sizes), `lg` (md), `xl` (lg/xl); a selected toggle swaps round ↔ square |
| Connected button group | full outside, `sm` between segments | segments press to `xs` |
| FAB | `lg` 16 (baseline 56px), `lg-increased` 20 (medium 80px), `xl` 28 (large 96px) | extended FAB `lg` |
| Chips | `sm` 8 | an avatar in a chip `md` 12 |
| Cards | `md` 12 | no change on hover |
| Text fields | `xs` 4 (outlined: all corners; filled: top corners only) | |
| Menus, snackbar, plain tooltip | `xs` 4 | the Expressive vertical menu rounds the focused item |
| Rich tooltip | `md` 12 | |
| Dialogs | `xl` 28 | full-screen dialog `none` |
| Bottom sheet | `xl` 28 on top | |
| Side sheet | `lg` 16 on the inner side | |
| Search bar | full | search view `xl` 28 when docked, `none` full-screen |
| Date and time pickers | `xl` 28 | date cells full |
| Carousel items | `xl` 28 | |
| Navigation indicator, badges, switch, slider handle, checkbox state layer | full | checkbox box 2px, tab indicator 3px on top |
| Navigation bar, app bar, docked toolbar, tabs | none | floating toolbar full |
| Segmented list rows | `xs` inner, `lg` outer; a selected row `lg` | |
### Rules
- Optical roundness: a shape nested in a rounded container takes inner radius = outer radius − padding (48 − 14 = 34), never the container's own radius.
- Large and full corners do not belong on information-dense containers (cards, tables, text fields).
- A press squares a round shape and rounds a square one (the components carry the morph on the fast spatial spring); nothing morphs on hover.
- The 35 Expressive shapes (`<x-shape name="cookie-9">`, also the loading indicator and the standard button group's press shape) are decoration for emphasis and delight — never a carrier of meaning, never behind text-heavy content, and used sparingly.
Sources: https://m3.material.io/styles/shape/corner-radius-scale · https://m3.material.io/styles/shape/shape-morph · https://m3.material.io/styles/shape/overview-principles
## Type
The typeface is Google Sans Flex for brand and plain styles (`--md-ref-typeface-brand`, `--md-ref-typeface-plain`); an application may replace it after importing the stylesheet. Each style is one class that sets size, line height, weight, family and tracking together — or, in the application's CSS, `font: var(--md-sys-typescale-body-md)` with `letter-spacing: var(--md-sys-typescale-body-md-tracking)`. A size, weight, line height or letter spacing of your own is off the scale.
| Role | Style | Size / line | Weight | In this library | Use for |
| --- | --- | --- | --- | --- | --- |
| Display | large / medium / small | 57/64 · 45/52 · 36/44 | 400 | `md-type-display-lg` … | hero figures, one short marketing line; never running text |
| Headline | large / medium / small | 32/40 · 28/36 · 24/32 | 400 | `md-type-headline-lg` … | page titles, section titles, a dialog's headline (`headline-sm`) |
| Title | large / medium / small | 22/28 · 16/24 · 14/20 | 400 / 500 / 500 | `md-type-title-lg` … | app bar title (`lg`), card and list-section titles (`md`), dense headers (`sm`) |
| Body | large / medium / small | 16/24 · 14/20 · 12/16 | 400 | `md-type-body-lg` … | paragraphs (`lg` for reading, `md` in components), supporting text (`sm`) |
| Label | large / medium / small | 14/20 · 12/16 · 11/16 | 500 | `md-type-label-lg` … | buttons and tabs (`lg`), chips and navigation (`md`), captions and badges (`sm`) |
- `md-type-emphasized-*` (`--md-sys-typescale-emphasized-*`) is the same size and line height one weight step heavier (400 → 500, 500 → 700), fully rounded in Google Sans Flex, with its own tracking. M3 uses it deliberately, never by default: a selected list or menu item, a button's label on a primary action, an extended FAB, a badge, a headline given editorial weight.
- Tracking follows Compose's `TypeScaleTokens`: display-large −0.2, title-medium 0.2, title-small 0.1, body-large 0.5, body-medium 0.2, body-small 0.4, label-large 0.1, label-medium and small 0.5 (sp; rem = sp/16); the emphasized set tightens a few (display-large 0, title-medium 0.15, body-large 0.15, body-medium 0.25).
- Line length 40–60 characters (`max-inline-size: 60ch` in the application's CSS). Figures that change take `md-tabular`.
- Text must scale to 200%: containers grow, side-by-side controls stack, padding stays; components without text (progress, checkboxes) do not scale. Truncate to an ellipsis (`md-truncate`) only when the full text is one tooltip or link away.
- When customising, change the typeface or tracking, never the sizes: component layout depends on them.
Sources: https://m3.material.io/styles/typography/type-scale-tokens · https://m3.material.io/styles/typography/applying-type · https://m3.material.io/styles/typography/fonts · https://m3.material.io/foundations/writing/text-resizing · https://m3.material.io/foundations/writing/text-truncation
## Motion
M3 Expressive moves on physics: every transition is a spring, and the library samples each spring into a CSS `linear()` easing paired with a duration. Use the pair together, or the curve is stretched over the wrong time.
| Spring | Damping / stiffness | Duration | In this library | For |
| --- | --- | --- | --- | --- |
| Spatial fast | 0.6 / 800 | 350ms | `var(--md-sys-motion-spatial-fast-duration) var(--md-sys-motion-spatial-fast)` | small elements: a button's press morph, a switch, a chip |
| Spatial default | 0.8 / 380 | 500ms | `var(--md-sys-motion-spatial-default-duration) var(--md-sys-motion-spatial-default)` | most position, size and shape changes |
| Spatial slow | 0.8 / 200 | 650ms | `var(--md-sys-motion-spatial-slow-duration) var(--md-sys-motion-spatial-slow)` | large surfaces: a sheet, a pane, a full-screen transition |
| Effects fast | 1.0 / 3800 | 150ms | `var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast)` | state layers, small fades |
| Effects default | 1.0 / 1600 | 200ms | `var(--md-sys-motion-effects-default-duration) var(--md-sys-motion-effects-default)` | most colour and opacity changes |
| Effects slow | 1.0 / 800 | 300ms | `var(--md-sys-motion-effects-slow-duration) var(--md-sys-motion-effects-slow)` | large fades, a scrim |
A transition names the property, then the pair: `transition: transform var(--md-sys-motion-spatial-default-duration) var(--md-sys-motion-spatial-default), opacity var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast)`.
- Spatial springs are underdamped and overshoot — that bounce is what reads as Expressive — so they carry only position, size and shape. Effects springs are critically damped and carry colour and opacity, which must never overshoot. A transition on `all` mixes the two and is wrong.
- The Standard motion scheme (`<html data-motion="standard">`, config `motion.scheme`) swaps the spatial springs for stiffer ones with almost no bounce (0.9 / 1400, 700, 300; 350, 500, 750ms) for utilitarian products; effects are shared.
- Direction: something entering decelerates (`--md-sys-motion-easing-emphasized-decelerate`, or a spatial spring from off-screen), a permanent exit accelerates (`--md-sys-motion-easing-emphasized-accelerate`), a temporary exit that can be recalled (a drawer, a sheet) takes `--md-sys-motion-easing-emphasized`; exits are shorter than entrances, and larger areas move longer.
- The cubic-bezier set (`--md-sys-motion-easing-standard`, `-emphasized`, `-emphasized-decelerate`, `-emphasized-accelerate`, with `--md-sys-motion-duration-short|medium|long`) is for the few transitions whose duration is fixed from outside: a view transition, an animated scroll.
- Reduced motion zeroes every duration token, so anything animated through them turns instant; a literal `300ms`, or a keyframe animation with its own timing, ignores the visitor's setting and is a bug. Container transforms, parallax and expansions are removed, not slowed.
Sources: https://m3.material.io/styles/motion/overview · https://m3.material.io/styles/motion/overview/specs · https://m3.material.io/styles/motion/easing-and-duration/tokens-specs · https://m3.material.io/styles/motion/transitions/transition-patterns
## States and targets
| State | Layer | Class or hook | Also |
| --- | --- | --- | --- |
| Enabled | none | — | |
| Hover | 8% of the content colour | `md-state-layer` (pointer devices only) | one level of elevation on floating elements |
| Focused | 10% | `md-state-layer md-focus-ring` (keyboard focus: a 3px `secondary` ring, 2px out) | only one focused element at a time |
| Pressed | 10% | `md-state-layer` (`:active`) | the shape morph on buttons |
| Dragged | 16% | `md-state-layer` with `data-md-dragged` | one level of elevation |
| Disabled | content 38%, container 12%, no state layer, not focusable | `color-mix(in srgb, var(--md-sys-color-on-surface) calc(var(--md-sys-state-disabled-content-opacity) * 100%), transparent)`, and the container likewise with `--md-sys-state-disabled-container-opacity` | exempt from contrast; a FAB is hidden rather than disabled |
| Selected | the `secondary-container` pair, a filled icon, the emphasized style | component props (`selected`, `aria-selected`, `aria-pressed`) | combines with hover, focus and press |
- The state layer takes the content's `on-` colour (on `secondary-container` it is `on-secondary-container`), is 40px on a 48px target, and only one shows at a time. `md-state-layer` draws it in `currentColor` as a `::before`, so the element becomes `position: relative`.
- Every state shows two indicators, so a colour change alone is never a state: add a shape, an outline, an icon, a weight or a word (`aria-selected` plus the container, an error colour plus an icon and a message).
- Targets: 48×48px minimum, 8px between targets, on every device; `md-touch-target` extends a smaller drawing to 48px. Density is an opt-in prop (`dense`) that steps padding by 4px and never applies to menus, snackbars, dialogs or settings controls, and never takes a target below 48px.
- Keyboard: Tab and Shift+Tab between components in DOM order, arrows within a component (menu, tabs, grid, radio group), Enter and Space activate, Escape dismisses; a dialog moves focus in on open and back to its opener on close.
Sources: https://m3.material.io/foundations/interaction/states/state-layers · https://m3.material.io/foundations/interaction/states/applying-states · https://m3.material.io/foundations/designing/structure · https://m3.material.io/foundations/layout/grids-spacing/density
## Layout and breakpoints
Layout keys on the width of the window, in M3's five window size classes and only those. A layout component names the class in a prop (`hide-below`, `hide-from`, `stack-below`, `<x-grid>`'s `columns` map); the application's CSS writes the width as a range media query; a script asks `resources/js/breakpoints.js` (`from('expanded')`, `upTo('medium')`) for the same numbers.
| Class | Width | Prop value · CSS | Navigation | Panes | Dialogs and choices | Margins |
| --- | --- | --- | --- | --- | --- | --- |
| Compact | below 600px | the default; `hide-from="medium"` for "only here" · `@media (width < 600px)` | navigation bar; the rail opens as a modal | 1 | full-screen or basic dialog; a bottom sheet for choices | 16px |
| Medium | 600–839px | `medium` · `@media (width >= 600px)` | collapsed rail (96px) | 1, or 2 for low-density content at 50% each | basic dialog; a menu for choices | 24px |
| Expanded | 840–1199px | `expanded` · `@media (width >= 840px)` | rail, collapsed or expanded, collapsible | 2 recommended; a fixed pane 360px | basic dialog; menu | 24px |
| Large | 1200–1599px | `large` · `@media (width >= 1200px)` | rail expanded | 2; a fixed pane 412px | basic dialog; menu | 24px |
| Extra-large | 1600px and up | `extra-large` · `@media (width >= 1600px)` | rail expanded | 2, or 3 with a standard side sheet (at most 400px) | basic dialog; menu | 24px |
- `<x-scaffold>` implements the navigation column; `<x-pane>` is a content region with the margins above; `<x-list-detail>` is the second pane of a list-detail layout from expanded, `<x-supporting-pane>` puts a supporting pane (360px, beside the focus pane) from expanded and below it before that. Moving up a class, ask what to reveal, divide into panes, resize, reposition or swap — never swap a component for one that does not do the same job.
- Scaffold: bars (app bar at the top, navigation bar at the bottom: 3–5 destinations), rails (the navigation rail, toolbars, the FAB, on the leading edge), panes (all content), around a safety region that stays clear of the device's own chrome (`--material-safe-top|bottom|left|right`).
- Canonical layouts: feed (`<x-feed>`, a grid of cards that gains columns as the room grows), list-detail (one pane on compact, two from expanded; a back button only in single-pane mode, a selected row only in two-pane mode), supporting pane (two thirds focus, one third support).
- Bidirectionality: write logical properties (`padding-inline-start`, `margin-inline-end`, `inset-inline-start`, `border-inline-start`, `md-text-start`); `<x-row>` runs in the inline direction and mirrors by itself; leading and trailing icons swap, directional icons (back, send) mirror, the rail moves to the right; charts, media controls, clocks and Hebrew progress bars stay left-to-right.
Sources: https://m3.material.io/foundations/layout/breakpoints/overview · https://m3.material.io/foundations/layout/breakpoints/compact (medium, expanded, large-extra-large) · https://m3.material.io/foundations/layout/scaffold/overview · https://m3.material.io/foundations/layout/canonical-examples/overview · https://m3.material.io/foundations/layout/bidirectionality-rtl
## Spacing
M3's spacing tokens are multiples of an 8px base on a 4px grid. A layout component takes the token's name (`gap="space200"`, `<x-surface padding="space300">`); the application's CSS reads it (`var(--md-sys-measurement-space200)`).
| Token | Value | In this library |
| --- | --- | --- |
| space25 | 2px | `space25` |
| space50 | 4px | `space50` |
| space75 | 6px | `space75` |
| space100 | 8px (the base) | `space100` |
| space125 | 10px | `space125` |
| space200 | 16px | `space200` — a component's padding, compact margins |
| space300 | 24px | `space300` — a dialog's padding, margins from medium |
| space400 | 32px | `space400` |
| space500 | 40px | `space500` |
| space600 | 48px | `space600` — a target |
| space700 | 56px | `space700` |
| space800 | 64px | `space800` |
| space900 | 72px | `space900` |
- Padding and gaps live on the parent (`<x-surface padding="space200">` around `<x-stack gap="space100">`), never as margins on children; a margin is for space beyond a container's padding or between layout regions.
- Spacing does not scale with text: at 200% text size the same padding and gaps stay.
- Name a gap by what it separates when a component has several (icon–label 8px, label–supporting text 4px).
Sources: https://m3.material.io/styles/spacing/overview · https://m3.material.io/styles/spacing/tokens · https://m3.material.io/styles/spacing/applying-spacing
## Icons
`<x-icon name="lock">` draws a Material Symbol Rounded (weight 400, grade 0), outlined or `filled`, at optical size 24 or 20.
| Axis | Values | In this library |
| --- | --- | --- |
| Fill | 0 outlined, 1 filled | `filled` — active, selected or on state (a selected navigation item, a FAB's icon, a checked filter chip) |
| Weight | 100–700; never below 200 at 24px | 400 for every icon; one weight per group |
| Grade | −25 on dark backgrounds, 0 otherwise, positive for emphasis | 0 |
| Optical size | 20 dense, 24 standard, 40–48 with display type | `size="20"` and below pick the 20 cut (small buttons, chips, dense lists); `optical="20"` for an icon sized by the application's own CSS |
- An icon beside text takes the text's size and colour (`size="20"` beside `md-type-label-lg`, 24 beside body) and the same optical weight; its baseline sits about 11.5% of the text size below the text's.
- Icons stay flat and forward-facing, on the pixel grid, inside their 20px live area of the 24px canvas.
- An icon-only control has an accessible name (`aria-label`, or a tooltip that names it); a decorative icon is `aria-hidden`; a complex icon drawn below 20px needs a label beside it.
Sources: https://m3.material.io/styles/icons/overview · https://m3.material.io/styles/icons/designing-icons · https://m3.material.io/styles/icons/applying-icons
## Accessibility
The guideline's own Accessibility line has the rule; beyond it: every repeated landmark —
`search`, `complementary`, `form`, `region`, not just `nav` — is labelled the same way; an
ambiguous button ("Save", "Learn more") needs a name that says what it does, not just what kind
of control it is; DOM order is reading order, a dialog returns focus to its opener, and a group of
related controls is one Tab stop with the arrows moving inside it; an invalid field also carries
`aria-invalid`, and a loading state has a name too.
Sources: https://m3.material.io/foundations/overview/principles · https://m3.material.io/foundations/designing/structure · https://m3.material.io/foundations/designing/flow · https://m3.material.io/foundations/designing/elements · https://m3.material.io/foundations/overview/assistive-technology
## Don'ts
The guideline's Don'ts, Type and Motion bullets name them; where they name no replacement — a vertical
group or chips for radios in a row, `<x-divider>` for the outline case, the `md-type-*`/`md-ink-*`
classes and `--md-sys-*` tokens for the utility-class case, wrap/grow/a tooltip instead of a bare
ellipsis, the paired motion tokens instead of a literal duration — the components and layout
sections above have it.
## Attribution
The rules, tables and wording here are Google's, condensed from the Material Design 3 documentation at https://m3.material.io (Foundations, Styles and Components), which Google publishes under the Creative Commons Attribution 4.0 License except as otherwise noted; the numeric token values are from the Android Open Source Project's Material 3 token files in androidx Compose (Apache License 2.0). Copyright Google LLC; Copyright The Android Open Source Project. The library's `NOTICE` records the same. Dates and page names are those of the site as read on 2026-09-13; the full extracted references, with every source page, are kept in the package repository under `docs/reference/m3/`.
-166
View File
@@ -1,166 +0,0 @@
---
name: pest-testing
description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
license: MIT
metadata:
author: laravel
---
# Pest Testing 4
## Documentation
Use `search-docs` for detailed Pest 4 patterns and documentation.
## Basic Usage
### Creating Tests
All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
The `{name}` argument should include only the path and test name, but should not include the test suite.
- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`
- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`
- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`
- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`
### Test Organization
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
- Browser tests: `tests/Browser/` directory.
- Do NOT remove tests without approval - these are core application code.
### Basic Test Structure
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
<!-- Basic Pest Test Example -->
```php
it('is true', function () {
expect(true)->toBeTrue();
});
```
### Running Tests
- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.
- Run all tests: `php artisan test --compact`.
- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.
## Assertions
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
<!-- Pest Response Assertion -->
```php
it('returns all', function () {
$this->postJson('/api/docs', [])->assertSuccessful();
});
```
| Use | Instead of |
|-----|------------|
| `assertSuccessful()` | `assertStatus(200)` |
| `assertNotFound()` | `assertStatus(404)` |
| `assertForbidden()` | `assertStatus(403)` |
## Mocking
Import mock function before use: `use function Pest\Laravel\mock;`
## Datasets
Use datasets for repetitive tests (validation rules, etc.):
<!-- Pest Dataset Example -->
```php
it('has emails', function (string $email) {
expect($email)->not->toBeEmpty();
})->with([
'james' => 'james@laravel.com',
'taylor' => 'taylor@laravel.com',
]);
```
## Pest 4 Features
| Feature | Purpose |
|---------|---------|
| Browser Testing | Full integration tests in real browsers |
| Smoke Testing | Validate multiple pages quickly |
| Visual Regression | Compare screenshots for visual changes |
| Test Sharding | Parallel CI runs |
| Architecture Testing | Enforce code conventions |
### Browser Test Example
Browser tests run in real browsers for full integration testing:
- Browser tests live in `tests/Browser/`.
- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.
- Use `RefreshDatabase` for clean state per test.
- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.
- Test on multiple browsers (Chrome, Firefox, Safari) if requested.
- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.
- Switch color schemes (light/dark mode) when appropriate.
- Take screenshots or pause tests for debugging.
<!-- Pest Browser Test Example -->
```php
it('may reset the password', function () {
Notification::fake();
$this->actingAs(User::factory()->create());
$page = visit('/sign-in');
$page->assertSee('Sign In')
->assertNoJavaScriptErrors()
->click('Forgot Password?')
->fill('email', 'nuno@laravel.com')
->click('Send Reset Link')
->assertSee('We have emailed your password reset link!');
Notification::assertSent(ResetPassword::class);
});
```
### Smoke Testing
Quickly validate multiple pages have no JavaScript errors:
<!-- Pest Smoke Testing Example -->
```php
$pages = visit(['/', '/about', '/contact']);
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
```
### Visual Regression Testing
Capture and compare screenshots to detect visual changes.
### Test Sharding
Split tests across parallel processes for faster CI runs.
### Architecture Testing
Pest 4 includes architecture testing (from Pest 3):
<!-- Architecture Test Example -->
```php
arch('controllers')
->expect('App\Http\Controllers')
->toExtendNothing()
->toHaveSuffix('Controller');
```
## Common Pitfalls
- Not importing `use function Pest\Laravel\mock;` before using mock
- Using `assertStatus(200)` instead of `assertSuccessful()`
- Forgetting datasets for repetitive validation tests
- Deleting tests without approval
- Forgetting `assertNoJavaScriptErrors()` in browser tests
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`
@@ -1,119 +0,0 @@
---
name: tailwindcss-development
description: "Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS."
license: MIT
metadata:
author: laravel
---
# Tailwind CSS Development
## Documentation
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
## Basic Usage
- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns.
- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue).
- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically.
## Tailwind CSS v4 Specifics
- Always use Tailwind CSS v4 and avoid deprecated utilities.
- `corePlugins` is not supported in Tailwind v4.
### CSS-First Configuration
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
<!-- CSS-First Config -->
```css
@theme {
--color-brand: oklch(0.72 0.11 178);
}
```
### Import Syntax
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
<!-- v4 Import Syntax -->
```diff
- @tailwind base;
- @tailwind components;
- @tailwind utilities;
+ @import "tailwindcss";
```
### Replaced Utilities
Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.
| Deprecated | Replacement |
|------------|-------------|
| bg-opacity-* | bg-black/* |
| text-opacity-* | text-black/* |
| border-opacity-* | border-black/* |
| divide-opacity-* | divide-black/* |
| ring-opacity-* | ring-black/* |
| placeholder-opacity-* | placeholder-black/* |
| flex-shrink-* | shrink-* |
| flex-grow-* | grow-* |
| overflow-ellipsis | text-ellipsis |
| decoration-slice | box-decoration-slice |
| decoration-clone | box-decoration-clone |
## Spacing
Use `gap` utilities instead of margins for spacing between siblings:
<!-- Gap Utilities -->
```html
<div class="flex gap-8">
<div>Item 1</div>
<div>Item 2</div>
</div>
```
## Dark Mode
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
<!-- Dark Mode -->
```html
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
Content adapts to color scheme
</div>
```
## Common Patterns
### Flexbox Layout
<!-- Flexbox Layout -->
```html
<div class="flex items-center justify-between gap-4">
<div>Left content</div>
<div>Right content</div>
</div>
```
### Grid Layout
<!-- Grid Layout -->
```html
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div>Card 1</div>
<div>Card 2</div>
<div>Card 3</div>
</div>
```
## Common Pitfalls
- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)
- Using `@tailwind` directives instead of `@import "tailwindcss"`
- Trying to use `tailwind.config.js` instead of CSS `@theme` directive
- Using margins for spacing between siblings instead of gap utilities
- Forgetting to add dark mode variants when the project uses dark mode
@@ -0,0 +1,58 @@
---
name: testing-best-practices
description: "Laravel test design and review. Use when selecting coverage, naming or structuring tests, choosing assertions or test data, isolating dependencies, testing HTTP or security boundaries, improving suite performance, or reviewing test value. Use framework guidance or search-docs for Pest and PHPUnit syntax."
license: MIT
metadata:
author: laravel
---
# Testing Best Practices
This skill provides rules for designing Laravel tests. Each rule file explains what to do and why. Use `search-docs` for Laravel and Pest API syntax.
This project uses Pest. Follow the corresponding guidance in each rule.
## Consistency First
Read nearby tests before you choose syntax and organization.
A pattern repeated throughout the project is a convention, and project conventions take precedence over this skill. Follow them and give new tests the same structure.
These rules govern the tests you write now. An existing test that follows a project convention is not defective merely because it conflicts with this skill. Do not delete or rewrite it. If the convention has drawbacks, explain them and let the user decide.
## What to Test
Read this section before you write a test.
- Test observable behavior and application contracts. A test must pass after an implementation change if the behavior stays the same.
- Cover every changed decision and each applicable high-value failure mode. A decision is a branch, a validation, a calculation, or an authorization.
- Exercise declarations through behavior instead of repeating their text.
- Leave framework behavior to framework tests. Testing project configuration is not testing the framework. A constrained relationship, cast, scope, or validation rule belongs to this project.
- Keep every test that can detect a distinct defect. When two tests detect the same defect, trim the higher-layer test to one case and report the duplication. Do not delete an existing test.
- Write a feature test first. Write a unit test only for logic that does not use the framework.
- Write a browser test only for behavior in JavaScript that a feature test cannot reach. Put a browser test in `tests/Browser`, and call `assertNoJavaScriptErrors()` in it.
- Judge an architecture test by the convention it protects, not by the rules above. An `arch()` test declares a rule for an entire directory, such as the parent class of every model, the classes that may use an enum, or the methods every factory declares. It intentionally checks declarations and fails when a new file breaks the convention.
- Use the test tools that the project installs. Add a new test dependency, plugin, or browser only after the user asks for it.
## How to Apply
1. Read the code under test. Read the tests in the same directory. Identify every decision in the code.
2. Select every applicable branch in the rule index. Read every selected rule file.
3. Report each defect in the code before you write a test. Examples are a method with no body, a policy that no action calls, and a write action with no validation. Test the actual behavior. Report the defect to the user.
4. Write the tests. Run the smallest set of tests that covers the change. The tests must pass.
5. Check every applicable item in `rules/review.md` and every selected rule file. Resolve every mismatch before completion.
## Rule Index
Most changes need more than one rule file.
| Subject | Rule File |
| --- | --- |
| Test framework features that may already do the work | [`rules/finding-features.md`](rules/finding-features.md) |
| File layout, test names, and groups | [`rules/naming.md`](rules/naming.md) |
| Arrange-act-assert and choosing the correct assertion | [`rules/assertions.md`](rules/assertions.md) |
| Endpoint coverage, authentication, authorization, tenant isolation, validation, and browser tests | [`rules/endpoint-tests.md`](rules/endpoint-tests.md) |
| Factories, test data ownership, and repeated input values | [`rules/test-data.md`](rules/test-data.md) |
| Fakes, mocks, outbound HTTP, time, randomness, and databases | [`rules/isolation.md`](rules/isolation.md) |
| Escaping, injection, cross-tenant access, and privilege checks | [`rules/security.md`](rules/security.md) |
| Environment and CI settings for a slow suite | [`rules/performance.md`](rules/performance.md) |
| Reviewing a test or suite | [`rules/review.md`](rules/review.md) |
@@ -0,0 +1,64 @@
# Assertions
## Arrange, Act, Assert
Write each test in three parts: setup, one action, and assertions. Put one blank line between them so readers can identify each part without comments.
Keep each test self-contained. Do not use values created by another test.
## How to Find the Correct Assertion
First identify the subject of the check, then find an assertion designed for it. A subject-specific assertion identifies the incorrect value when the test fails.
1. Search Laravel's assertions for framework subjects such as responses, the database, sessions, models, queues, events, mail, and notifications.
2. Fetch `https://pestphp.com/docs/expectations.md` for the expectations of Pest for a plain value, a type, a format, or a shape.
3. Build the check by hand only if no assertion exists for the subject.
4. Confirm the name in the documentation before you use it. Do not write an assertion that you did not confirm.
Use the assertion in this table for each subject.
| Subject | Assertion to use |
| --- | --- |
| A return value, the state of an object, or a transformation of a value | an `expect()` chain |
| An HTTP status, JSON, a session, or Inertia | a Laravel response assertion |
| The state in the database | a Laravel database assertion |
| The existence of a model | `assertModelExists($model)` rather than `assertDatabaseHas('users', ['id' => $user->id])` |
Use a PHPUnit assertion only if no Pest expectation and no Laravel assertion exists for the subject.
Assert each fact once. Do not assert a 200 status before `assertSee`, because `assertSee` already shows that the page rendered.
## Named Response Assertions
Use a named response assertion, such as `assertNotFound()`, rather than `assertStatus(404)`. A failure then identifies the broken contract. Laravel provides named assertions for commonly tested status codes.
Keep one `expect()` chain on one subject. Start a new chain when the subject changes, or when the chain is difficult to read.
## Format Expectations
Use Pest's format expectations rather than regular expressions because they provide clearer failure messages. Pest covers email addresses, URLs, UUIDs, IP addresses, and other common formats, and each expectation supports `not` for the negative case.
## Assert a Known Value
Write the expected value in the test, or calculate the expected value by a different method. Do not calculate the expected value with the logic of the implementation, because the test then passes when that logic is wrong.
```php
// The test calculates the value with the logic of the implementation...
$expected = now()->subHours(24)->floorSeconds(30)->toJson();
expect($from)->toBe($expected);
// The test sets a fixed input and asserts a known value...
travelTo('2025-01-01 00:00:00');
expect($from)->toBe('2024-12-31T00:00:00.000000Z');
```
## Assert the Complete Result
A status code is not the complete result of a write operation. Assert each of the following if the operation changes it:
- The response or the return value.
- The state in the database.
- The jobs and the events that the operation dispatches.
- The notifications and the mail that the operation sends.
On the failure path, assert that the operation makes none of these changes. A test that asserts only `assertOk()` passes even when the application saves no record.
@@ -0,0 +1,73 @@
# Endpoint Tests
## How to Write the Test
Fetch `https://laravel.com/framework/docs/http-tests` for the request helpers, the authentication helpers, and the response assertions. Confirm the name before you use it, and do not guess an assertion.
Choose an assertion based on the subject of the check: the status, a header, a redirect, the JSON body, the session, a validation error, or the view. Laravel provides a named assertion for each subject that identifies the incorrect value.
## Endpoint Coverage
Write a test for each applicable case:
- The request has missing or invalid authentication.
- The request comes from a different tenant, team, or organization.
- The user has an insufficient role or permission.
- The request does not satisfy a route or scope constraint.
- The request fails the validation.
- The request is valid. Assert both the response and the persisted state.
Assert the application's actual behavior rather than a generic status code. An API returns `401` for a missing or invalid token, while a browser endpoint redirects to the sign-in route.
## Tenant Isolation
Assert the status code returned for a cross-tenant request. Use `404` rather than `403` when one tenant must not learn that another tenant's record exists, because `403` confirms its existence.
## Test Authorization at the Policy Level
An HTTP test shows that the endpoint performs authorization. It cannot identify which mechanism refused the request because middleware, a policy, and a call to `abort()` can all return `403`.
- Assert the complete matrix of the permissions against the policy or the gate. A failure then names the rule that is not correct.
- Write one HTTP test for one refused role, which shows that the endpoint calls the authorization.
- Use the helper of the project that asserts the ability and the arguments of the gate, if such a helper exists.
## Browser Tests
Write a browser test only for JavaScript behavior that an HTTP test cannot reach, such as modal interaction, drag-and-drop, live search, or client-side validation. Browser tests are slower than HTTP tests and can fail for reasons unrelated to the code under test.
- Assert the state that the user can see, and assert the state in the database that the interaction saves.
- Wait until the test reaches the required state. Do not wait for a fixed number of seconds, which can fail on a slower machine.
- Call `assertNoJavaScriptErrors()` in each browser test. An error in the console is a defect.
### Where a Browser Test Lives and How to Run It
The plugin runs browser tests as normal Pest tests, so they need no separate suite. Put them in `tests/Browser` to separate them from faster tests and run the directory with one command.
- Run a browser test with `vendor/bin/pest tests/Browser`, and add `--parallel` for the complete suite.
- Run `vendor/bin/pest --debug` to open the window of the browser and to pause at a failure. Use `--headed` to watch a run that passes.
- Add `--browser firefox` or `--browser safari` to run the test in a different browser. The default browser is Chrome.
- The run needs Playwright and a browser on the machine. Follow the plugin documentation for local and CI installation commands.
- Fetch `https://pestphp.com/docs/browser-testing` for the interactions, the assertions, and the devices that the plugin gives.
### Browser Test Pitfalls
- The plugin waits five seconds for an element. Raise the value with `pest()->browser()->timeout(10000)` in `Pest.php` for a page that is slower, and do not add a wait for a number of seconds to the test.
- Apply `RefreshDatabase` to the browser tests in `Pest.php`. A browser test hits the application through a real request, and the records that it leaves break the next test.
- Add `tests/Browser/Screenshots` to `.gitignore`. A failure writes a screenshot, and the file is not part of the repository.
- Give `withKeyDown()` a key code, such as `KeyA`. A letter such as `'a'` gives the lowercase character, whatever modifier the test holds.
- Interact inside the callback of `withinFrame()`. An interaction outside the callback does not reach the frame.
## Testing Validation
- Write one test for each validation rule when each failure represents a separate contract.
- Write one test with an empty payload to assert several required fields together.
- Assert the text of the message that the user gets. A message that is present but wrong is a defect.
- Use a dataset for input values that need the same setup and the same assertions.
Send an input value that is not valid through the application, and assert the error. Do not assert that an array of rules contains a string, because that assertion tests the declaration and not the behavior. Use such an assertion only for a rule that no request can reach, and write the reason in the test.
### Which Layer Owns Which Case
The rule-class test owns the matrix of values that pass and fail. The endpoint test proves that the endpoint applies the rule and that the user receives the message.
When both tests contain the matrix, move it to the rule-class test and retain one case in the endpoint test. Never remove the last case, because the rule-class test still passes if the request omits the rule. The same division applies to policies, scopes, and other classes called by a request.
@@ -0,0 +1,37 @@
# How to Find Test Framework Features
Pest adds features faster than this skill can list them. Find an existing feature before implementing the behavior by hand.
- Give `search-docs` the capability you need rather than the name of a function you remember. It returns features available in the installed version.
- Fetch `https://pestphp.com/llms.txt` for the complete feature list and additions in each release.
- If a search returns no results, tell the user that the installed version does not provide the feature. Do not write an API that you have not confirmed.
Search for a feature in this table before you write the code by hand.
| Work that you need | Term to search for |
| --- | --- |
| Run one test with many input values | datasets, bound datasets |
| Assert over many values or over a collection | higher-order expectations |
| Remove the same setup from each test in a file | hooks, higher-order tests |
| Apply a convention to the complete codebase | architecture testing |
| Measure if the suite finds a defect | mutation testing |
| Find code with no types | type coverage |
| Reduce the time of a slow suite | parallel, profiling |
| Split the suite across CI jobs | sharding, `--update-shards` |
| Run only the tests that a change affects | Test Impact Analysis, `--tia` |
| Assert that a value has a known format | validation expectations |
| Run one test while you debug | filtering, `--bail`, `--dirty` |
## Built-in Laravel Assertion Methods
Laravel provides assertions for each part of the framework. Fetch `https://laravel.com/framework/docs/testing` for the complete list, and search for an assertion before building a check by hand. Examples include `assertDatabaseHas()`, `assertModelExists()`, `assertSoftDeleted()`, response assertions such as `assertRedirectToRoute()` and `assertJsonPath()`, and fake assertions such as `Queue::assertPushed()` and `Notification::assertSentTo()`.
A hand-built check fails with `false is not true`, which identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure indicates what to fix.
```php
// The failure says that false is not true. Instead of this...
expect(User::where('email', 'taylor@laravel.com')->exists())->toBeTrue();
// Use this... the failure names the table and the attributes that it did not find...
$this->assertDatabaseHas('users', ['email' => 'taylor@laravel.com']);
```
@@ -0,0 +1,52 @@
# Fakes, Mocks, and Determinism
Tests that depend on actual time, randomness, sleeping, or network calls can fail for reasons unrelated to the code under test. Control all four.
## How to Isolate a Dependency
Fetch `https://laravel.com/framework/docs/mocking` for Laravel's fakes, facade doubles, and fake assertions. Confirm each name before using it.
Identify the dependency, then choose the first applicable option. A framework fake preserves the real code path, while a mock replaces the dependency.
1. Always use framework fakes for facades such as events, queues, mail, notifications, storage, the HTTP client, time, and sleep.
2. Use a developer-defined fake implementation of a service if the application provides one.
3. Use a mock for a container-resolved contract only when the real implementation leaves the process or is nondeterministic.
4. Use the real implementation for everything else, including the database.
## Framework Fakes
- Create each fake inside the test that needs it. Do not create fakes in a file-level `beforeEach()`.
- Pass class names to `Event::fake()` and `Queue::fake()` when you know which classes the code dispatches. A fake without class names can hide an unexpected dispatch.
- Use a fake without class names only when the test asserts the complete result, including a call to `assertNothingPushed()`.
- Write one assertion for each fake. The assertion states that the code dispatches the item, or that the code does not dispatch the item.
- Assert the data of a job or of an event if that data is part of the behavior.
- Use `Exceptions::fake()` to assert that the application reports the correct exception. Do not use `withoutExceptionHandling()`, because it changes the response under test.
Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID, and a fake without class names suppresses those events and can produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.
## Mocking
Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. Use `Mockery::on()` or `withArgs()` if an equality check cannot state the expected argument, such as a check of one field of a value object.
Import the mock function before you use it: `use function Pest\Laravel\mock;`.
## Outbound HTTP Testing
Call `Http::preventStrayRequests()`. Any request without a matching fake then fails without reaching the network.
Fake the exact endpoint used by each test. Do not call `Http::fake()` without an endpoint because it accepts unexpected requests and can hide defects.
## Time and Randomness
- Freeze the time or move the time in each test that depends on a date, a period, or a timestamp.
- Use the framework helpers `freezeTime()`, `travelTo()`, `travel()`, and `travelBack()`. Do not call `Carbon::setTestNow()`.
- Use `Str::createRandomStringsUsing()` to fix a generated string, if the test asserts an identifier or a slug.
- Use `Sleep::fake()` instead of a real sleep, and assert the sleeps that the code requests.
- Restore the time and the randomness after each test, if the suite does not restore them for every test.
## Database
- Run real queries against the real records in the test database. Do not mock the query builder, because the test then asserts the mock.
- Assert the exact keys of `toArray()` if the shape of the serialized model is a contract. The test then fails when the model exposes a new attribute.
- Test application behavior caused by the schema, such as deleting dependent records through a cascade. Do not test the database engine's cascade implementation.
- Use `LazilyRefreshDatabase` instead of `RefreshDatabase`. A test that does not use the database then does not run the migrations.
@@ -0,0 +1,45 @@
# Naming and Structure
## File Layout
- Name each test file `{ClassName}Test.php`.
- Place each test file at the same relative path as the class under test. The class `app/Actions/DeleteTeam.php` gets the test `tests/Unit/Actions/DeleteTeamTest.php`.
- Follow the project's convention for fixture files. If none exists, put fixtures in `tests/Fixtures/` and load them by path.
- Move large literal values out of the test body and into fixture files.
## Test Function
Use the test function used by other files in the same directory. If no neighboring test files exist:
- Use `it()` for the behavior of the code, and write the name as a verb phrase.
- Use `test()` for a declarative fact, such as a grant in a policy, the labels of an enum, or the shape of a serialized model.
Use one Pest declaration style in each file. Use either `it()` or `test()` consistently.
## Naming Tests
The name of a test is a specification. State the user-visible result and the condition that causes it.
- Name the behavior, and not the method under test. The file name already gives the class.
- Give the exact status code in the name of a test for an API error.
- Do not write `Given`, `When`, or `Then` in the name.
```php
it('returns 401 when no token is provided', function () { ... });
it('does not include deployments from deleted environments', function () { ... });
it('falls back to the default region when none is configured', function () { ... });
```
Use a verb that describes a result, such as `returns`, `renders`, `creates`, `dispatches`, `rejects`, `forbids`, `falls back`, or `does not`.
Do not write `it('works correctly')` or `it('returns data')`, because neither specifies a meaningful result. Do not write `it('handleMethod creates record')`, because it names a method rather than behavior.
## Grouping
Use `describe()` if one file covers separate actions in a lifecycle. An example is a controller with the actions `index`, `show`, `store`, `update`, and `destroy`.
Do not use `describe()` in these cases:
- The file covers one action or one flow.
- The tests are different only in the input value. Use a dataset instead.
- The group adds a level but does not make the file easier to read.
@@ -0,0 +1,58 @@
# Test Suite Performance
These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.
Fetch `https://pestphp.com/docs/optimizing-tests` for Pest options that make test runs faster.
Verify each flag in the documentation before adding it to CI.
Measure before changing a setting. Find the slow test first, and apply a project-wide setting only after identifying the costly work.
## Test Environment
- Set `BCRYPT_ROUNDS=4` in `.env.testing` or in `phpunit.xml`. The default value is 12, and the hash then takes most of the time of each test that signs a user in.
- Disable XDebug. Disable pcov also, unless the run needs the coverage.
- Disable packages that perform work on every request in the test environment. Examples are Pulse, Telescope, and Nightwatch.
- Use the `WithCachedConfig` and `WithCachedRoutes` traits, so the run does not parse the configuration and the routes for every test.
- Call `withoutVite()`, or `withoutMix()`, so the framework does not resolve a built asset.
## Global Fakes
Put these three calls in the base `Pest.php` of the project:
- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. This catches requests made through Laravel's HTTP client. Check direct Guzzle and cURL usage separately.
- `Sleep::fake(syncWithCarbon: true)`, so a retry and a backoff do not sleep.
- `Exceptions::fake()`, so the suite does not report an exception to an external service.
## How to Run the Suite in Parallel
Run `vendor/bin/pest --parallel` to spread tests across the machine's CPU cores. Add `--processes=N` if the default count is unsuitable for the machine or CI.
A parallel run gives each process a separate database. Tests must meet these conditions; a test that fails only in parallel breaks one of them:
- The test creates each record that it reads. It does not read a record that another test creates.
- The test does not depend on the order of the run.
- The test does not share a file, a cache key, or a queue with another test. Give each process a separate name for such a resource.
## How to Run Fewer Tests
Run `vendor/bin/pest --parallel --tia` to run only the tests that the recent changes affect. Pest replays the cached result of each other test.
Pest replays cached results rather than skipping unaffected tests. The cache includes each produced value and the covered lines and branches. Pest finds affected Laravel, Symfony, Livewire, and Inertia tests without configuration.
## How to Split Tests Across CI
Run `vendor/bin/pest --update-shards` to measure the time of each test. Run `vendor/bin/pest --shard=1/4` in each CI job, and change the first number for each job.
Commit `tests/.pest/shards.json` so each CI job gets the same shard and the shards remain balanced by runtime rather than test count.
## How to Find a Slow Test
Run `vendor/bin/pest --profile` to list the slowest tests. Start with the ten slowest tests, because the same cause often applies to the complete suite.
If the cause of a slow test is unclear, add an event listener or temporary log entry to identify its work.
## Common Errors
- The run loads XDebug for a test that does not need it.
- `BCRYPT_ROUNDS` keeps the default value, because the project has no `.env.testing`.
- The code under test calls the real `sleep()`, and `Sleep::fake()` then does not help.
@@ -0,0 +1,44 @@
# Reviewing Tests
Check every item in this file. A passing test may still provide no value. For each test, identify the defect it would catch.
Report each finding. Do not delete or rewrite a test without the user's approval. When an issue appears throughout the suite as a convention, report the pattern once rather than every affected file.
## Test Value
Apply this section to behavioral tests. An architecture test states a convention for a directory, so these items do not apply to it.
- [ ] Each test covers observable behavior or an application contract, and passes after a change to the implementation that keeps the behavior.
- [ ] Each tested declaration is exercised through behavior, and no test asserts the behavior of the framework. A test of what this project configures, such as a relation with a constraint, a cast, or a scope, belongs to this project.
- [ ] Each test detects a distinct defect that no other test covers. A duplicate shrinks at the higher layer to the one case that proves the wiring.
- [ ] Every changed decision and each applicable high-value failure mode has coverage.
## Names and Structure
- [ ] Each file has the name `{ClassName}Test.php` and the relative path of the class under test.
- [ ] Each name states a result, the condition that causes it, and the status code for an API error.
- [ ] Each file uses one declaration style consistently, and each `describe()` group holds separate behavior.
## Coverage
- [ ] HTTP tests cover authentication, authorization, role, scope, and validation when applicable.
- [ ] A request for a record of a different tenant gets a status code that does not confirm that the record exists.
- [ ] The complete permission matrix belongs in policy tests, not controller tests.
- [ ] Each validation rule has one test that asserts the user-visible message. When a unit test owns a matrix, reduce duplicate higher-level coverage to one case rather than deleting it.
- [ ] Rendered user input and each dynamic part of a query have a security test.
## Data and Determinism
- [ ] Each test creates its mutable records directly or through a helper that it calls, and every created record arranges the behavior or supports an assertion.
- [ ] Each `beforeEach()` holds configuration only.
- [ ] Each factory state and each relationship gives the meaning of the data.
- [ ] Each call to `make()` is in a test that does not need the database.
- [ ] Time, randomness, sleep, and outbound HTTP are controlled.
- [ ] Each test passes alone, and passes in the complete suite in any order.
## Assertions
- [ ] Each expected value is a known value, and the test does not calculate the value with the logic of the implementation.
- [ ] Each test of a write operation asserts the response, the state in the database, and the side effects.
- [ ] Each fake has one assertion, and gives the class names unless the test asserts the complete result.
- [ ] Each `expect()` chain stays on one subject.
@@ -0,0 +1,27 @@
# Security Tests
Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary can be difficult to detect because the feature may continue to work.
Write a test for each of these cases:
- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for why the response should possibly be `404` rather than `403`.
- **Each unprivileged role.** Use a dataset over the roles that the endpoint must refuse.
- **Escaping user-provided content.** Test escaping in HTML and mail. Include names and every free-text field a template renders. Assert that dangerous characters are escaped and the raw value is absent. Do not assert an exact entity for a quote, because Markdown and mail CSS inliners may decode it.
- **Injection into dynamic query components.** Examples include sort columns, filter fields, and sort directions.
- **An unexpected key** in a payload or configuration array. A merge that accepts every key can set an attribute the user must not control.
```php
it('escapes dangerous content in the notification', function () {
$organization = Organization::factory()->make([
'name' => "O'Reilly <script>alert('xss')</script>",
]);
$content = (new QuotaApproaching($organization, 80))->toMail()->render();
expect($content)
->toContain('&lt;script&gt;')
->not->toContain("<script>alert('xss')</script>");
});
```
Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the appropriate defense to each attribute, route, and template.
@@ -0,0 +1,56 @@
# Factories and Test Data
## Each Test Makes Its Own Data
Create mutable records inside the test that uses them. This keeps setup visible and lets each test select its factory state.
Use `beforeEach()` only for configuration that applies to every test in the file. Do not create records in it.
## Record Construction
- Use `create()` if the test needs the record in the database.
- Use `make()` only if the test does not need the database. Examples include rendering a notification and testing a value object's behavior.
- Use a named factory state instead of a raw attribute. `User::factory()->unverified()->create()` gives the state meaning; `create(['email_verified_at' => null])` gives only its value.
- Use `for()` or the relationship helper of the project to declare the owner of a record.
- Use `recycle()` if several records must share one parent record.
- Use `sequence()` if several records need different attributes.
```php
$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();
$environment = Environment::factory()->recycle($organization)->create();
$organizations = Organization::factory()
->count(3)
->sequence(
['created_at' => now()->setSeconds(30)],
['created_at' => now()->setSeconds(1)],
)
->create();
```
Create only the records required to arrange the behavior or support an assertion.
## Datasets
Use a dataset when the setup, test body, and assertions remain the same across input values.
```php
it('forbids roles other than admin', function (Role $role) {
actingAs(User::factory()->hasOrganization($role)->create())
->post('/settings')
->assertForbidden();
})->with(collect(Role::cases())->reject(fn (Role $role) => $role === Role::ADMIN));
```
Use parameterized tests for:
- enum cases
- roles and plans
- boundary values
- input values that are invalid in the same way
- input and output value pairs
Write separate tests if the cases need a different setup, a different behavior, or different assertions. One test function with a branch in the body is two tests in one function.
Give each dataset case a name that states the difference. A failure then identifies the case without requiring you to count positions.
+4 -1
View File
@@ -21,10 +21,13 @@ docker-compose*.yml
Dockerfile
# CI/CD
.github
.gitea
# Testing
tests
# Website (published separately)
website
phpunit.xml
.phpunit.cache
+16 -1
View File
@@ -69,5 +69,20 @@ VITE_APP_NAME="${APP_NAME}"
# OCTANE_HTTPS=false
# OCTANE_MAX_EXECUTION_TIME=300
# Docker (used only when deploying with docker-compose.yml)
# Uploads: each encrypted chunk the browser sends, in MB
# UPLOAD_CHUNK_SIZE_MB=16
# Docker development: `docker compose up` runs this file. On OrbStack, also set
# APP_URL=https://app.sealshare.orb.local and VITE_DEV_SERVER_URL=https://vite.sealshare.orb.local.
# Without OrbStack, append :docker-compose.ports.yml and set APP_URL=http://localhost:8000.
COMPOSE_FILE=docker-compose.dev.yml
# Where the browser reaches the Vite dev server, when not on http://localhost
# VITE_DEV_SERVER_URL=https://vite.sealshare.orb.local
# Ports on this machine: the Vite dev server's, and the app's with docker-compose.ports.yml
# VITE_PORT=5173
# APP_PORT=8000
# Docker production (docker compose -f docker-compose.yml), with AUTO_HTTPS=true
# SERVER_NAME=share.example.com
+1 -1
View File
@@ -8,4 +8,4 @@
CHANGELOG.md export-ignore
README.md export-ignore
.github/workflows/browser-tests.yml export-ignore
.gitea export-ignore
@@ -42,9 +42,6 @@ jobs:
- name: Install Node Dependencies
run: npm ci
- name: Add Flux Credentials Loaded From ENV
run: composer config http-basic.composer.fluxui.dev "${{ secrets.FLUX_USERNAME }}" "${{ secrets.FLUX_LICENSE_KEY }}"
- name: Install Dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader
@@ -57,6 +54,9 @@ jobs:
- name: Build Assets
run: npm run build
- name: Install Playwright Browsers
run: npx playwright install --with-deps chromium
- name: Run Tests
run: ./vendor/bin/pest
@@ -67,25 +67,33 @@ jobs:
- name: Checkout code
uses: actions/checkout@v6
# The runner is an arm64 server, so the amd64 image's final stage is emulated. QEMU 8.x
# crashes running x86_64 programs on an arm64 host (QEMU issue 2168, "QEMU internal
# SIGSEGV {code=MAPERR, addr=0x20}") and 10.2 segfaults on this runner too; 9.2.2 was
# checked on the runner's host: node, composer and install-php-extensions all run.
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
image: tonistiigi/binfmt:qemu-v9.2.2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
# Gitea's job token cannot publish packages yet: REGISTRY_TOKEN is an access token with
# package write rights, owned by the account that pushes (gitea.actor).
- name: Log in to the Gitea container registry
if: gitea.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
registry: gitea.nonameweb.ch
username: ${{ gitea.actor }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
images: gitea.nonameweb.ch/nonameweb/sealshare
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
@@ -98,21 +106,27 @@ jobs:
with:
context: .
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
push: ${{ gitea.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
cache-from: type=registry,ref=gitea.nonameweb.ch/nonameweb/sealshare:buildcache
cache-to: ${{ gitea.event_name != 'pull_request' && 'type=registry,ref=gitea.nonameweb.ch/nonameweb/sealshare:buildcache,mode=max' || '' }}
release:
runs-on: ubuntu-latest
needs: build-and-push
if: startsWith(github.ref, 'refs/tags/v')
if: startsWith(gitea.ref, 'refs/tags/v')
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
- name: Take the release notes from the changelog
run: |
version="${{ gitea.ref_name }}"
awk -v heading="## [${version#v}]" 'index($0, heading) == 1 { found = 1; next } found && /^## \[/ { exit } found { print }' CHANGELOG.md > release-notes.md
test -s release-notes.md
- name: Create the Gitea release
uses: https://gitea.com/actions/gitea-release-action@v1
with:
generate_release_notes: true
body_path: release-notes.md
@@ -29,9 +29,6 @@ jobs:
with:
php-version: '8.5'
- name: Add Flux Credentials Loaded From ENV
run: composer config http-basic.composer.fluxui.dev "${{ secrets.FLUX_USERNAME }}" "${{ secrets.FLUX_LICENSE_KEY }}"
- name: Install Dependencies
run: |
composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
@@ -47,4 +44,4 @@ jobs:
# commit_options: '--no-verify'
# file_pattern: |
# **/*
# !.github/workflows/*
# !.gitea/workflows/*
@@ -42,9 +42,6 @@ jobs:
- name: Install Node Dependencies
run: npm i
- name: Add Flux Credentials Loaded From ENV
run: composer config http-basic.composer.fluxui.dev "${{ secrets.FLUX_USERNAME }}" "${{ secrets.FLUX_LICENSE_KEY }}"
- name: Install Dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader
@@ -57,5 +54,8 @@ jobs:
- name: Build Assets
run: npm run build
- name: Install Playwright Browsers
run: npx playwright install --with-deps chromium
- name: Run Tests
run: ./vendor/bin/pest
+5
View File
@@ -25,3 +25,8 @@ yarn-error.log
**/caddy
frankenphp
frankenphp-worker.php
/tests/Browser/Screenshots
# Planning notes stay local
/docs/plans
+174
View File
@@ -0,0 +1,174 @@
# Changelog
All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.2.0] - 2026-09-19
### Added
- The admin dashboard shows the installed SealShare version, with links to its release notes, the SealShare website and noNameWEB.
### Changed
- `docker-compose.example.yml` mounts `sealshare_database` at `/app/database/sqlite` instead of `/app/database`, and sets `DB_DATABASE: /app/database/sqlite/database.sqlite`. Existing compose files keep working. To switch, mount the same volume at the new path and set `DB_DATABASE` in both services; the database is kept.
- A share that reaches its download limit is closed at once, but deleted by the hourly cleanup 24 hours after its last download instead of immediately, so downloads still running can finish. Until then its files count towards the storage quota.
- The download page of a share with a download limit says how many downloads are left, or how long the recipient can still download.
- The admin dashboard shows downloads as "2 of 3 downloads" and marks shares at their limit as "Download limit reached". These no longer count as active shares.
- The sort dropdown on the admin dashboard spans the full width of the shares card.
- PHP reads the Docker image's limits (`PHP_UPLOAD_MAX_FILESIZE`, `PHP_POST_MAX_SIZE`, `PHP_MAX_EXECUTION_TIME`, `PHP_MAX_INPUT_TIME`, `PHP_MEMORY_LIMIT`) from the environment itself; the entrypoint no longer writes an ini file on start. The variables and their defaults are unchanged.
- Updated to Livewire Material 2.2.0.
- Development: `docker-compose.dev.yml` extends `docker-compose.yml`, so the dev stack runs the scheduler and the production image's PHP extensions, plus a Vite dev server with hot reload. It takes its settings from `.env`, and publishes ports only with `docker-compose.ports.yml`. `docker/dev.Dockerfile` became the `dev` stage of the `Dockerfile`.
### Fixed
- Docker installs set up before 2.1.0 answered every upload with "409 Conflict" after the update. The example `docker-compose.yml` mounted the SQLite volume over all of `/app/database`, which hid the image's new migrations, so they never ran. The container now adds the migrations the volume is missing before migrating.
- A share with several files and a download limit was deleted as soon as one file was downloaded, because every file counted as a whole download. Now one recipient's visit counts once, and they have 1 hour to download all the files and the ZIP. Two recipients who start at the same moment can no longer both get the last download.
- The scheduler container no longer shows as "unhealthy". It inherited the image's healthcheck, which asks the web server that only the app container runs. For an existing install, add `healthcheck: { disable: true }` to the scheduler service in your `docker-compose.yml`.
- The "30 Days" expiration lasted a calendar month; it now lasts 30 days.
- Admin settings only save a default expiration that is one of the offered options.
### Removed
- Email verification (`/email/verify`), which was never enforced: SealShare has a single admin account and no registration.
- The `composer dev` script and the packages only it used (`concurrently`, `laravel/pail`, `laravel/sail`, `autoprefixer`), with the `shell-quote` override that `concurrently` needed. Development runs in Docker (`docker-compose.dev.yml`).
## [2.1.0] - 2026-09-16
### Added
- A password generator for share passwords, with a copy button. The password is shown once more beside the new link. Admins can turn it off, or switch between random characters and a passphrase, in Admin settings.
- `AUTO_HTTPS` for the Docker image: set it to `"true"` with `SERVER_NAME` to get a Let's Encrypt certificate and serve HTTPS. Without it the container serves plain HTTP on port 80, as before.
- `UPLOAD_CHUNK_SIZE_MB` sets the size of each upload chunk (default 16).
### Changed
- **Breaking: uploads need HTTPS.** Files are now encrypted in the browser and uploaded in chunks, which browsers only allow over HTTPS or on `localhost`. Over plain HTTP downloads still work, but uploads don't. Use `AUTO_HTTPS` or a reverse proxy that terminates TLS.
- Large uploads are much faster: each chunk is written to disk once, already encrypted, and a failed chunk is retried.
- Each share has its own random key; with a share password it is protected with Argon2id instead of PBKDF2. Existing shares keep working.
- PHP's upload limits no longer cap the share file size. `PHP_UPLOAD_MAX_FILESIZE` and `PHP_POST_MAX_SIZE` default to `64M`, and `LIVEWIRE_MAX_UPLOAD_TIME` is no longer needed.
- Unfinished uploads count towards the storage quota and are deleted after 4 hours.
- The interface moves to [Livewire Material](https://gitea.nonameweb.ch/noNameWEB/livewire-material) 2.1.0 and no longer ships Tailwind CSS. Every page uses the same single-column layout of cards, and the admin dashboard lists shares instead of a table. Colour profiles and light/dark choices carry over.
### Fixed
- "Download all" works for large shares: the ZIP is streamed instead of being built in memory and written unencrypted to a temporary file.
- Unencrypted copies of uploads no longer stay behind in Livewire's temporary folder; the hourly cleanup removes old ones.
- Removed the unused `docker/Caddyfile`.
### Security
- An encrypted file with missing or reordered chunks now fails to decrypt.
## [2.0.1] - 2026-09-13
### Fixed
- The 2.0.0 Docker image did not start: the entrypoint's `php artisan view:cache` failed with "Unable to locate a class or view for component [showcase::example]", because Livewire Material only registered its showcase components while the showcase was enabled, which it is not in production. Livewire Material 1.1.1 registers them always, and a test now caches every view as the entrypoint does.
## [2.0.0] - 2026-09-13
### Added
- Eight colour profiles — Indigo (the default), Blue, Teal, Green, Amber, Rose, Violet and Graphite. An admin picks one in Admin settings, previews it on the page, and after saving every page, mail and error page uses it; light and dark stay each visitor's own choice.
- The share created page offers the link as a QR code: "Show QR code" opens it in a dialog (full screen on a phone) and "Download" saves it as a PNG. For a password-protected share the dialog reminds that recipients also need the password; the code holds only the link.
- A "Share…" button on the same page opens the device's share sheet with the link, where the browser has one (mostly phones and Safari).
### Changed
- SealShare moved from GitHub to Gitea: the source is at https://gitea.nonameweb.ch/noNameWEB/SealShare, and the Docker image is published as `gitea.nonameweb.ch/nonameweb/sealshare`. Images at `ghcr.io/surtic86/sealshare` are no longer updated — change `image:` in your `docker-compose.yml` to the new name to keep receiving releases.
- The interface is rebuilt on [Livewire Material](https://gitea.nonameweb.ch/noNameWEB/livewire-material), a Material 3 Expressive component library, replacing Mary UI and DaisyUI. Every page — upload, share created, download, sign-in, settings, admin and the setup wizard — uses its components, in a colour scheme generated from SealShare's indigo.
- The theme follows the system's light or dark setting until a user picks Light, Dark or System in Settings → Appearance, or from the account menu. A theme chosen in 1.x is kept.
- A floating toolbar centred at the bottom of every page replaces the sidebar and header layouts. Signed-in users reach Upload and the admin pages from it, and Settings, the theme and Log out from its account menu. The site's name and logo head the upload and download pages.
- Confirmations for deleting a share, removing the logo, clearing the system password and deleting the account are dialogs instead of browser prompts, and "Saved." messages are snackbars.
- The two-factor setup opens full screen on a phone.
- HTTP error pages and Markdown mail (password reset, email verification) use the same Material design and colours. Set `MAIL_MARKDOWN_THEME=default` to get Laravel's mail theme back.
- Signing in now lands on the admin dashboard. The starter kit's placeholder `/dashboard` page is gone.
- The Docker build installs Composer packages before building the frontend, because the stylesheet imports Livewire Material from `vendor/`.
- Removed the dependencies `robsontenorio/mary`, `daisyui` and `alpinejs` (Livewire bundles Alpine). The Bunny Fonts request is gone.
### Fixed
- The README called SealShare's encryption end-to-end. Files are encrypted at rest on the server; the README now says so, and that a share password's key is never stored.
- The admin dashboard passed its sort column and direction straight to the query, so a crafted Livewire request could order shares by any column or cause a server error. It now sorts only by the columns it shows and otherwise falls back to newest first.
## [1.2.0] - 2026-09-10
### Added
- `LIVEWIRE_MAX_UPLOAD_TIME` (minutes, default 30) sets how long a single upload may take before its signed upload URL expires. Raise it when large files arrive over slow connections.
- A "Large files" section in the README listing every limit that has to be raised together for big uploads: PHP, admin settings, upload time, execution time and the reverse proxy.
### Changed
- Upgraded to Pest 5.1 (`pestphp/pest` ^5.1, `pestphp/pest-plugin-laravel` ^5.0), which brings PHPUnit 13.3. The test suite needed no changes.
- Updated PHP dependencies within their existing constraints: Laravel 13.31, Livewire 4.4.4, Octane 2.19.1, Fortify 1.39, Mary 2.9.10, Boost 2.8 and Pint 1.32. Guzzle moves to 8.2 as a transitive dependency of Laravel.
- Updated frontend dependencies: Alpine.js 3.17.2, DaisyUI 5.7.32, Vite 8.2.2 and `laravel-vite-plugin` 3.2.
### Fixed
- Files larger than 4 GB were always rejected with "Upload failed: file exceeds the maximum size of N MB", even when the admin's maximum file size N was bigger than the file. Livewire's temporary upload rule had a hard-coded 4 GB cap; it is gone, so `PHP_UPLOAD_MAX_FILESIZE` is the hard limit and the admin setting is the enforced one.
- An upload the server rejects no longer blames the admin's maximum file size. The user is told the server could not accept the file, and the actual reason is logged as a warning.
## [1.1.0] - 2026-07-23
### Changed
- Upgraded to Laravel 13 (`laravel/framework` ^13.0, `laravel/tinker` ^3.0). PHP 8.5 is now the minimum.
- Set `serializable_classes` to `false` in `config/cache.php`, so a leaked `APP_KEY` cannot drive an object gadget chain through the cache.
- Upgraded the frontend toolchain to match the Laravel 13 skeleton: Vite 8, `laravel-vite-plugin` 3, Tailwind CSS 4.3.3, DaisyUI 5.7, Alpine.js 3.15.12 and concurrently 10.
### Fixed
- Adding a second batch of files to a share left the uploader stuck on "Processing files…" forever, with the drop zone and the "Create Share Link" button permanently disabled. The uploading state is now cleared by a `files-processed` event dispatched on every batch, instead of a one-off `x-init` that only ran the first time the file list appeared.
- Dropping files on the drop zone showed no upload progress at all, because `uploadMultiple()` was called without progress callbacks.
- Dropping a second folder onto an existing selection replaced the collected relative paths instead of appending them, which shifted every earlier file's path onto the wrong file.
### Removed
- Dropped the unused `axios` dependency and the stale `@rollup/rollup-linux-x64-gnu` optional pin (Vite 8 builds with rolldown).
### Security
- Forced `shell-quote` to a patched release via an npm override, clearing GHSA-395f-4hp3-45gv (quadratic complexity DoS). `npm audit` reports 0 vulnerabilities, down from 3.
## [1.0.1] - 2026-02-25
### Fixed
- ZIP downloads returned 0-byte archives under FrankenPHP. ZipStream writes through `fwrite(php://output)`, which FrankenPHP silently drops; downloads are now built with native `ZipArchive` and served as a file response.
- Docker image was missing the PHP `zip` extension required by `ZipArchive`.
- Stale `bootstrap/cache/*.php` from the build context could load dev-only service providers in the production image.
- `DB_DATABASE` now defaults to `/app/database/database.sqlite` in `docker-compose.yml`, so the `env()` fallback resolves correctly.
- The unlock button on the password-protected share page rendered outside the form and did nothing. Share page action buttons are now consistently full width.
### Removed
- `maennchen/zipstream-php` dependency.
## [1.0.0] - 2026-02-13
### Added
- Initial release.
- File uploading via drag & drop or browse, supporting multiple files and folders with real-time progress.
- Shareable links, one unique link per upload.
- AES-256-GCM encryption at rest, chunked and streaming, with PBKDF2-SHA256 key derivation.
- Optional password protection per share.
- Configurable expiration from 1 hour to 30 days, and per-share download limits.
- ZIP download of all files in a share.
- Hourly auto-cleanup of expired shares and their files.
- Admin dashboard and settings for upload limits, storage quotas and branding.
- Site branding: custom logo, title and description.
- Optional system password gate restricting upload access.
- User authentication (login, registration, password reset, email verification) and TOTP two-factor authentication via Laravel Fortify.
- First-run setup wizard for creating the initial admin account.
- Dark themed UI built with Livewire, Alpine.js, Tailwind CSS and DaisyUI.
- Docker images published to `ghcr.io/surtic86/sealshare`, served by FrankenPHP via Laravel Octane.
[2.2.0]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.1.0...v2.2.0
[2.1.0]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.0.1...v2.1.0
[2.0.1]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.0.0...v2.0.1
[2.0.0]: https://gitea.nonameweb.ch/noNameWEB/SealShare/releases/tag/v2.0.0
+116 -26
View File
@@ -7,23 +7,11 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for
## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
This application is a Laravel application running on PHP 8.5. You are an expert with the Laravel ecosystem. Always use the APIs that match the installed major version of each package — do not assume a version.
- php - 8.5
- laravel/fortify (FORTIFY) - v1
- laravel/framework (LARAVEL) - v13
- laravel/octane (OCTANE) - v2
- laravel/prompts (PROMPTS) - v0
- livewire/livewire (LIVEWIRE) - v4
- laravel/boost (BOOST) - v2
- laravel/mcp (MCP) - v0
- laravel/pail (PAIL) - v1
- laravel/pint (PINT) - v1
- laravel/sail (SAIL) - v1
- pestphp/pest (PEST) - v4
- phpunit/phpunit (PHPUNIT) - v12
- alpinejs (ALPINEJS) - v3
- tailwindcss (TAILWINDCSS) - v4
Before relying on a package's API, confirm its installed version:
- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show <vendor/package>` for a single package.
- JS packages: check `package.json` for the installed versions.
## Skills Activation
@@ -70,7 +58,7 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
## Searching Documentation (IMPORTANT)
- Always use `search-docs` before making code changes. Do not skip this step. It returns version-specific docs based on installed packages automatically.
- Use `search-docs` before changes that depend on Laravel ecosystem APIs, behavior, configuration, or version-specific syntax. Skip it for copy-only edits and other changes where package documentation is irrelevant. Reuse sufficient results already in context instead of searching again.
- Pass a `packages` array to scope results when you know which packages are relevant.
- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first.
- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`.
@@ -82,6 +70,11 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
3. Combine words and phrases for mixed queries: `middleware "rate limit"`.
4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.
## Project Rules
- This project contains committed, area-grouped rules in `.ai/rules` when that directory exists (settled decisions, non-obvious traps, standing constraints). Framework and package guidelines that only apply to specific paths (testing, frontend, components) also live there, under `.ai/rules/boost` — this is not just recorded decisions, it is load-bearing guidance you have not seen inline. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule. If `.ai/rules` does not exist, continue without it.
- Record a rule with `record-rule` only when the user explicitly asks for one. Instructions for the work at hand are not rules, no matter how emphatic: "remove this typo", "use X here" are work to do, not rules to record. Never record a rule on your own initiative, as a byproduct of a change, or to summarize what you just did. When the user does ask, pass a `glob` (e.g. `app/Http/Controllers/**`), a short `title`, and a few-line `note`. Use `record-rule` rather than your native memory or notes tool, because native memory is personal and session-scoped, while only `.ai/rules` is shared with the team and persists in the repo.
## Artisan
- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.
@@ -110,13 +103,17 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
# Deployment
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
- Activate the `deploying-to-cloud` skill whenever deploying to Laravel Cloud, configuring Cloud environments or resources, using the Cloud CLI, or troubleshooting Cloud deployments.
=== tests rules ===
# Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test --compact` with a specific filename or filter.
- Add or update tests for behavior and logic changes when a test provides meaningful regression coverage.
- Pure copy, styling, and layout-only changes do not require new or updated tests.
- When test coverage applies, run the affected tests and ensure they pass.
- Test the changed behavior and its important failure modes, but do not add tests beyond them.
- Read the `testing-best-practices` skill before writing tests.
=== laravel/core rules ===
@@ -148,7 +145,7 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
=== octane/core rules ===
=== laravel-octane/core rules ===
# Laravel Octane
@@ -164,7 +161,7 @@ When working on Octane-specific features (concurrency, shared tables, memory, dr
# Livewire
- Livewire allow to build dynamic, reactive interfaces in PHP without writing JavaScript.
- Livewire allows you to build dynamic, reactive interfaces in PHP without writing JavaScript.
- You can use Alpine.js for client-side interactions instead of JavaScript frameworks.
- Keep state server-side so the UI reflects it. Validate and authorize in actions as you would in HTTP requests.
@@ -177,11 +174,104 @@ When working on Octane-specific features (concurrency, shared tables, memory, dr
=== pest/core rules ===
## Pest
# Pest
- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.
- The `{name}` argument should not include the test suite directory. Use `php artisan make:test --pest SomeFeatureTest` instead of `php artisan make:test --pest Feature/SomeFeatureTest`.
- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.
- Do NOT delete tests without approval.
- This project uses Pest. Create tests with `php artisan make:test --pest {name}`.
- Do not include the test suite directory in `{name}`. Use `SomeFeatureTest`, not `Feature/SomeFeatureTest`.
- Read the `testing-best-practices` skill for guidance on coverage, naming, structure, dependency isolation, and review.
- Do not delete tests or test files without approval. They are part of the application.
## Running Tests
- Run the narrowest set of tests that covers the change. Pass a file path or `--filter=testName` to `php artisan test --compact`.
- Rerun a test after each change to it.
- Run `vendor/bin/pest` to call the test runner directly. It accepts the same file path and `--filter=testName` arguments.
- After the feature tests pass, ask the user to run the complete suite with `php artisan test --compact`.
=== nonameweb/livewire-material/core rules ===
## Livewire Material
This application uses `nonameweb/livewire-material`: Material 3 Expressive components for Laravel and Livewire, in plain CSS. No utility classes — Tailwind, daisyUI or any other — belong here: a class your CSS does not declare does nothing, and `DesignGuard` fails it.
- Components are anonymous Blade components, unprefixed unless `config/livewire-material.php` sets a `prefix`. Before writing or changing a view that uses them, activate the `livewire-material-development` skill for the props, slots and traps of each component.
- The CSS entry imports `foundation.css` first, then the stylesheet of each component the views render (or `all.css` for all of them). A component whose stylesheet is not imported renders unstyled; `DesignGuard::missingStylesheets()` names each missing `@import`.
- Every layout includes `<x-theme-script />` in `<head>` before `@vite`. The colour scheme is generated with `php artisan material:scheme` — never edit `resources/css/material-scheme.css` by hand. With colour profiles (`livewire-material.profiles`), run it without a seed after changing them; the active profile comes from `Scheme::resolveProfileUsing()`.
- While the application runs locally, every token and component renders in the application's own scheme at `/material` (the showcase).
- HTTP error pages and the Markdown mail theme come from the package. Change error wording by publishing `--tag=livewire-material-errors`; select the mail theme with `MAIL_MARKDOWN_THEME=livewire-material::mail.theme`.
=== nonameweb/livewire-material/material-3 rules ===
## Material 3
Every view in this application is Material 3 Expressive (m3.material.io), through `nonameweb/livewire-material`. These rules decide what to write; the `material-3-design` skill carries the tables, the numbers and Google's source pages behind each one — activate it before designing a screen.
The library is plain CSS on M3's tokens. No utility classes — Tailwind, daisyUI or any other — belong here: a class your CSS does not declare does nothing, and `DesignGuard` fails it. A view is written three ways:
- Components and their props: `<x-button variant="filled">`, and the layout components `<x-row>`, `<x-stack>`, `<x-grid>`, `<x-feed>`, `<x-surface>` and `<x-pane>`, whose `gap` and `padding` take a spacing token (`space200`) and whose `hide-below`, `hide-from` and `stack-below` take a window size class.
- A fixed set of classes for text and interaction on plain elements: `md-type-*`, `md-ink-*`, `md-text-*`, `md-truncate`, `md-tabular`, `md-visually-hidden`, `md-state-layer`, `md-focus-ring`, `md-touch-target` and `md-link`.
- The application's own CSS, named by the application, whose values are `--md-sys-*` custom properties.
### Colour
- A colour is always a role: `md-ink-variant` on text, `var(--md-sys-color-outline-variant)` in the application's CSS, `color="error"` on a component. Never a hex, a palette tone or an opacity.
- Pair a role only with its `on-` partner: a `primary` fill takes `on-primary` text, a `secondary-container` fill takes `on-secondary-container`. That pair is the one whose contrast is guaranteed at every contrast level; mixing pairs (`primary-container` under `on-surface`) is not.
- `primary` is the one key action on a screen (a filled button; the FAB in `primary-container`). `secondary-container` is the quiet fill (tonal buttons, selected navigation, selected chips). `tertiary` is a contrasting accent, used rarely. `error`, `success`, `warning`, `info` mean state and nothing else: the `-container` for a tinted panel, the role itself for its text and icon.
- Ink is `on-surface` (`md-ink`); lower emphasis is `on-surface-variant` (`md-ink-variant`); decoration is `outline` (`md-ink-quiet`). Never dim ink with an opacity: 38% means disabled.
- `outline` is a boundary that must be read (a text field, the edge of a target). `outline-variant` is a divider or a card edge (`<x-divider>`, `<x-surface outlined>`). Never `outline` on a divider.
- Fixed and dim roles (`primary-fixed`, `surface-dim`, …) are for a colour that must not change with the theme; if unsure, don't. Inverse roles only on an inverse surface (the snackbar).
- A link in running text is underlined (`md-link`, with `md-ink-primary`); colour alone signals nothing.
- Contrast: 4.5:1 for text, 3:1 for large text, icons and grouped controls; disabled is exempt. Three contrast levels exist (`<html data-contrast>`: standard, medium, high) and every role changes with them — which is why only roles are allowed.
### Surfaces and elevation
- The page is `surface`. Panels separate by tone first: `surface-container-lowest` … `surface-container-highest` is a hierarchy of emphasis, not of height (`<x-surface level="surface-container-high">`). Navigation chrome is `surface-container`; a dialog, a menu, the search bar are `surface-container-high`; a modal sheet is `surface-container-low`; a filled card is `surface-container-highest`. A region keeps its role at every width.
- Shadows (`var(--md-sys-elevation-1)` … `-5`) are for what floats or lifts: 1 for elevated cards, buttons and modal sheets; 2 for menus, the navigation bar, a scrolled app bar; 3 for the FAB, dialogs, pickers and search; one level more on hover; nothing rests above 3. Fewer shadows carry more meaning.
- A scrim is `scrim` at 32%: `color-mix(in srgb, var(--md-sys-color-scrim) 32%, transparent)`.
### Shape
- Corners come from the scale `var(--md-sys-shape-corner-{none|xs|sm|md|lg|lg-increased|xl|xl-increased|xxl|full})`, or `<x-surface corner="md">`; never a length of your own.
- By family: `full` buttons, icon buttons, chips' avatars, badges, switches, sliders, the search bar, navigation indicators; `xs` text fields, menus, snackbars, plain tooltips; `sm` chips; `md` cards, rich tooltips; `lg` the FAB and a side sheet's inner corners; `xl` dialogs, bottom sheets, the search view, pickers, carousel items; `xxl` large hero containers.
- Nested shapes: inner radius = outer radius − padding; never the same radius inside and out.
- A press squares a round shape (the components do it; nothing morphs on hover). The 35 `<x-shape>`s are decoration, never meaning, used sparingly.
### Type
- Every text element carries one `md-type-*` class: `display` for hero figures and short marketing lines; `headline` for page and section titles; `title` for card, dialog and list-section titles; `body` for paragraphs (`md-type-body-lg` for reading); `label` inside components (buttons, chips, tabs, captions). In the application's CSS a style is `font: var(--md-sys-typescale-body-md)` with its `-tracking`; never a size, weight, line height or letter spacing of your own.
- `md-type-emphasized-*` is opt-in: a selected item, a primary action, a headline, a badge — not decoration.
- 40–60 characters per line; `md-tabular` on figures that change; text must scale to 200% without loss (containers grow, rows wrap, no fixed heights on text, no ellipsis without a way to read the rest).
### Motion
- Position, size and shape move on the spatial springs (they overshoot): `transition: transform var(--md-sys-motion-spatial-default-duration) var(--md-sys-motion-spatial-default)` — `fast` for small elements, `slow` for large ones. Colour and opacity move on the effects springs (`--md-sys-motion-effects-*`), which never overshoot. Always pair an easing with its duration.
- Entering decelerates, a permanent exit accelerates, a temporary exit (a sheet, a drawer) takes the emphasized curve; exits are shorter than entrances.
- Everything that moves goes through these tokens, so reduced motion makes it instant; a literal duration is a bug.
### States and targets
- Interactive elements carry `md-state-layer md-focus-ring`: hover 8%, focus 10%, pressed 10%, dragged 16% (`data-md-dragged`) of the content colour. Disabled is content at 38% and a container at 12% of `on-surface` (`--md-sys-state-disabled-content-opacity`, `--md-sys-state-disabled-container-opacity`, through `color-mix()`), with no state layer. Every state shows two indicators: colour plus a shape, an outline, an icon or a word.
- Every target is at least 48×48px with 8px between targets (`md-touch-target` on anything drawn smaller); a denser layout is an opt-in prop, never a default.
- Keyboard: Tab between components, arrows within one, Enter and Space activate, Escape dismisses; a dialog takes focus and gives it back to what opened it.
### Layout and breakpoints
- Widths are M3's window size classes and only those: compact below 600px (the default), medium 600, expanded 840, large 1200, extra-large 1600. A layout component takes them as props (`<x-row stack-below="medium">`, `<x-stack hide-from="expanded">`, `<x-grid :columns="['compact' => 1, 'expanded' => 2]">`); the application's CSS writes `@media (width >= 840px)`; a script asks `from()` and `upTo()` from `resources/js/breakpoints.js`.
- What changes per class: compact — navigation bar, one pane, full-screen dialogs, a bottom sheet for choices; medium — collapsed rail, one pane; expanded — rail (collapsible), two panes, menus and basic dialogs; large and extra-large — the rail expanded, two panes, a third only at extra-large as a side sheet. `<x-scaffold>` does this; content lives in panes (`<x-pane>`, `<x-list-detail>` for a list's second pane), never beside the rail by hand.
- Margins are 16px below medium and 24px from it (`<x-pane>` draws them); spacing sits on the 4px grid as `space25` … `space900`, as padding and gaps on the parent, with margins only between layout regions. A fixed pane is 360px (expanded) or 412px (large); a side sheet at most 400px.
- Write logical properties (`padding-inline-start`, `inset-inline-end`, `md-text-start`); directional icons mirror in RTL; charts and media controls stay LTR. Keep controls inside the safe area (`--material-safe-*`).
### Accessibility
- Native elements first (`<button>`, `<dialog>`, `<input>`), then ARIA. One `main`, one `banner`, one `contentinfo`; every repeated `nav` labelled, without the word "navigation".
- Headings in order from a single H1; the level is structure, the `md-type-*` class is appearance.
- An icon-only control has an accessible name that does not include its role; decorative icons are hidden; an error is announced and tied to its field (`aria-describedby`); a toast uses a polite live region and never takes focus. A single-key shortcut needs a modifier or a focused component.
### Icons
- `<x-icon name="home">` is a Material Symbol Rounded: `filled` means active or selected, `optical="20"` when drawn at 20px or less, one weight per group, the size and colour of the text beside it.
### Don'ts
- No icon in a snackbar; no disabled FAB (hide it); no horizontal radio rows; no hover morph on cards; no `outline` on dividers; no hex colours; no utility classes, and no breakpoint, radius, shadow, type size or duration off M3's scales; no segmented buttons, navigation drawer or bottom app bar — use `<x-button-group connected>`, the expanded rail and `<x-toolbar>`.
</laravel-boost-guidelines>
+65 -36
View File
@@ -1,22 +1,9 @@
# ============================================
# Stage 1: Build frontend assets
# Stage 1: Install PHP dependencies
# ============================================
FROM node:24-alpine AS assets
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci --prefer-offline
COPY vite.config.js ./
COPY resources/ ./resources/
RUN npm run build
# ============================================
# Stage 2: Install PHP dependencies
# ============================================
FROM composer:2 AS vendor
# Built on the build machine's own platform: vendor/ is plain PHP, the same for every target, so a
# multi-arch build runs it once and never under emulation.
FROM --platform=$BUILDPLATFORM composer:2 AS vendor
WORKDIR /app
@@ -34,20 +21,66 @@ COPY . .
RUN composer dump-autoload --optimize --no-dev
# ============================================
# Stage 3: Production image (FrankenPHP/Octane)
# Stage 2: Build frontend assets
# ============================================
FROM dunglas/frankenphp:php8.5-alpine AS production
# After Composer: the stylesheet and script import Livewire Material from vendor/. On the build
# machine's platform too: the output is CSS and JavaScript, whatever the target.
FROM --platform=$BUILDPLATFORM node:24-alpine AS assets
LABEL maintainer="surtic86"
LABEL org.opencontainers.image.source="https://github.com/surtic86/SealShare"
LABEL org.opencontainers.image.description="Self-hosted encrypted file sharing"
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci --prefer-offline
COPY vite.config.js ./
COPY resources/ ./resources/
COPY --from=vendor /app/vendor/nonameweb ./vendor/nonameweb
RUN npm run build
# ============================================
# Stage 3: PHP runtime, shared by development and production
# ============================================
FROM dunglas/frankenphp:php8.5-alpine AS base
# Install required PHP extensions
RUN install-php-extensions \
intl \
pcntl \
zip
# PHP limits, read from PHP_* environment variables by PHP itself
COPY docker/php/uploads.ini /usr/local/etc/php/conf.d/99-uploads.ini
WORKDIR /app
# ============================================
# Stage 4: Development image (docker-compose.dev.yml)
# ============================================
# Holds only the tools: the checkout is mounted at /app, and its entrypoint runs from there.
FROM base AS dev
# For the dev packages: Pest's browser plugin needs sockets; the screenshot publisher and fake test
# images need gd (the app itself never processes images, so production goes without)
RUN install-php-extensions sockets gd
# Node.js for the Vite dev server
RUN apk add --no-cache nodejs npm
# Composer: the entrypoint installs the packages on every start
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
ENTRYPOINT ["docker/dev-entrypoint.sh"]
# ============================================
# Stage 5: Production image (FrankenPHP/Octane)
# ============================================
# The last stage, so a build without --target builds this one.
FROM base AS production
LABEL maintainer="surtic86"
LABEL org.opencontainers.image.source="https://gitea.nonameweb.ch/noNameWEB/SealShare"
LABEL org.opencontainers.image.description="Self-hosted encrypted file sharing"
# Laravel environment defaults
ENV APP_NAME="SealShare" \
APP_ENV="production" \
@@ -64,14 +97,6 @@ ENV APP_NAME="SealShare" \
BCRYPT_ROUNDS="12" \
OCTANE_SERVER="frankenphp"
WORKDIR /app
# Copy Caddyfile
COPY docker/Caddyfile /etc/caddy/Caddyfile
# Copy PHP ini for upload limits
COPY docker/php/uploads.ini /usr/local/etc/php/conf.d/99-uploads.ini
# Copy application code
COPY . .
@@ -82,23 +107,27 @@ COPY --from=vendor /app/vendor ./vendor
COPY --from=assets /app/public/build ./public/build
# Remove dev/build files and stale cache not needed in production
RUN rm -rf node_modules tests .github docker/dev.Dockerfile docker/dev-entrypoint.sh .env .env.example \
RUN rm -rf node_modules tests .gitea docker/dev-entrypoint.sh .env .env.example \
bootstrap/cache/*.php \
&& mkdir -p storage/app/shares storage/app/public storage/framework/cache \
storage/framework/sessions storage/framework/testing storage/framework/views \
storage/logs database \
storage/logs database/sqlite \
&& chmod -R 777 storage database bootstrap/cache
# A docker-compose.yml from before 2.2.0 mounts the SQLite volume over all of database/, which hides
# the migrations of every later image; the entrypoint adds the ones the volume is missing from here.
RUN cp -R database/migrations docker/migrations
# Create SQLite database file if it doesn't exist
RUN touch database/database.sqlite \
&& chmod 666 database/database.sqlite
# Make entrypoint executable
RUN chmod +x docker/entrypoint.sh
# Make entrypoint and healthcheck executable
RUN chmod +x docker/entrypoint.sh docker/healthcheck.sh
EXPOSE 80 443 443/udp
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD curl --silent --fail http://localhost/up || exit 1
CMD /app/docker/healthcheck.sh
ENTRYPOINT ["docker/entrypoint.sh"]
+77 -24
View File
@@ -2,36 +2,49 @@
A simple, self-hosted file sharing solution built with Laravel. Upload files, get a shareable link, done. All files are encrypted at rest with AES-256-GCM.
**Website:** [sealshare.nonameweb.ch](https://sealshare.nonameweb.ch)
## Screenshots
<p>
<img src="website/img/screenshots/desktop/light/01-upload-800.webp" alt="Uploading files and folders with share options" width="49%">
<img src="website/img/screenshots/desktop/light/02-share-created-800.webp" alt="A new share with its link and QR code button" width="49%">
</p>
<p>
<img src="website/img/screenshots/phone/light/03-download-540.webp" alt="The recipient's download page on a phone" width="30%">
</p>
## Features
- **File Uploading** — Drag & drop or browse to upload single/multiple files and folders with real-time progress
- **Shareable Links** — Each upload generates a unique link for recipients
- **End-to-End Encryption** — All files encrypted at rest using AES-256-GCM (chunked, streaming)
- **Password Protection** — Optionally protect shares with a password
- **File Uploading** — Drag & drop or browse to upload single/multiple files and folders with real-time progress; large files go up in chunks, each retried on its own if the connection drops
- **Shareable Links** — Each upload generates a unique link for recipients, also as a QR code (saved as a PNG) or through the device's share sheet
- **Encryption at Rest** — Files are encrypted in the uploader's browser, chunk by chunk with AES-256-GCM, before they are sent, and are stored only in encrypted form; with a share password the share's key is wrapped with a key derived from it (Argon2id) and never stored as it is. It is not end-to-end encryption: the server issues the key, checks each chunk, and decrypts the files for downloads
- **Password Protection** — Optionally protect shares with a password, typed or generated (random characters or a passphrase, as the admin configures) and copied on the upload page or next to the new link
- **Expiration** — Shares auto-expire after a configurable duration (1 hour to 30 days)
- **Download Limits** — Set a maximum number of downloads per share
- **ZIP Downloads** — Download all files in a share as a single ZIP archive
- **ZIP Downloads** — Download all files in a share as a single ZIP archive, streamed as it is built, whatever the files' size
- **Auto-Cleanup** — Expired shares and files are automatically deleted (hourly)
- **Admin Dashboard** — View, manage, and delete all shares
- **Admin Settings** — Configure upload limits, storage quotas, branding, and more
- **Site Branding** — Custom logo, title, and description
- **Colour Profiles** — Eight Material 3 colour profiles (Indigo, Blue, Teal, Green, Amber, Rose, Violet, Graphite); the admin picks one for every page, mail and error page
- **System Password** — Optional global password gate to restrict upload access
- **User Authentication** — Login, registration, password reset, email verification
- **User Authentication** — Login, password reset, email verification
- **Two-Factor Authentication** — TOTP-based 2FA via Laravel Fortify
- **Dark Mode** — Dark themed UI with DaisyUI components
- **Light and Dark Themes** — Material 3 Expressive design that follows the system theme, or light or dark by choice
- **Setup Wizard** — First-run wizard to create the initial admin account
## Tech Stack
| Layer | Technology |
|-------|-----------|
| **Framework** | Laravel 12 |
| **Framework** | Laravel 13 |
| **Application Server** | FrankenPHP (via Laravel Octane) |
| **Frontend** | Livewire 4, Alpine.js, Tailwind CSS 4, DaisyUI 5, Mary UI |
| **Frontend** | Livewire 4, [Livewire Material](https://gitea.nonameweb.ch/noNameWEB/livewire-material) (Material 3 Expressive) |
| **Authentication** | Laravel Fortify |
| **Encryption** | Chunked AES-256-GCM with PBKDF2-SHA256 key derivation |
| **ZIP Streaming** | maennchen/zipstream-php |
| **Testing** | Pest 4 |
| **Encryption** | Chunked AES-256-GCM (WebCrypto in the browser), keys wrapped with Argon2id |
| **ZIP Downloads** | [ZipStream-PHP](https://packagist.org/packages/maennchen/zipstream-php) |
| **Testing** | Pest 5 with browser tests (Playwright) |
| **Code Style** | Laravel Pint |
| **Build Tool** | Vite |
@@ -39,15 +52,35 @@ A simple, self-hosted file sharing solution built with Laravel. Upload files, ge
### Docker (recommended)
```bash
# Build and start the dev container
docker compose -f docker-compose.dev.yml up -d --build
`docker-compose.dev.yml` extends the production stack (`docker-compose.yml`, app and scheduler): the checkout mounted at `/app`, Octane reloading on PHP changes, and a Vite dev server with HMR. `.env` selects it through `COMPOSE_FILE`, so plain `docker compose` commands work.
# View logs (including Vite output)
docker compose -f docker-compose.dev.yml logs -f
```bash
cp .env.example .env
# Set APP_KEY (composer setup generates one) and the values for your setup (below)
# Build and start the app, the scheduler and Vite
docker compose up -d --build
# View logs
docker compose logs -f
```
The app is available at `http://localhost:8000` with Vite HMR on port `5173`.
With [OrbStack](https://orbstack.dev), no ports are published: set these in `.env` and open `https://app.sealshare.orb.local`. Uploads need HTTPS or `localhost`, because browsers only encrypt files there.
```dotenv
COMPOSE_FILE=docker-compose.dev.yml
APP_URL=https://app.sealshare.orb.local
VITE_DEV_SERVER_URL=https://vite.sealshare.orb.local
```
Without OrbStack, publish the ports on `127.0.0.1` and open `http://localhost:8000` (change the ports with `APP_PORT` and `VITE_PORT`):
```dotenv
COMPOSE_FILE=docker-compose.dev.yml:docker-compose.ports.yml
APP_URL=http://localhost:8000
```
The containers read `.env` when they are created: run `docker compose up -d` again after changing it.
## Installation — Production
@@ -56,13 +89,13 @@ The app is available at `http://localhost:8000` with Vite HMR on port `5173`.
```bash
mkdir sealshare && cd sealshare
curl -O https://raw.githubusercontent.com/surtic86/SealShare/main/docker-compose.example.yml
curl -O https://gitea.nonameweb.ch/noNameWEB/SealShare/raw/branch/main/docker-compose.example.yml
cp docker-compose.example.yml docker-compose.yml
# Generate an app key and paste it into docker-compose.yml
docker run --rm ghcr.io/surtic86/sealshare:latest php artisan key:generate --show
docker run --rm gitea.nonameweb.ch/nonameweb/sealshare:latest php artisan key:generate --show
# Edit docker-compose.yml — set APP_KEY, APP_URL, and SERVER_NAME
# Edit docker-compose.yml — set APP_KEY and APP_URL, and choose how HTTPS is served (below)
# Then start:
docker compose up -d
```
@@ -75,21 +108,39 @@ Migrations run automatically on startup. Open your configured domain — the Set
|----------|----------|-------------|
| `APP_KEY` | Yes | Laravel encryption key |
| `APP_URL` | Yes | Full URL (e.g. `https://share.example.com`) |
| `SERVER_NAME` | Yes | Domain for auto-TLS (e.g. `share.example.com`) |
| `AUTO_HTTPS` | No | `true` to fetch a Let's Encrypt certificate for `SERVER_NAME` and serve HTTPS on port 443 (port 80 redirects); default `false`, plain HTTP on port 80 for a reverse proxy |
| `SERVER_NAME` | With `AUTO_HTTPS` | The domain to fetch the certificate for (e.g. `share.example.com`) |
| `UPLOAD_CHUNK_SIZE_MB` | No | Size of each encrypted chunk the browser sends; default `16` |
**HTTPS is required for uploads.** Files are encrypted in the uploader's browser with WebCrypto, which browsers only offer over HTTPS or on `localhost`; over plain HTTP the upload page says so and takes no files (downloads keep working). Either set `AUTO_HTTPS: "true"` with `SERVER_NAME` — ports 80 and 443 must be reachable from the internet — or put a reverse proxy that terminates TLS in front of port 80.
**Volumes:**
| Volume | Path | Purpose |
|--------|------|---------|
| `sealshare_storage` | `/app/storage/app` | Encrypted uploaded files |
| `sealshare_database` | `/app/database` | SQLite database |
| `sealshare_database` | `/app/database/sqlite` | SQLite database (`DB_DATABASE: /app/database/sqlite/database.sqlite`) |
| `caddy_data` | `/data` | TLS certificates |
| `caddy_config` | `/config` | Caddy configuration |
A `docker-compose.yml` from before 2.2.0 mounts `sealshare_database` at `/app/database`, which also hides the image's migrations; the container adds the ones the volume is missing on startup, so it keeps working. To move to the layout above, mount the same volume at `/app/database/sqlite` and set `DB_DATABASE: /app/database/sqlite/database.sqlite` in both services — the existing database is at that path then, and nothing is lost.
**Large files:**
Files go up in chunks of `UPLOAD_CHUNK_SIZE_MB`, one request each, so PHP's upload limits and a proxy's request timeout do not limit a file's size. What does:
| Limit | Where | Default |
|-------|-------|---------|
| Max file size / Max size per share | Admin → Settings | 100 MB / 2 GB |
| Storage quota | Admin → Settings | 20 GB — files still uploading count towards it |
| `UPLOAD_CHUNK_SIZE_MB` | Environment | `16` |
Behind a reverse proxy, its request body limit must be a little larger than a chunk (nginx: `client_max_body_size 32m;`), and `proxy_request_buffering off;` keeps nginx from writing each chunk to its own temporary files. `PHP_UPLOAD_MAX_FILESIZE` / `PHP_POST_MAX_SIZE` (default `64M`) only apply to the admin's logo upload. An upload no chunk reached for 4 hours is deleted by the hourly cleanup.
### Manual (without Docker)
```bash
git clone https://github.com/surtic86/SealShare.git
git clone https://gitea.nonameweb.ch/noNameWEB/SealShare.git
cd SealShare
composer install --no-dev --optimize-autoloader
@@ -126,3 +177,5 @@ Add the scheduler to your crontab:
## License
This project is open-source software licensed under the [MIT License](LICENSE).
Generated passphrases draw from the [EFF Large Wordlist](https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases) by the Electronic Frontier Foundation, licensed under [CC BY 3.0 US](https://creativecommons.org/licenses/by/3.0/us/) (`resources/wordlists/eff-large-wordlist.txt`, without its four hyphenated words).
-33
View File
@@ -1,33 +0,0 @@
<?php
namespace App\Actions\Fortify;
use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules, ProfileValidationRules;
/**
* Validate and create a newly registered user.
*
* @param array<string, string> $input
*/
public function create(array $input): User
{
Validator::make($input, [
...$this->profileRules(),
'password' => $this->passwordRules(),
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => $input['password'],
]);
}
}
+3 -5
View File
@@ -12,7 +12,7 @@ trait ProfileValidationRules
*
* @return array<string, array<int, \Illuminate\Contracts\Validation\Rule|array<mixed>|string>>
*/
protected function profileRules(?int $userId = null): array
protected function profileRules(int $userId): array
{
return [
'name' => $this->nameRules(),
@@ -35,16 +35,14 @@ trait ProfileValidationRules
*
* @return array<int, \Illuminate\Contracts\Validation\Rule|array<mixed>|string>
*/
protected function emailRules(?int $userId = null): array
protected function emailRules(int $userId): array
{
return [
'required',
'string',
'email',
'max:255',
$userId === null
? Rule::unique(User::class)
: Rule::unique(User::class)->ignore($userId),
Rule::unique(User::class)->ignore($userId),
];
}
}
+59 -5
View File
@@ -5,30 +5,84 @@ namespace App\Console\Commands;
use App\Models\Share;
use App\Services\ShareService;
use Illuminate\Console\Command;
use Livewire\Features\SupportFileUploads\FileUploadConfiguration;
class CleanupExpiredShares extends Command
{
/**
* How long an upload or a temporary upload file may sit untouched before it is deleted.
*/
private const ABANDONED_AFTER_HOURS = 4;
/**
* How long a share at its download limit is kept after its last download, so that downloads its
* last recipients started can finish: a ZIP opens each file only when it reaches it.
*/
private const DELETE_AFTER_LIMIT_HOURS = 24;
protected $signature = 'shares:cleanup';
protected $description = 'Delete expired shares and shares that have reached their download limit';
protected $description = 'Delete expired shares, shares that have reached their download limit, abandoned uploads and old temporary uploads';
public function handle(ShareService $shareService): int
{
$expiredShares = Share::query()
->where(function ($query): void {
$query->where('expires_at', '<', now())
->orWhereRaw('max_downloads IS NOT NULL AND download_count >= max_downloads');
->orWhere(function ($query): void {
$query->whereNotNull('max_downloads')
->whereColumn('download_count', '>=', 'max_downloads')
->where(function ($query): void {
$query->whereNull('last_downloaded_at')
->orWhere('last_downloaded_at', '<', now()->subHours(self::DELETE_AFTER_LIMIT_HOURS));
});
});
})
->get();
$count = $expiredShares->count();
foreach ($expiredShares as $share) {
$shareService->deleteShare($share);
}
$this->info("Cleaned up {$count} expired share(s).");
$this->info("Cleaned up {$expiredShares->count()} expired share(s).");
// A page that stopped sending chunks: closed, crashed or left behind.
$abandonedUploads = Share::query()
->whereNull('completed_at')
->where('updated_at', '<', now()->subHours(self::ABANDONED_AFTER_HOURS))
->get();
foreach ($abandonedUploads as $share) {
$shareService->deleteShare($share);
}
$this->info("Cleaned up {$abandonedUploads->count()} abandoned upload(s).");
$this->info('Cleaned up '.$this->deleteOldTemporaryUploads().' temporary upload file(s).');
return self::SUCCESS;
}
/**
* Delete Livewire's temporary uploads past the same age: the admin logo's, and the unencrypted
* copies uploads left there before files were encrypted in the browser.
*/
private function deleteOldTemporaryUploads(): int
{
if (FileUploadConfiguration::isUsingS3()) {
return 0;
}
$storage = FileUploadConfiguration::storage();
$cutoff = now()->subHours(self::ABANDONED_AFTER_HOURS)->getTimestamp();
$deleted = 0;
foreach ($storage->allFiles(FileUploadConfiguration::path()) as $path) {
if ($storage->exists($path) && $storage->lastModified($path) < $cutoff) {
$storage->delete($path);
$deleted++;
}
}
return $deleted;
}
}
+63 -30
View File
@@ -6,11 +6,13 @@ use App\Models\Share;
use App\Models\ShareFile;
use App\Services\FileEncryptionService;
use App\Services\ShareService;
use GuzzleHttp\Psr7\PumpStream;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\StreamedResponse;
use ZipArchive;
use ZipStream\CompressionMethod;
use ZipStream\ZipStream;
class DownloadController extends Controller
{
@@ -20,53 +22,68 @@ class DownloadController extends Controller
) {}
/**
* Download all files as a ZIP archive.
* Download all files as a ZIP archive, streamed file by file as it is decrypted: stored without
* compression, with ZIP64 for files over 4 GB, and never held in memory or written to disk.
*/
public function download(Share $share): BinaryFileResponse
public function download(Request $request, Share $share): StreamedResponse
{
abort_if($share->isExpired() || $share->hasReachedDownloadLimit(), 404);
abort_if(! $share->isCompleted() || $share->isExpired(), 404);
$share->load('files');
$key = $this->resolveDecryptionKey($share);
$tempPath = tempnam(sys_get_temp_dir(), 'sealshare_');
// Counted before the body streams: the session is saved by then.
abort_unless($this->shareService->claimDownload($share, $request->session()), 404);
$zip = new ZipArchive;
$zip->open($tempPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
return new StreamedResponse(function () use ($share, $key): void {
$zip = new ZipStream(
defaultCompressionMethod: CompressionMethod::STORE,
defaultEnableZeroHeader: true,
sendHttpHeaders: false,
flushOutput: true,
);
foreach ($share->files as $file) {
$encryptedPath = Storage::disk('shares')->path($share->token.'/'.basename($file->stored_path));
$content = $this->encryptionService->decryptFile($encryptedPath, $key);
foreach ($share->files as $file) {
$chunks = $this->encryptionService->decryptedChunks(
Storage::disk('shares')->path($share->token.'/'.basename($file->stored_path)),
$key,
);
$filename = $file->relative_path ?: $file->original_name;
$filename = str_replace('\\', '/', $filename);
$zip->addFileFromPsr7Stream(fileName: $this->archiveName($file), stream: new PumpStream(function () use ($chunks): string|false {
while ($chunks->valid() && $chunks->current() === '') {
$chunks->next();
}
if (str_starts_with($filename, '/') || str_contains($filename, '..')) {
$filename = basename($filename);
if (! $chunks->valid()) {
return false;
}
$chunk = $chunks->current();
$chunks->next();
return $chunk;
}));
}
$zip->addFromString($filename, $content);
}
$zip->close();
$this->shareService->recordDownload($share);
return response()->download($tempPath, 'share-'.$share->token.'.zip', [
$zip->finish();
}, 200, [
'Content-Type' => 'application/zip',
])->deleteFileAfterSend(true);
'Content-Disposition' => HeaderUtils::makeDisposition('attachment', 'share-'.$share->token.'.zip'),
]);
}
/**
* Download a single file.
*/
public function downloadFile(Share $share, ShareFile $shareFile): StreamedResponse
public function downloadFile(Request $request, Share $share, ShareFile $shareFile): StreamedResponse
{
abort_if($share->isExpired() || $share->hasReachedDownloadLimit(), 404);
abort_if(! $share->isCompleted() || $share->isExpired(), 404);
abort_if($shareFile->share_id !== $share->id, 404);
$key = $this->resolveDecryptionKey($share);
abort_unless($this->shareService->claimDownload($share, $request->session()), 404);
$encryptedPath = Storage::disk('shares')->path($share->token.'/'.basename($shareFile->stored_path));
$mimeType = $shareFile->mime_type ?? 'application/octet-stream';
@@ -83,13 +100,29 @@ class DownloadController extends Controller
$headers['Content-Length'] = $shareFile->file_size;
}
return new StreamedResponse(function () use ($encryptedPath, $key, $share): void {
$this->encryptionService->streamDecryptedFile($encryptedPath, $key);
$this->shareService->recordDownload($share);
return new StreamedResponse(function () use ($encryptedPath, $key): void {
foreach ($this->encryptionService->decryptedChunks($encryptedPath, $key) as $chunk) {
echo $chunk;
flush();
}
}, 200, $headers);
}
/**
* A file's path inside the archive: its folder path when it came from a dropped folder, never
* one that could reach outside the archive.
*/
private function archiveName(ShareFile $file): string
{
$filename = str_replace('\\', '/', $file->relative_path ?: $file->original_name);
if (str_starts_with($filename, '/') || str_contains($filename, '..')) {
return basename($filename);
}
return $filename;
}
/**
* Resolve the decryption key from session or share.
*/
@@ -0,0 +1,45 @@
<?php
namespace App\Http\Controllers;
use App\Models\ShareFile;
use App\Services\ShareService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use InvalidArgumentException;
class UploadChunkController extends Controller
{
public function __construct(
private ShareService $shareService,
) {}
/**
* Store one encrypted chunk of a file the uploader's page registered.
*
* Only the session that started the pending share may add to it. A chunk the server already
* has is acknowledged without being written again; one that skips ahead gets a 409 with the
* number of chunks stored, so the browser can continue from there.
*/
public function store(Request $request, ShareFile $shareFile, int $index): JsonResponse
{
$share = $shareFile->share;
abort_if($share->isCompleted() || ! in_array($share->token, $request->session()->get('pending_shares', []), true), 404);
if ($index !== $shareFile->uploaded_chunks) {
return response()->json(
['uploaded_chunks' => $shareFile->uploaded_chunks],
$index < $shareFile->uploaded_chunks ? 200 : 409,
);
}
try {
$uploadedChunks = $this->shareService->storeChunk($shareFile, $index, $request->getContent());
} catch (InvalidArgumentException) {
abort(422, 'The chunk is invalid.');
}
return response()->json(['uploaded_chunks' => $uploadedChunks]);
}
}
+38 -17
View File
@@ -14,49 +14,70 @@ class AdminDashboard extends Component
{
use WithPagination;
/** @var array<string, string> */
public array $sortBy = ['column' => 'created_at', 'direction' => 'desc'];
/**
* The orders the shares list offers, each a column and a direction.
*
* @var array<string, array{0: string, 1: string}>
*/
public const SORTS = [
'newest' => ['created_at', 'desc'],
'oldest' => ['created_at', 'asc'],
'expiring' => ['expires_at', 'asc'],
'largest' => ['total_size', 'desc'],
'most-downloaded' => ['download_count', 'desc'],
'most-files' => ['files_count', 'desc'],
];
public string $sort = 'newest';
/** The share the delete dialog is asking about, while it is open. */
public ?int $deletingShareId = null;
public function deleteShare(int $shareId, ShareService $shareService): void
{
$share = Share::query()->findOrFail($shareId);
$shareService->deleteShare($share);
$this->deletingShareId = null;
}
/**
* @return array<string, array<string, string|bool>>
* A new order starts again from the first page.
*/
public function headers(): array
public function updatedSort(): void
{
return [
['key' => 'token', 'label' => __('Token')],
['key' => 'files_count', 'label' => __('Files')],
['key' => 'total_size', 'label' => __('Size')],
['key' => 'download_count', 'label' => __('Downloads')],
['key' => 'expires_at', 'label' => __('Expires')],
['key' => 'created_at', 'label' => __('Created')],
];
$this->resetPage();
}
public function render(): mixed
{
$shareService = app(ShareService::class);
// The sort comes from the browser: only a known order reaches the query.
[$column, $direction] = self::SORTS[$this->sort] ?? self::SORTS['newest'];
// Shares whose files are still being uploaded are not shares yet; their bytes do count as used space.
$shares = Share::query()
->whereNotNull('completed_at')
->withCount('files')
->orderBy($this->sortBy['column'], $this->sortBy['direction'])
// Shares that never expire come after every share that does, whichever way expiry is sorted.
->when($column === 'expires_at', fn ($query) => $query->orderByRaw('expires_at is null'))
->orderBy($column, $direction)
->orderByDesc('id')
->paginate(15);
return view('livewire.admin.admin-dashboard', [
'shares' => $shares,
'totalShares' => Share::query()->count(),
'activeShares' => Share::query()->where(function ($q) {
'totalShares' => Share::query()->whereNotNull('completed_at')->count(),
'activeShares' => Share::query()->whereNotNull('completed_at')->where(function ($q) {
$q->whereNull('expires_at')->orWhere('expires_at', '>', now());
})->where(function ($q) {
$q->whereNull('max_downloads')->orWhereColumn('download_count', '<', 'max_downloads');
})->count(),
'totalFiles' => ShareFile::query()->count(),
'totalFiles' => ShareFile::query()->whereHas('share', fn ($query) => $query->whereNotNull('completed_at'))->count(),
'usedSpace' => $shareService->getTotalUsedSpace(),
'maxQuota' => $shareService->getMaxStorageQuota(),
'headers' => $this->headers(),
'version' => config('app.version'),
]);
}
}
+135 -33
View File
@@ -3,17 +3,27 @@
namespace App\Livewire\Admin;
use App\Models\Setting;
use App\Models\Share;
use App\Services\PasswordGeneratorService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithFileUploads;
use NoNameWeb\LivewireMaterial\Concerns\Toasts;
use NoNameWeb\LivewireMaterial\Support\Scheme;
#[Layout('layouts.app')]
class AdminSettings extends Component
{
use Toasts;
use WithFileUploads;
/** The colour profile every page, mail and error page wears (config/livewire-material.php). */
public string $colorProfile = '';
public string $systemPassword = '';
public string $defaultExpiration = '';
@@ -28,68 +38,79 @@ class AdminSettings extends Component
public bool $allowNeverExpire = false;
/** How the upload page offers generated share passwords: `off`, `button` or `prefill`. */
public string $passwordGeneratorMode = 'button';
/** `characters` or `passphrase`. */
public string $passwordGeneratorType = 'characters';
public int $passwordLength = 20;
/** @var list<string> */
public array $passwordCharacterSets = [];
public bool $passwordAvoidAmbiguous = true;
public int $passphraseWords = 6;
public string $passphraseSeparator = 'hyphen';
public string $siteTitle = '';
public string $siteDescription = '';
public $siteLogo;
/** Whether the "Remove the logo?" dialog is open. */
public bool $confirmingLogoRemoval = false;
/** Whether the "Remove the system password?" dialog is open. */
public bool $confirmingPasswordRemoval = false;
public function mount(): void
{
$this->colorProfile = Scheme::profile() ?? '';
$this->defaultExpiration = Setting::get('default_expiration', '') ?? '';
$this->maxFileSize = min(
(int) Setting::get('max_file_size', 100 * 1024 * 1024) / (1024 * 1024),
self::phpMaxUploadMb(),
);
$this->maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024) / (1024 * 1024);
$this->maxStorageQuota = (int) Setting::get('max_storage_quota', 20 * 1024 * 1024 * 1024) / (1024 * 1024 * 1024);
$this->maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
$this->maxSizePerShare = (int) Setting::get('max_size_per_share', 2 * 1024 * 1024 * 1024) / (1024 * 1024 * 1024);
$this->allowNeverExpire = (bool) Setting::get('allow_never_expire', false);
$this->siteTitle = Setting::get('site_title', '') ?? '';
$this->siteDescription = Setting::get('site_description', '') ?? '';
}
public static function phpMaxUploadMb(): int
{
$parse = function (string $value): int {
$value = trim($value);
$last = strtolower($value[strlen($value) - 1]);
$num = (int) $value;
return match ($last) {
'g' => $num * 1024,
'm' => $num,
'k' => max(1, (int) ($num / 1024)),
default => max(1, (int) ($num / (1024 * 1024))),
};
};
$upload = $parse(ini_get('upload_max_filesize') ?: '2M');
$post = $parse(ini_get('post_max_size') ?: '8M');
return min($upload, $post);
$passwordOptions = app(PasswordGeneratorService::class)->options();
$this->passwordGeneratorMode = $passwordOptions['mode'];
$this->passwordGeneratorType = $passwordOptions['type'];
$this->passwordLength = $passwordOptions['length'];
$this->passwordCharacterSets = $passwordOptions['characterSets'];
$this->passwordAvoidAmbiguous = $passwordOptions['avoidAmbiguous'];
$this->passphraseWords = $passwordOptions['words'];
$this->passphraseSeparator = $passwordOptions['separator'];
}
public function saveSettings(): void
{
$phpMaxMb = self::phpMaxUploadMb();
$this->validate([
'maxFileSize' => ['required', 'integer', 'min:1', 'max:'.$phpMaxMb],
$validated = $this->validate([
'colorProfile' => ['required', 'string', Rule::in(array_keys(Scheme::profiles()))],
'defaultExpiration' => ['nullable', 'string', Rule::in(array_keys(Share::EXPIRATIONS))],
'maxFileSize' => ['required', 'integer', 'min:1'],
'maxStorageQuota' => ['required', 'integer', 'min:1'],
'maxFilesPerShare' => ['required', 'integer', 'min:1'],
'maxSizePerShare' => ['required', 'integer', 'min:1'],
'siteTitle' => ['nullable', 'string', 'max:255'],
'siteDescription' => ['nullable', 'string', 'max:1000'],
'siteLogo' => ['nullable', 'file', 'mimes:png,jpg,jpeg,gif,webp', 'max:2048'],
...$this->passwordGeneratorRules(),
], [
'maxFileSize.max' => __('Cannot exceed the PHP limit of :max MB. Increase upload_max_filesize and post_max_size in your PHP configuration.', ['max' => $phpMaxMb]),
'passwordCharacterSets.required' => __('Choose at least one kind of character.'),
]);
if ($this->systemPassword) {
Setting::set('system_password', Hash::make($this->systemPassword));
}
Setting::set('color_profile', $this->colorProfile);
Setting::set('default_expiration', $this->defaultExpiration ?: null);
Setting::set('max_file_size', $this->maxFileSize * 1024 * 1024);
Setting::set('max_storage_quota', $this->maxStorageQuota * 1024 * 1024 * 1024);
@@ -100,6 +121,8 @@ class AdminSettings extends Component
Setting::set('site_title', $this->siteTitle ?: null);
Setting::set('site_description', $this->siteDescription ?: null);
$this->savePasswordGeneratorSettings($validated);
if ($this->siteLogo && is_object($this->siteLogo)) {
$existingLogo = Setting::get('site_logo');
if ($existingLogo) {
@@ -113,7 +136,78 @@ class AdminSettings extends Component
$this->systemPassword = '';
session()->flash('message', __('Settings saved successfully.'));
$this->success(__('Settings saved successfully.'));
}
/**
* The generator's rules. A field the chosen mode or type hides is excluded, so it never blocks
* saving and keeps the value saved before.
*
* @return array<string, array<int, mixed>>
*/
protected function passwordGeneratorRules(): array
{
$characters = ['exclude_if:passwordGeneratorMode,off', 'exclude_unless:passwordGeneratorType,characters'];
$passphrase = ['exclude_if:passwordGeneratorMode,off', 'exclude_unless:passwordGeneratorType,passphrase'];
return [
'passwordGeneratorMode' => ['required', 'string', Rule::in(PasswordGeneratorService::MODES)],
'passwordGeneratorType' => ['exclude_if:passwordGeneratorMode,off', 'required', 'string', Rule::in(PasswordGeneratorService::TYPES)],
'passwordLength' => [...$characters, 'required', 'integer', 'min:'.PasswordGeneratorService::MIN_LENGTH, 'max:'.PasswordGeneratorService::MAX_LENGTH],
'passwordCharacterSets' => [...$characters, 'required', 'array'],
'passwordCharacterSets.*' => [...$characters, 'string', Rule::in(array_keys(PasswordGeneratorService::CHARACTER_SETS))],
'passwordAvoidAmbiguous' => [...$characters, 'boolean'],
'passphraseWords' => [...$passphrase, 'required', 'integer', 'min:'.PasswordGeneratorService::MIN_WORDS, 'max:'.PasswordGeneratorService::MAX_WORDS],
'passphraseSeparator' => [...$passphrase, 'required', 'string', Rule::in(array_keys(PasswordGeneratorService::SEPARATORS))],
];
}
/**
* Store the generator settings that passed validation; excluded ones keep their saved value.
*
* @param array<string, mixed> $validated
*/
protected function savePasswordGeneratorSettings(array $validated): void
{
Setting::set('password_generator_mode', $validated['passwordGeneratorMode']);
if (array_key_exists('passwordGeneratorType', $validated)) {
Setting::set('password_generator_type', $validated['passwordGeneratorType']);
}
if (array_key_exists('passwordLength', $validated)) {
Setting::set('password_generator_length', $validated['passwordLength']);
Setting::set('password_generator_character_sets', implode(',', $validated['passwordCharacterSets']));
Setting::set('password_generator_avoid_ambiguous', $validated['passwordAvoidAmbiguous'] ? '1' : '0');
}
if (array_key_exists('passphraseWords', $validated)) {
Setting::set('password_generator_words', $validated['passphraseWords']);
Setting::set('password_generator_separator', $validated['passphraseSeparator']);
}
}
/**
* The form's generator options while they are valid, for the example; `null` otherwise.
*
* @return array{type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}|null
*/
protected function passwordPreviewOptions(): ?array
{
$values = $this->only(['passwordGeneratorMode', 'passwordGeneratorType', 'passwordLength', 'passwordCharacterSets', 'passwordAvoidAmbiguous', 'passphraseWords', 'passphraseSeparator']);
if ($this->passwordGeneratorMode === 'off' || Validator::make($values, $this->passwordGeneratorRules())->fails()) {
return null;
}
return [
'type' => $this->passwordGeneratorType,
'length' => $this->passwordLength,
'characterSets' => array_values($this->passwordCharacterSets),
'avoidAmbiguous' => $this->passwordAvoidAmbiguous,
'words' => $this->passphraseWords,
'separator' => $this->passphraseSeparator,
];
}
public function removeLogo(): void
@@ -125,22 +219,30 @@ class AdminSettings extends Component
Setting::set('site_logo', null);
}
session()->flash('message', __('Logo removed.'));
$this->confirmingLogoRemoval = false;
$this->success(__('Logo removed.'));
}
public function clearSystemPassword(): void
{
Setting::set('system_password', null);
session()->flash('message', __('System password cleared.'));
$this->confirmingPasswordRemoval = false;
$this->success(__('System password cleared.'));
}
public function render(): mixed
{
$passwordGenerator = app(PasswordGeneratorService::class);
$passwordPreviewOptions = $this->passwordPreviewOptions();
return view('livewire.admin.admin-settings', [
'hasSystemPassword' => (bool) Setting::get('system_password'),
'currentLogo' => Setting::get('site_logo'),
'phpMaxUploadMb' => self::phpMaxUploadMb(),
'passwordExample' => $passwordPreviewOptions ? $passwordGenerator->generate($passwordPreviewOptions) : null,
'passwordEntropy' => $passwordPreviewOptions ? $passwordGenerator->entropyBits($passwordPreviewOptions) : null,
]);
}
}
+139 -124
View File
@@ -3,23 +3,29 @@
namespace App\Livewire;
use App\Models\Setting;
use App\Models\Share;
use App\Services\PasswordGeneratorService;
use App\Services\ShareService;
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
/**
* The upload page. The browser encrypts each file chunk by chunk and sends the chunks to
* UploadChunkController (resources/js/share-uploader.js); this component registers the files
* into a pending share, lists them and completes the share with its options.
*/
#[Layout('layouts.app')]
class FileUploader extends Component
{
use WithFileUploads;
/** @var array<int, TemporaryUploadedFile> */
public array $files = [];
/** @var array<int, string|null> */
public array $relativePaths = [];
/** The pending share this page uploads into: created with the first file, one per page load. */
#[Locked]
public ?string $pendingToken = null;
public bool $usePassword = false;
@@ -36,158 +42,167 @@ class FileUploader extends Component
$this->expiration = Setting::get('default_expiration', '7d') ?: '7d';
}
public function _uploadErrored($name, $errorsInJson, $isMultiple): void
/**
* Register the files a visitor chose and hand the browser what it encrypts and sends them
* with. A file an admin limit refuses gets `null` in its place and the reason under `files`.
*
* @param array<int, array{name?: mixed, size?: mixed, path?: mixed}> $files
* @return array<int, array{id: int, url: string, key: string, noncePrefix: string, chunkSize: int, chunkCount: int}|null>
*/
public function registerFiles(array $files, ShareService $shareService): array
{
$this->dispatch('upload:errored', name: $name)->self();
$maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024);
$maxFileSizeMb = (int) ($maxFileSize / (1024 * 1024));
if (! is_null($errorsInJson)) {
$errors = json_decode($errorsInJson, true)['errors'] ?? null;
if ($errors) {
$messages = [];
foreach ($errors as $messages_array) {
foreach ((array) $messages_array as $msg) {
$messages[] = $msg;
}
}
throw ValidationException::withMessages([
'files' => __('Upload failed: file exceeds the maximum size of :max MB.', ['max' => $maxFileSizeMb]),
]);
}
}
throw ValidationException::withMessages([
'files' => __('Upload failed: file may be too large (max :max MB) or the connection was interrupted.', ['max' => $maxFileSizeMb]),
]);
}
public function updatedFiles(): void
{
$maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024);
$maxFileSizeMb = $maxFileSize / (1024 * 1024);
$maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
$this->resetErrorBag('files');
if (count($this->files) > $maxFilesPerShare) {
$this->addError('files', __('Too many files. Maximum :max files allowed per share.', ['max' => $maxFilesPerShare]));
$targets = [];
foreach ($files as $file) {
try {
$shareFile = $shareService->registerFile(
$this->pendingShare(),
(string) ($file['name'] ?? ''),
(int) ($file['size'] ?? -1),
isset($file['path']) ? (string) $file['path'] : null,
);
} catch (ValidationException $e) {
if (! $this->getErrorBag()->has('files')) {
$this->addError('files', $e->errors()['files'][0]);
}
$targets[] = null;
continue;
}
if ($this->pendingToken !== $shareFile->share->token) {
$this->pendingToken = $shareFile->share->token;
session()->push('pending_shares', $this->pendingToken);
}
$header = $shareService->readHeader($shareFile);
$targets[] = [
'id' => $shareFile->id,
'url' => Str::beforeLast(route('upload.chunk', ['shareFile' => $shareFile, 'index' => 0]), '/'),
'key' => $shareFile->share->encryption_key,
'noncePrefix' => bin2hex($header['noncePrefix']),
'chunkSize' => $header['chunkSize'],
'chunkCount' => $header['chunkCount'],
];
}
return $targets;
}
/**
* Take files out of the pending share, whether or not their upload finished.
*
* @param array<int, mixed> $fileIds
*/
public function removeFiles(array $fileIds, ShareService $shareService): void
{
$files = $this->pendingShare()?->files()->whereIn('id', array_map('intval', $fileIds))->get() ?? [];
foreach ($files as $file) {
$shareService->removeFile($file);
}
$this->resetErrorBag('files');
}
/**
* Fill in a generated password as protection is switched on, when the admin chose "Prefilled".
* A password already in the field stays.
*/
public function updatedUsePassword(bool $value): void
{
$passwordGenerator = app(PasswordGeneratorService::class);
if ($value && $this->password === '' && $passwordGenerator->mode() === 'prefill') {
$this->password = $passwordGenerator->generate();
}
}
public function generatePassword(PasswordGeneratorService $passwordGenerator): void
{
if ($passwordGenerator->mode() === 'off') {
return;
}
foreach ($this->files as $file) {
if ($file->getSize() > $maxFileSize) {
$this->addError('files', __('":name" is too large (:size MB). Maximum file size is :max MB.', [
'name' => $file->getClientOriginalName(),
'size' => round($file->getSize() / (1024 * 1024), 1),
'max' => (int) $maxFileSizeMb,
]));
return;
}
}
}
public function removeFile(int $index): void
{
unset($this->files[$index], $this->relativePaths[$index]);
$this->files = array_values($this->files);
$this->relativePaths = array_values($this->relativePaths);
$this->password = $passwordGenerator->generate();
$this->resetErrorBag('password');
}
public function createShare(ShareService $shareService): void
{
$maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
$maxSizePerShare = (int) Setting::get('max_size_per_share', 2 * 1024 * 1024 * 1024);
$maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024);
$rules = [];
$rules = [
'files' => ['required', 'array', 'min:1', 'max:'.$maxFilesPerShare],
'files.*' => ['required', 'file', 'max:'.($maxFileSize / 1024)],
];
$allowNeverExpire = (bool) Setting::get('allow_never_expire', false);
if (! $allowNeverExpire) {
$rules['expiration'] = ['required', 'string', 'in:1h,24h,48h,7d,14d,30d'];
if (! Setting::get('allow_never_expire', false)) {
$rules['expiration'] = ['required', 'string', Rule::in(array_keys(Share::EXPIRATIONS))];
}
if ($this->usePassword) {
$rules['password'] = ['required', 'string', 'min:8'];
}
$this->validate($rules, [
'expiration.required' => __('An expiration time is required.'),
'files.required' => __('Please select at least one file to upload.'),
'files.max' => __('Too many files. Maximum :max files allowed per share.'),
'files.*.max' => __('A file exceeds the maximum size of :max KB.'),
]);
if ($rules !== []) {
$this->validate($rules, [
'expiration.required' => __('An expiration time is required.'),
]);
}
if ($shareService->isStorageFull()) {
$this->addError('files', __('Storage is full. Please contact the administrator.'));
$pendingShare = $this->pendingShare();
if ($pendingShare === null) {
$this->addError('files', __('Please select at least one file to upload.'));
return;
}
$totalSize = collect($this->files)->sum(fn ($file) => $file->getSize());
if ($totalSize > $maxSizePerShare) {
$this->addError('files', __('Total file size exceeds the maximum allowed per share.'));
return;
}
$fileData = [];
foreach ($this->files as $index => $file) {
$relativePath = $this->relativePaths[$index] ?? null;
if ($relativePath !== null) {
$relativePath = str_replace('\\', '/', $relativePath);
if (str_starts_with($relativePath, '/') || str_contains($relativePath, '..')) {
$relativePath = null;
}
}
$fileData[] = [
'file' => $file,
'relativePath' => $relativePath,
];
}
$expiresAt = match ($this->expiration) {
'1h' => now()->addHour(),
'24h' => now()->addDay(),
'48h' => now()->addDays(2),
'7d' => now()->addWeek(),
'14d' => now()->addDays(14),
'30d' => now()->addMonth(),
default => null,
};
$share = $shareService->createShare($fileData, [
$share = $shareService->completeShare($pendingShare, [
'password' => $this->usePassword ? $this->password : null,
'expires_at' => $expiresAt,
'expires_at' => isset(Share::EXPIRATIONS[$this->expiration])
? now()->add(CarbonInterval::make(Share::EXPIRATIONS[$this->expiration]['interval']))
: null,
'max_downloads' => $this->maxDownloads ?: null,
]);
session()->put('pending_shares', array_values(array_diff(session('pending_shares', []), [$share->token])));
// The page the upload leads to offers the password once more, next to the link; it is
// never stored in the clear, so this flash is the only way it gets there.
if ($this->usePassword) {
session()->flash('share_password', [
'token' => $share->token,
'password' => Crypt::encryptString($this->password),
]);
}
$this->redirect(route('share.created', $share), navigate: true);
}
public function render(): mixed
{
$shareService = app(ShareService::class);
$pendingFiles = $this->pendingShare()?->files()->orderBy('id')->get() ?? collect();
return view('livewire.file-uploader', [
'pendingFiles' => $pendingFiles,
'allFilesUploaded' => $pendingFiles->isNotEmpty() && $pendingFiles->every(fn ($file): bool => $file->completed_at !== null),
'isStorageFull' => $shareService->isStorageFull(),
'siteTitle' => Setting::get('site_title'),
'siteDescription' => Setting::get('site_description'),
'siteLogo' => Setting::get('site_logo'),
'allowNeverExpire' => (bool) Setting::get('allow_never_expire', false),
'passwordGeneratorMode' => app(PasswordGeneratorService::class)->mode(),
]);
}
/**
* This page's pending share, while it is still pending and this session started it.
*/
private function pendingShare(): ?Share
{
if ($this->pendingToken === null || ! in_array($this->pendingToken, session('pending_shares', []), true)) {
return null;
}
return Share::query()->where('token', $this->pendingToken)->whereNull('completed_at')->first();
}
}
+1 -5
View File
@@ -2,7 +2,6 @@
namespace App\Livewire;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
@@ -10,7 +9,7 @@ use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;
#[Layout('layouts.auth')]
#[Layout('layouts.app')]
class SetupWizard extends Component
{
#[Validate('required|string|max:255')]
@@ -45,14 +44,11 @@ class SetupWizard extends Component
'name' => $this->name,
'email' => $this->email,
'password' => Hash::make($this->password),
'email_verified_at' => now(),
]);
$user->is_admin = true;
$user->save();
Setting::set('setup_complete', 'true');
Auth::login($user);
$this->redirect(route('admin.dashboard'), navigate: true);
+23 -1
View File
@@ -2,8 +2,12 @@
namespace App\Livewire;
use App\Models\Setting;
use App\Models\Share;
use App\Services\QrCodeService;
use Illuminate\Support\Facades\Crypt;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;
#[Layout('layouts.app')]
@@ -11,13 +15,31 @@ class ShareCreated extends Component
{
public Share $share;
/** The share's password, offered once to the uploader who just set it; `null` on any other visit. */
#[Locked]
public ?string $password = null;
public function mount(Share $share): void
{
abort_unless($share->isCompleted(), 404);
$this->share = $share;
$flashedPassword = session('share_password');
if (is_array($flashedPassword) && ($flashedPassword['token'] ?? null) === $share->token) {
$this->password = Crypt::decryptString($flashedPassword['password']);
}
}
public function render(): mixed
{
return view('livewire.share-created');
$shareUrl = route('share.download', $this->share);
return view('livewire.share-created', [
'shareUrl' => $shareUrl,
'qrCodeSvg' => app(QrCodeService::class)->svg($shareUrl),
'siteTitle' => Setting::get('site_title') ?: config('app.name'),
]);
}
}
+11 -13
View File
@@ -2,9 +2,9 @@
namespace App\Livewire;
use App\Models\Setting;
use App\Models\Share;
use App\Services\ShareService;
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
@@ -20,21 +20,17 @@ class ShareDownload extends Component
#[Validate('required|string')]
public string $password = '';
public function mount(Share $share): void
public function mount(Share $share, ShareService $shareService): void
{
$this->share = $share->load('files');
if ($share->isExpired() || $share->hasReachedDownloadLimit()) {
// A share at its download limit stays open for the recipient who took its last download.
if (! $share->isCompleted() || $share->isExpired()
|| ($share->hasReachedDownloadLimit() && $shareService->downloadWindowEndsAt($share, session()->driver()) === null)) {
abort(404);
}
if (! $share->isPasswordProtected()) {
$this->authenticated = true;
}
if ($share->isPasswordProtected() && session('share_key_'.$share->token)) {
$this->authenticated = true;
}
$this->authenticated = ! $share->isPasswordProtected() || (bool) session('share_key_'.$share->token);
}
public function verifyPassword(ShareService $shareService): void
@@ -66,10 +62,12 @@ class ShareDownload extends Component
public function render(): mixed
{
$shareService = app(ShareService::class);
return view('livewire.share-download', [
'siteTitle' => Setting::get('site_title'),
'siteDescription' => Setting::get('site_description'),
'siteLogo' => Setting::get('site_logo'),
'downloadWindowEndsAt' => $shareService->downloadWindowEndsAt($this->share, session()->driver()),
'remainingDownloads' => $this->share->max_downloads ? max($this->share->max_downloads - $this->share->download_count, 0) : null,
'downloadWindow' => CarbonInterval::minutes(ShareService::DOWNLOAD_WINDOW_MINUTES)->cascade()->forHumans(),
]);
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;
#[Layout('layouts.auth')]
#[Layout('layouts.app')]
class SystemPasswordPrompt extends Component
{
#[Validate('required|string')]
+28
View File
@@ -10,15 +10,32 @@ class Share extends Model
{
use HasFactory;
/**
* The expiration times an uploader can choose, by the id the upload form and Admin settings
* store: each one's label and how long a share lasts with it.
*
* @var array<string, array{label: string, interval: string}>
*/
public const EXPIRATIONS = [
'1h' => ['label' => '1 Hour', 'interval' => '1 hour'],
'24h' => ['label' => '24 Hours', 'interval' => '1 day'],
'48h' => ['label' => '48 Hours', 'interval' => '2 days'],
'7d' => ['label' => '7 Days', 'interval' => '7 days'],
'14d' => ['label' => '14 Days', 'interval' => '14 days'],
'30d' => ['label' => '30 Days', 'interval' => '30 days'],
];
protected $fillable = [
'token',
'password',
'encryption_key',
'encryption_salt',
'wrapped_key',
'expires_at',
'max_downloads',
'download_count',
'total_size',
'completed_at',
];
/**
@@ -30,8 +47,10 @@ class Share extends Model
'expires_at' => 'datetime',
'max_downloads' => 'integer',
'download_count' => 'integer',
'last_downloaded_at' => 'datetime',
'total_size' => 'integer',
'encryption_key' => 'encrypted',
'completed_at' => 'datetime',
];
}
@@ -43,6 +62,15 @@ class Share extends Model
return $this->hasMany(ShareFile::class);
}
/**
* Whether the share was created: until then its files are still being uploaded and nobody
* but the uploader's page may reach it.
*/
public function isCompleted(): bool
{
return $this->completed_at !== null;
}
public function isExpired(): bool
{
return $this->expires_at && $this->expires_at->isPast();
+4
View File
@@ -17,6 +17,8 @@ class ShareFile extends Model
'stored_path',
'file_size',
'mime_type',
'uploaded_chunks',
'completed_at',
];
/**
@@ -26,6 +28,8 @@ class ShareFile extends Model
{
return [
'file_size' => 'integer',
'uploaded_chunks' => 'integer',
'completed_at' => 'datetime',
];
}
-14
View File
@@ -2,12 +2,10 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Fortify\TwoFactorAuthenticatable;
class User extends Authenticatable
@@ -51,16 +49,4 @@ class User extends Authenticatable
'is_admin' => 'boolean',
];
}
/**
* Get the user's initials
*/
public function initials(): string
{
return Str::of($this->name)
->explode(' ')
->take(2)
->map(fn ($word) => Str::substr($word, 0, 1))
->implode('');
}
}
+6 -8
View File
@@ -2,28 +2,26 @@
namespace App\Providers;
use App\Models\Setting;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use NoNameWeb\LivewireMaterial\Support\Scheme;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
$this->configureDefaults();
// The colour profile the admin chose in Admin settings; asked each time a page, mail or
// error page draws its colours, so a new choice applies at once in every Octane worker.
Scheme::resolveProfileUsing(fn (): ?string => Setting::get('color_profile'));
}
/**
-12
View File
@@ -2,7 +2,6 @@
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
@@ -13,14 +12,6 @@ use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
@@ -37,7 +28,6 @@ class FortifyServiceProvider extends ServiceProvider
private function configureActions(): void
{
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
Fortify::createUsersUsing(CreateNewUser::class);
}
/**
@@ -46,10 +36,8 @@ class FortifyServiceProvider extends ServiceProvider
private function configureViews(): void
{
Fortify::loginView(fn () => view('pages::auth.login'));
Fortify::verifyEmailView(fn () => view('pages::auth.verify-email'));
Fortify::twoFactorChallengeView(fn () => view('pages::auth.two-factor-challenge'));
Fortify::confirmPasswordView(fn () => view('pages::auth.confirm-password'));
Fortify::registerView(fn () => view('pages::auth.register'));
Fortify::resetPasswordView(fn () => view('pages::auth.reset-password'));
Fortify::requestPasswordResetLinkView(fn () => view('pages::auth.forgot-password'));
}
+234 -190
View File
@@ -4,11 +4,30 @@ namespace App\Services;
use Generator;
use RuntimeException;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* The encrypted file formats and the keys behind them.
*
* New files are `SEALCHK2`, written chunk by chunk as the uploader's browser sends them:
*
* [8 bytes: "SEALCHK2" magic]
* [4 bytes: chunk size S, uint32 big-endian]
* [7 bytes: random nonce prefix]
* Per chunk i: [ciphertext (S bytes, fewer on the last chunk)][16 bytes: GCM tag]
*
* Chunk i's nonce is the prefix, i as uint32 big-endian and a byte that is 1 on the last chunk
* and 0 on every other (the STREAM construction), so dropping, reordering or appending chunks
* fails authentication. The browser encrypts with the same layout (resources/js/share-uploader.js).
*
* `SEALCHK1` (a tag before each chunk, the index XORed into a 12-byte nonce, no last-chunk flag)
* and the single-block legacy format are still read for shares created before.
*/
class FileEncryptionService
{
public const HEADER_LENGTH = 19;
public const TAG_LENGTH = 16;
private const CIPHER = 'aes-256-gcm';
private const PBKDF2_ITERATIONS = 100000;
@@ -17,28 +36,23 @@ class FileEncryptionService
private const NONCE_LENGTH = 12;
private const TAG_LENGTH = 16;
private const NONCE_PREFIX_LENGTH = 7;
private const MAGIC_HEADER = 'SEALCHK1';
private const MAGIC = 'SEALCHK2';
private const DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024; // 4 MB
private const LEGACY_CHUNKED_MAGIC = 'SEALCHK1';
private const WRAPPED_KEY_ALGORITHM = 'argon2id';
/**
* Derive an encryption key from a password and salt using PBKDF2-SHA256.
* Derive a key from a password and salt using PBKDF2-SHA256, as shares created before
* envelope encryption were keyed.
*/
public function deriveKey(string $password, string $salt): string
{
return hash_pbkdf2('sha256', $password, hex2bin($salt), self::PBKDF2_ITERATIONS, self::KEY_LENGTH, true);
}
/**
* Generate a random hex salt (32 bytes = 64 hex chars).
*/
public function generateSalt(): string
{
return bin2hex(random_bytes(32));
}
/**
* Generate a random encryption key (32 bytes, returned as hex).
*/
@@ -48,219 +62,134 @@ class FileEncryptionService
}
/**
* Encrypt a file using chunked AES-256-GCM.
* Wrap a share's data key with a key derived from its password (Argon2id).
*
* Output format:
* [8 bytes: "SEALCHK1" magic]
* [4 bytes: chunk size, uint32 big-endian]
* [12 bytes: base nonce]
* Per chunk:
* [16 bytes: GCM auth tag]
* [N bytes: ciphertext (up to chunk_size)]
* The result names its algorithm and parameters, so they can be raised later without breaking
* shares wrapped before: `argon2id$<opslimit>$<memlimit>$<salt>$<nonce>$<box>`, in hex.
*/
public function encryptFile(string $sourcePath, string $destPath, string $key): void
public function wrapKey(string $dataKeyHex, string $password): string
{
$source = fopen($sourcePath, 'rb');
$salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES);
$opslimit = SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE;
$memlimit = SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE;
if ($source === false) {
throw new RuntimeException("Cannot read source file: {$sourcePath}");
}
$wrappingKey = $this->deriveWrappingKey($password, $salt, $opslimit, $memlimit);
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$box = sodium_crypto_secretbox(hex2bin($dataKeyHex), $nonce, $wrappingKey);
$dest = fopen($destPath, 'wb');
sodium_memzero($wrappingKey);
if ($dest === false) {
fclose($source);
throw new RuntimeException("Cannot write encrypted file: {$destPath}");
}
try {
$binaryKey = $this->normalizeToBinaryKey($key);
$baseNonce = random_bytes(self::NONCE_LENGTH);
$chunkSize = self::DEFAULT_CHUNK_SIZE;
// Write header
fwrite($dest, self::MAGIC_HEADER);
fwrite($dest, pack('N', $chunkSize));
fwrite($dest, $baseNonce);
$chunkIndex = 0;
while (! feof($source)) {
$plaintext = fread($source, $chunkSize);
if ($plaintext === false || $plaintext === '') {
break;
}
$nonce = $this->deriveChunkNonce($baseNonce, $chunkIndex);
$tag = '';
$ciphertext = openssl_encrypt(
$plaintext,
self::CIPHER,
$binaryKey,
OPENSSL_RAW_DATA,
$nonce,
$tag,
'',
self::TAG_LENGTH,
);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed at chunk '.$chunkIndex);
}
fwrite($dest, $tag);
fwrite($dest, $ciphertext);
$chunkIndex++;
}
} catch (RuntimeException $e) {
fclose($source);
fclose($dest);
@unlink($destPath);
throw $e;
}
fclose($source);
fclose($dest);
return implode('$', [self::WRAPPED_KEY_ALGORITHM, $opslimit, $memlimit, bin2hex($salt), bin2hex($nonce), bin2hex($box)]);
}
/**
* Decrypt a file and return the plaintext content.
* Unwrap a share's data key with its password; returns the key as hex.
*/
public function decryptFile(string $encryptedPath, string $key): string
public function unwrapKey(string $wrappedKey, string $password): string
{
if ($this->isChunkedFormat($encryptedPath)) {
$parts = [];
$parts = explode('$', $wrappedKey);
foreach ($this->decryptChunks($encryptedPath, $key) as $chunk) {
$parts[] = $chunk;
}
return implode('', $parts);
if (count($parts) !== 6 || $parts[0] !== self::WRAPPED_KEY_ALGORITHM) {
throw new RuntimeException('Unsupported wrapped key');
}
return $this->decryptLegacy($encryptedPath, $key);
[, $opslimit, $memlimit, $salt, $nonce, $box] = $parts;
$wrappingKey = $this->deriveWrappingKey($password, hex2bin($salt), (int) $opslimit, (int) $memlimit);
$dataKey = sodium_crypto_secretbox_open(hex2bin($box), hex2bin($nonce), $wrappingKey);
sodium_memzero($wrappingKey);
if ($dataKey === false) {
throw new RuntimeException('Unwrapping failed - wrong password or corrupted key');
}
return bin2hex($dataKey);
}
/**
* Decrypt a file and stream the response.
* The header a new encrypted file starts with, with a fresh random nonce prefix.
*/
public function decryptFileStream(string $encryptedPath, string $key, string $filename, string $mimeType, ?int $fileSize = null): StreamedResponse
public function createHeader(int $chunkSize): string
{
$headers = [
'Content-Type' => $mimeType ?: 'application/octet-stream',
'Content-Disposition' => HeaderUtils::makeDisposition('attachment', $filename, 'download'),
return self::MAGIC.pack('N', $chunkSize).random_bytes(self::NONCE_PREFIX_LENGTH);
}
/**
* Read a `SEALCHK2` header.
*
* @return array{chunkSize: int, noncePrefix: string}
*/
public function parseHeader(string $header): array
{
if (strlen($header) !== self::HEADER_LENGTH || ! str_starts_with($header, self::MAGIC)) {
throw new RuntimeException('Invalid encrypted file header');
}
return [
'chunkSize' => unpack('N', substr($header, 8, 4))[1],
'noncePrefix' => substr($header, 12, self::NONCE_PREFIX_LENGTH),
];
if ($fileSize !== null) {
$headers['Content-Length'] = $fileSize;
}
if ($this->isChunkedFormat($encryptedPath)) {
return new StreamedResponse(function () use ($encryptedPath, $key): void {
foreach ($this->decryptChunks($encryptedPath, $key) as $chunk) {
echo $chunk;
flush();
}
}, 200, $headers);
}
$content = $this->decryptLegacy($encryptedPath, $key);
if (! isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($content);
}
return new StreamedResponse(function () use ($content): void {
echo $content;
}, 200, $headers);
}
/**
* Stream decrypted file content directly to output (echo).
* Use this when you need to add post-streaming logic inside a StreamedResponse callback.
* How many chunks a file of this size is sent in; an empty file is one empty chunk.
*/
public function streamDecryptedFile(string $encryptedPath, string $key): void
public function chunkCount(int $size, int $chunkSize): int
{
if ($this->isChunkedFormat($encryptedPath)) {
foreach ($this->decryptChunks($encryptedPath, $key) as $chunk) {
echo $chunk;
flush();
}
return;
}
echo $this->decryptLegacy($encryptedPath, $key);
return max(1, intdiv($size + $chunkSize - 1, $chunkSize));
}
/**
* Normalize a hex key to binary.
* Where chunk `$index` starts in the encrypted file.
*/
private function normalizeToBinaryKey(string $key): string
public function chunkOffset(int $index, int $chunkSize): int
{
return strlen($key) === 64 ? hex2bin($key) : $key;
return self::HEADER_LENGTH + $index * ($chunkSize + self::TAG_LENGTH);
}
/**
* Derive a unique nonce for a chunk by XORing the chunk index into the last 4 bytes.
* Encrypt one chunk: its ciphertext followed by its tag, as WebCrypto returns it.
*/
private function deriveChunkNonce(string $baseNonce, int $chunkIndex): string
public function encryptChunk(string $plaintext, string $key, string $noncePrefix, int $index, bool $isLast): string
{
$nonce = $baseNonce;
$indexBytes = pack('N', $chunkIndex);
$tag = '';
for ($i = 0; $i < 4; $i++) {
$nonce[self::NONCE_LENGTH - 4 + $i] = $nonce[self::NONCE_LENGTH - 4 + $i] ^ $indexBytes[$i];
$ciphertext = openssl_encrypt(
$plaintext,
self::CIPHER,
$this->normalizeToBinaryKey($key),
OPENSSL_RAW_DATA,
$this->chunkNonce($noncePrefix, $index, $isLast),
$tag,
'',
self::TAG_LENGTH,
);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed at chunk '.$index);
}
return $nonce;
return $ciphertext.$tag;
}
/**
* Check if a file uses the chunked encryption format.
* Decrypt one chunk, which fails unless its index and last-chunk flag are the ones it was
* encrypted with.
*/
private function isChunkedFormat(string $path): bool
public function decryptChunk(string $chunk, string $key, string $noncePrefix, int $index, bool $isLast): string
{
$handle = fopen($path, 'rb');
if ($handle === false) {
return false;
if (strlen($chunk) < self::TAG_LENGTH) {
throw new RuntimeException('Invalid encrypted file: truncated chunk '.$index);
}
$magic = fread($handle, 8);
fclose($handle);
return $magic === self::MAGIC_HEADER;
}
/**
* Decrypt a legacy single-block encrypted file.
* Format: [12-byte nonce][16-byte auth tag][ciphertext]
*/
private function decryptLegacy(string $encryptedPath, string $key): string
{
$data = file_get_contents($encryptedPath);
if ($data === false) {
throw new RuntimeException("Cannot read encrypted file: {$encryptedPath}");
}
$binaryKey = $this->normalizeToBinaryKey($key);
$nonce = substr($data, 0, self::NONCE_LENGTH);
$tag = substr($data, self::NONCE_LENGTH, self::TAG_LENGTH);
$ciphertext = substr($data, self::NONCE_LENGTH + self::TAG_LENGTH);
$plaintext = openssl_decrypt(
$ciphertext,
substr($chunk, 0, -self::TAG_LENGTH),
self::CIPHER,
$binaryKey,
$this->normalizeToBinaryKey($key),
OPENSSL_RAW_DATA,
$nonce,
$tag,
$this->chunkNonce($noncePrefix, $index, $isLast),
substr($chunk, -self::TAG_LENGTH),
);
if ($plaintext === false) {
@@ -271,7 +200,54 @@ class FileEncryptionService
}
/**
* Generator that yields decrypted plaintext chunks from a chunked encrypted file.
* The decrypted content of a file in any of the three formats, chunk by chunk.
*
* @return Generator<int, string>
*/
public function decryptedChunks(string $encryptedPath, string $key): Generator
{
$magic = (string) file_get_contents($encryptedPath, false, null, 0, 8);
if ($magic === self::MAGIC) {
yield from $this->decryptChunks($encryptedPath, $key);
} elseif ($magic === self::LEGACY_CHUNKED_MAGIC) {
yield from $this->decryptLegacyChunks($encryptedPath, $key);
} else {
yield $this->decryptLegacy($encryptedPath, $key);
}
}
/**
* Normalize a hex key to binary.
*/
private function normalizeToBinaryKey(string $key): string
{
return strlen($key) === 64 ? hex2bin($key) : $key;
}
private function deriveWrappingKey(string $password, string $salt, int $opslimit, int $memlimit): string
{
return sodium_crypto_pwhash(
SODIUM_CRYPTO_SECRETBOX_KEYBYTES,
$password,
$salt,
$opslimit,
$memlimit,
SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13,
);
}
/**
* A `SEALCHK2` chunk's nonce: the file's prefix, the chunk index and the last-chunk flag.
*/
private function chunkNonce(string $noncePrefix, int $index, bool $isLast): string
{
return $noncePrefix.pack('N', $index).($isLast ? "\x01" : "\x00");
}
/**
* Decrypt a `SEALCHK2` file; the chunk count comes from the file's length, so a file cut short
* at a chunk boundary fails on its new last chunk.
*
* @return Generator<int, string>
*/
@@ -284,17 +260,44 @@ class FileEncryptionService
}
try {
// Read header
$magic = fread($handle, 8);
['chunkSize' => $chunkSize, 'noncePrefix' => $noncePrefix] = $this->parseHeader((string) fread($handle, self::HEADER_LENGTH));
if ($magic !== self::MAGIC_HEADER) {
throw new RuntimeException('Invalid chunked file format');
$storedChunkSize = $chunkSize + self::TAG_LENGTH;
$payloadLength = (int) filesize($encryptedPath) - self::HEADER_LENGTH;
$chunkCount = intdiv($payloadLength + $storedChunkSize - 1, $storedChunkSize);
if ($chunkCount === 0) {
throw new RuntimeException('Invalid encrypted file: no chunks');
}
$chunkSizeData = fread($handle, 4);
$chunkSize = unpack('N', $chunkSizeData)[1];
for ($index = 0; $index < $chunkCount; $index++) {
$chunk = (string) fread($handle, $storedChunkSize);
$baseNonce = fread($handle, self::NONCE_LENGTH);
yield $this->decryptChunk($chunk, $key, $noncePrefix, $index, $index === $chunkCount - 1);
}
} finally {
fclose($handle);
}
}
/**
* Decrypt a `SEALCHK1` file.
*
* @return Generator<int, string>
*/
private function decryptLegacyChunks(string $encryptedPath, string $key): Generator
{
$handle = fopen($encryptedPath, 'rb');
if ($handle === false) {
throw new RuntimeException("Cannot read encrypted file: {$encryptedPath}");
}
try {
fread($handle, 8);
$chunkSize = unpack('N', (string) fread($handle, 4))[1];
$baseNonce = (string) fread($handle, self::NONCE_LENGTH);
if (strlen($baseNonce) !== self::NONCE_LENGTH) {
throw new RuntimeException('Invalid chunked file: truncated header');
@@ -320,14 +323,12 @@ class FileEncryptionService
throw new RuntimeException('Invalid chunked file: missing ciphertext at chunk '.$chunkIndex);
}
$nonce = $this->deriveChunkNonce($baseNonce, $chunkIndex);
$plaintext = openssl_decrypt(
$ciphertext,
self::CIPHER,
$binaryKey,
OPENSSL_RAW_DATA,
$nonce,
$this->legacyChunkNonce($baseNonce, $chunkIndex),
$tag,
);
@@ -342,4 +343,47 @@ class FileEncryptionService
fclose($handle);
}
}
/**
* A `SEALCHK1` chunk's nonce: the chunk index XORed into the last 4 bytes of the base nonce.
*/
private function legacyChunkNonce(string $baseNonce, int $chunkIndex): string
{
$nonce = $baseNonce;
$indexBytes = pack('N', $chunkIndex);
for ($i = 0; $i < 4; $i++) {
$nonce[self::NONCE_LENGTH - 4 + $i] = $nonce[self::NONCE_LENGTH - 4 + $i] ^ $indexBytes[$i];
}
return $nonce;
}
/**
* Decrypt a legacy single-block encrypted file.
* Format: [12-byte nonce][16-byte auth tag][ciphertext]
*/
private function decryptLegacy(string $encryptedPath, string $key): string
{
$data = file_get_contents($encryptedPath);
if ($data === false) {
throw new RuntimeException("Cannot read encrypted file: {$encryptedPath}");
}
$plaintext = openssl_decrypt(
substr($data, self::NONCE_LENGTH + self::TAG_LENGTH),
self::CIPHER,
$this->normalizeToBinaryKey($key),
OPENSSL_RAW_DATA,
substr($data, 0, self::NONCE_LENGTH),
substr($data, self::NONCE_LENGTH, self::TAG_LENGTH),
);
if ($plaintext === false) {
throw new RuntimeException('Decryption failed - wrong key or corrupted data');
}
return $plaintext;
}
}
+197
View File
@@ -0,0 +1,197 @@
<?php
namespace App\Services;
use App\Models\Setting;
use InvalidArgumentException;
use Random\Randomizer;
/**
* Random share passwords, drawn the way Admin settings say.
*
* Every draw comes from `Random\Randomizer`'s default engine, which is the operating system's
* CSPRNG. Passphrases come from EFF's large word list (CC BY 3.0 US), without its four hyphenated
* words so a separator always splits a passphrase into its words.
*/
class PasswordGeneratorService
{
/** Off: uploaders type their own. Button: a Generate button fills one in. Prefill: filled in as protection is switched on. */
public const MODES = ['off', 'button', 'prefill'];
public const TYPES = ['characters', 'passphrase'];
/**
* The characters each set draws from. The symbols leave out what chat apps turn into formatting
* (`* _ ~ \``) and what breaks once pasted into quotes or markup (`' " \ < >`).
*
* @var array<string, string>
*/
public const CHARACTER_SETS = [
'uppercase' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'lowercase' => 'abcdefghijklmnopqrstuvwxyz',
'numbers' => '0123456789',
'symbols' => '!#$%&()+,-./:;=?@[]{}',
];
/** Characters that read alike in many typefaces. */
public const AMBIGUOUS_CHARACTERS = '0O1lI';
/** @var array<string, string> */
public const SEPARATORS = [
'hyphen' => '-',
'dot' => '.',
'underscore' => '_',
'space' => ' ',
];
public const MIN_LENGTH = 12;
public const MAX_LENGTH = 64;
public const MIN_WORDS = 4;
public const MAX_WORDS = 10;
/**
* @var array{mode: string, type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}
*/
public const DEFAULTS = [
'mode' => 'button',
'type' => 'characters',
'length' => 20,
'characterSets' => ['uppercase', 'lowercase', 'numbers'],
'avoidAmbiguous' => true,
'words' => 6,
'separator' => 'hyphen',
];
/** @var list<string>|null */
private ?array $wordList = null;
/**
* How the upload page offers generated passwords.
*/
public function mode(): string
{
$mode = Setting::get('password_generator_mode');
return in_array($mode, self::MODES, true) ? $mode : self::DEFAULTS['mode'];
}
/**
* The saved generator settings, with the default for anything missing or no longer allowed.
*
* @return array{mode: string, type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}
*/
public function options(): array
{
$type = Setting::get('password_generator_type');
$length = (int) Setting::get('password_generator_length', self::DEFAULTS['length']);
$words = (int) Setting::get('password_generator_words', self::DEFAULTS['words']);
$separator = Setting::get('password_generator_separator');
$characterSets = array_values(array_intersect(
array_keys(self::CHARACTER_SETS),
explode(',', (string) Setting::get('password_generator_character_sets')),
));
return [
'mode' => $this->mode(),
'type' => in_array($type, self::TYPES, true) ? $type : self::DEFAULTS['type'],
'length' => $length >= self::MIN_LENGTH && $length <= self::MAX_LENGTH ? $length : self::DEFAULTS['length'],
'characterSets' => $characterSets ?: self::DEFAULTS['characterSets'],
'avoidAmbiguous' => (bool) Setting::get('password_generator_avoid_ambiguous', self::DEFAULTS['avoidAmbiguous'] ? '1' : '0'),
'words' => $words >= self::MIN_WORDS && $words <= self::MAX_WORDS ? $words : self::DEFAULTS['words'],
'separator' => is_string($separator) && array_key_exists($separator, self::SEPARATORS) ? $separator : self::DEFAULTS['separator'],
];
}
/**
* Generate a password from the given options, or from the saved settings.
*
* @param array{type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int, separator: string}|null $options
*/
public function generate(?array $options = null): string
{
$options ??= $this->options();
return $options['type'] === 'passphrase'
? $this->passphrase($options['words'], self::SEPARATORS[$options['separator']])
: $this->characters($options['length'], $options['characterSets'], $options['avoidAmbiguous']);
}
/**
* Draw characters uniformly from the chosen sets, drawing again until every set shows up at
* least once. Redrawing keeps each valid password equally likely, where placing one character
* of each set first would not.
*
* @param list<string> $characterSets
*/
public function characters(int $length, array $characterSets, bool $avoidAmbiguous): string
{
$alphabets = $this->alphabets($characterSets, $avoidAmbiguous);
if ($alphabets === [] || $length < count($alphabets)) {
throw new InvalidArgumentException('A password needs at least one character set and room for each of them.');
}
$randomizer = new Randomizer;
do {
$password = $randomizer->getBytesFromString(implode('', $alphabets), $length);
} while (array_filter($alphabets, fn (string $alphabet): bool => strpbrk($password, $alphabet) === false) !== []);
return $password;
}
/**
* Draw words from the word list, each independently of the others.
*/
public function passphrase(int $words, string $separator): string
{
$wordList = $this->wordList();
$randomizer = new Randomizer;
return implode($separator, array_map(
fn (): string => $wordList[$randomizer->getInt(0, count($wordList) - 1)],
range(1, max(1, $words)),
));
}
/**
* Roughly how many bits of entropy a password from these options carries.
*
* @param array{type: string, length: int, characterSets: list<string>, avoidAmbiguous: bool, words: int} $options
*/
public function entropyBits(array $options): int
{
if ($options['type'] === 'passphrase') {
return (int) floor($options['words'] * log(count($this->wordList()), 2));
}
$alphabetSize = strlen(implode('', $this->alphabets($options['characterSets'], $options['avoidAmbiguous'])));
return $alphabetSize > 0 ? (int) floor($options['length'] * log($alphabetSize, 2)) : 0;
}
/**
* @return list<string>
*/
public function wordList(): array
{
return $this->wordList ??= file(resource_path('wordlists/eff-large-wordlist.txt'), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}
/**
* The characters of each chosen set, without the look-alikes when asked.
*
* @param list<string> $characterSets
* @return array<string, string>
*/
private function alphabets(array $characterSets, bool $avoidAmbiguous): array
{
return collect(self::CHARACTER_SETS)
->only($characterSets)
->map(fn (string $alphabet): string => $avoidAmbiguous ? str_replace(str_split(self::AMBIGUOUS_CHARACTERS), '', $alphabet) : $alphabet)
->all();
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Services;
use BaconQrCode\Common\ErrorCorrectionLevel;
use BaconQrCode\Encoder\Encoder;
use BaconQrCode\Renderer\Color\Rgb;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\Fill;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
class QrCodeService
{
/**
* The QR code's width and height in the SVG, in pixels: the size a canvas draws it at.
*/
public const SIZE = 1024;
/**
* Draw the contents as a QR code in SVG: black on white with a four-module quiet zone and
* error correction M, the most reliable to scan from a screen or a print. The XML declaration
* is dropped so the markup can sit inline in a page.
*/
public function svg(string $contents): string
{
$svg = (new Writer(
new ImageRenderer(
new RendererStyle(self::SIZE, 4, null, null, Fill::uniformColor(new Rgb(255, 255, 255), new Rgb(0, 0, 0))),
new SvgImageBackEnd,
),
))->writeString($contents, Encoder::DEFAULT_BYTE_MODE_ENCODING, ErrorCorrectionLevel::M());
return trim(substr($svg, strpos($svg, "\n") + 1));
}
}
+329 -53
View File
@@ -5,80 +5,265 @@ namespace App\Services;
use App\Models\Setting;
use App\Models\Share;
use App\Models\ShareFile;
use Carbon\CarbonInterface;
use Illuminate\Contracts\Session\Session;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use League\MimeTypeDetection\FinfoMimeTypeDetector;
use RuntimeException;
/**
* A share's life: files registered into a pending share, their encrypted chunks stored as the
* uploader's browser sends them, and the share completed with its options.
*/
class ShareService
{
/**
* How long a recipient may keep starting downloads of a share after their download was counted.
*/
public const DOWNLOAD_WINDOW_MINUTES = 60;
public function __construct(
private FileEncryptionService $encryptionService,
) {}
/**
* Create a new share with encrypted files.
* Register a file the uploader's browser is about to send, in the given pending share or in a
* new one, and write its encrypted file's header.
*
* @param array<int, array{file: UploadedFile, relativePath: string|null}> $files
* @param array{password?: string|null, expires_at?: string|null, max_downloads?: int|null} $options
* @throws ValidationException when the file breaks an admin limit
*/
public function createShare(array $files, array $options = []): Share
public function registerFile(?Share $pendingShare, string $name, int $size, ?string $relativePath): ShareFile
{
$token = $this->generateUniqueToken();
$salt = $this->encryptionService->generateSalt();
$password = $options['password'] ?? null;
$maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024);
$maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
$maxSizePerShare = (int) Setting::get('max_size_per_share', 2 * 1024 * 1024 * 1024);
if ($password) {
$encryptionKey = $this->encryptionService->deriveKey($password, $salt);
$encryptionKeyHex = bin2hex($encryptionKey);
$storedEncryptionKey = null;
} else {
$encryptionKeyHex = $this->encryptionService->generateRandomKey();
$storedEncryptionKey = $encryptionKeyHex;
if ($name === '' || mb_strlen($name) > 255 || $size < 0) {
$this->rejectFile(__('The file could not be added.'));
}
$share = Share::query()->create([
'token' => $token,
'password' => $password ? Hash::make($password) : null,
'encryption_key' => $storedEncryptionKey,
'encryption_salt' => $salt,
'expires_at' => $options['expires_at'] ?? null,
'max_downloads' => $options['max_downloads'] ?? null,
if ($size > $maxFileSize) {
$this->rejectFile(__('":name" is too large (:size MB). Maximum file size is :max MB.', [
'name' => $name,
'size' => round($size / (1024 * 1024), 1),
'max' => intdiv($maxFileSize, 1024 * 1024),
]));
}
if ($pendingShare && $pendingShare->files()->count() >= $maxFilesPerShare) {
$this->rejectFile(__('Too many files. Maximum :max files allowed per share.', ['max' => $maxFilesPerShare]));
}
if (($pendingShare?->total_size ?? 0) + $size > $maxSizePerShare) {
$this->rejectFile(__('Total file size exceeds the maximum allowed per share.'));
}
if ($this->getTotalUsedSpace() + $size > $this->getMaxStorageQuota()) {
$this->rejectFile(__('Storage is full. Please contact the administrator.'));
}
$share = $pendingShare ?? Share::query()->create([
'token' => $this->generateUniqueToken(),
'encryption_key' => $this->encryptionService->generateRandomKey(),
'total_size' => 0,
]);
$totalSize = 0;
$storedName = Str::uuid().'.enc';
foreach ($files as $fileData) {
/** @var UploadedFile $file */
$file = $fileData['file'];
$relativePath = $fileData['relativePath'] ?? null;
$storedName = Str::uuid().'.enc';
$storedPath = 'shares/'.$share->token.'/'.$storedName;
Storage::disk('shares')->makeDirectory($share->token);
Storage::disk('shares')->put($share->token.'/'.$storedName, $this->encryptionService->createHeader((int) config('uploads.chunk_size')));
$tempPath = $file->getRealPath();
$destPath = Storage::disk('shares')->path($share->token.'/'.$storedName);
$file = $share->files()->create([
'original_name' => $name,
'relative_path' => $this->sanitizeRelativePath($relativePath),
'stored_path' => 'shares/'.$share->token.'/'.$storedName,
'file_size' => $size,
]);
Storage::disk('shares')->makeDirectory($share->token);
$share->increment('total_size', $size);
$this->encryptionService->encryptFile($tempPath, $destPath, $encryptionKeyHex);
return $file;
}
ShareFile::query()->create([
'share_id' => $share->id,
'original_name' => $file->getClientOriginalName(),
'relative_path' => $relativePath,
'stored_path' => $storedPath,
'file_size' => $file->getSize(),
'mime_type' => $file->getMimeType(),
]);
/**
* Verify the encrypted chunk that comes next for a file and write it into place; returns how
* many of the file's chunks are stored. The plaintext only exists in memory, to be checked.
*
* @throws InvalidArgumentException when the chunk has the wrong length or fails authentication
* @throws ModelNotFoundException when the file was removed meanwhile
*/
public function storeChunk(ShareFile $file, int $index, string $chunk): int
{
$share = $file->share;
$handle = @fopen($this->storedFilePath($file), 'r+b');
$totalSize += $file->getSize();
if ($handle === false) {
throw (new ModelNotFoundException)->setModel(ShareFile::class, [$file->id]);
}
$share->update(['total_size' => $totalSize]);
try {
['chunkSize' => $chunkSize, 'noncePrefix' => $noncePrefix] = $this->encryptionService->parseHeader(
(string) fread($handle, FileEncryptionService::HEADER_LENGTH),
);
return $share->fresh();
$chunkCount = $this->encryptionService->chunkCount($file->file_size, $chunkSize);
$isLast = $index === $chunkCount - 1;
if ($index >= $chunkCount) {
throw new InvalidArgumentException('Chunk '.$index.' is beyond the end of the file');
}
$plaintextLength = $isLast ? $file->file_size - $index * $chunkSize : $chunkSize;
if (strlen($chunk) !== $plaintextLength + FileEncryptionService::TAG_LENGTH) {
throw new InvalidArgumentException('Chunk '.$index.' has the wrong length');
}
try {
$plaintext = $this->encryptionService->decryptChunk($chunk, $share->encryption_key, $noncePrefix, $index, $isLast);
} catch (RuntimeException) {
throw new InvalidArgumentException('Chunk '.$index.' failed authentication');
}
$mimeType = $index === 0
? ((new FinfoMimeTypeDetector)->detectMimeType($file->original_name, $plaintext) ?? 'application/octet-stream')
: $file->mime_type;
unset($plaintext);
if (fseek($handle, $this->encryptionService->chunkOffset($index, $chunkSize)) !== 0
|| fwrite($handle, $chunk) !== strlen($chunk)
|| ! fflush($handle)) {
throw new RuntimeException('Cannot write chunk '.$index.' of file '.$file->id);
}
} finally {
fclose($handle);
}
// Counted only once, even when a retry of the same chunk raced this request.
$stored = ShareFile::query()
->whereKey($file->id)
->where('uploaded_chunks', $index)
->update([
'uploaded_chunks' => $index + 1,
'mime_type' => $mimeType,
'completed_at' => $isLast ? now() : null,
]);
if ($stored === 0) {
return ShareFile::query()->findOrFail($file->id)->uploaded_chunks;
}
$share->touch();
return $index + 1;
}
/**
* Remove a file from a pending share, whether or not its upload finished.
*/
public function removeFile(ShareFile $file): void
{
Storage::disk('shares')->delete($file->share->token.'/'.basename($file->stored_path));
$file->share->decrement('total_size', $file->file_size);
$file->delete();
}
/**
* Complete a pending share once every file has arrived: with a password the data key is
* wrapped and no longer stored as it is.
*
* @param array{password?: string|null, expires_at?: mixed, max_downloads?: int|null} $options
*
* @throws ValidationException when files are missing, unfinished or break an admin limit
*/
public function completeShare(Share $share, array $options = []): Share
{
$files = $share->files()->get();
$maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
$maxSizePerShare = (int) Setting::get('max_size_per_share', 2 * 1024 * 1024 * 1024);
if ($files->isEmpty()) {
$this->rejectFile(__('Please select at least one file to upload.'));
}
if ($files->contains(fn (ShareFile $file): bool => $file->completed_at === null)) {
$this->rejectFile(__('Wait until every file has finished uploading, or remove the ones that failed.'));
}
if ($files->count() > $maxFilesPerShare) {
$this->rejectFile(__('Too many files. Maximum :max files allowed per share.', ['max' => $maxFilesPerShare]));
}
if ($files->sum('file_size') > $maxSizePerShare) {
$this->rejectFile(__('Total file size exceeds the maximum allowed per share.'));
}
$password = $options['password'] ?? null;
$share->update([
'password' => $password ? Hash::make($password) : null,
'wrapped_key' => $password ? $this->encryptionService->wrapKey($share->encryption_key, $password) : null,
'encryption_key' => $password ? null : $share->encryption_key,
'expires_at' => $options['expires_at'] ?? null,
'max_downloads' => $options['max_downloads'] ?? null,
'total_size' => $files->sum('file_size'),
'completed_at' => now(),
]);
return $share;
}
/**
* Create a share from files already on the server, through the same steps an upload from the
* browser takes. Used by tests and demo data.
*
* @param array<int, array{file: UploadedFile, relativePath: string|null}> $files
* @param array{password?: string|null, expires_at?: mixed, max_downloads?: int|null} $options
*/
public function createShare(array $files, array $options = []): Share
{
$share = null;
foreach ($files as $fileData) {
$file = $fileData['file'];
$shareFile = $this->registerFile($share, $file->getClientOriginalName(), $file->getSize(), $fileData['relativePath'] ?? null);
$share = $shareFile->share;
$header = $this->readHeader($shareFile);
$source = fopen($file->getRealPath(), 'rb');
for ($index = 0; $index < $header['chunkCount']; $index++) {
$plaintextLength = min($header['chunkSize'], $shareFile->file_size - $index * $header['chunkSize']);
// A fake upload reports a size its content does not have: zeros make up the rest.
$chunk = $this->encryptionService->encryptChunk(
str_pad($plaintextLength > 0 ? (string) fread($source, $plaintextLength) : '', $plaintextLength, "\0"),
$share->encryption_key,
$header['noncePrefix'],
$index,
$index === $header['chunkCount'] - 1,
);
$this->storeChunk($shareFile->refresh(), $index, $chunk);
}
fclose($source);
}
if ($share === null) {
$this->rejectFile(__('Please select at least one file to upload.'));
}
return $this->completeShare($share, $options);
}
/**
@@ -108,7 +293,8 @@ class ShareService
}
/**
* Get the decryption key for a share.
* Get the decryption key for a share: unwrapped with the password, derived from it for shares
* created before key wrapping, or stored for shares without a password.
*/
public function getDecryptionKey(Share $share, ?string $password = null): string
{
@@ -117,6 +303,10 @@ class ShareService
throw new RuntimeException('Password required for this share');
}
if ($share->wrapped_key !== null) {
return $this->encryptionService->unwrapKey($share->wrapped_key, $password);
}
return bin2hex($this->encryptionService->deriveKey($password, $share->encryption_salt));
}
@@ -136,19 +326,59 @@ class ShareService
}
/**
* Record a download and auto-delete if limit reached.
* When this session's download window for a share ends, or null while it has none open. The
* window opens with the session's counted download; until it ends, the session may start more
* downloads of the share without counting them, even once the share has reached its limit.
*/
public function recordDownload(Share $share): void
public function downloadWindowEndsAt(Share $share, Session $session): ?CarbonInterface
{
$share->increment('download_count');
$countedAt = $session->get($this->downloadSessionKey($share));
if ($share->hasReachedDownloadLimit()) {
$this->deleteShare($share);
if (! is_int($countedAt)) {
return null;
}
$endsAt = Carbon::createFromTimestamp($countedAt)->addMinutes(self::DOWNLOAD_WINDOW_MINUTES);
return $endsAt->isFuture() ? $endsAt : null;
}
/**
* Get total used space in bytes.
* Let this session download from a share: one recipient's visit is one download, so a session
* without an open window counts one and opens its window. The limit is checked in the same
* update that counts, so two recipients who start at once cannot both take the last download.
* False when no download is left for this session.
*/
public function claimDownload(Share $share, Session $session): bool
{
if ($this->downloadWindowEndsAt($share, $session) !== null) {
return true;
}
$counted = Share::query()
->whereKey($share->id)
->where(fn ($query) => $query->whereNull('max_downloads')->orWhereColumn('download_count', '<', 'max_downloads'))
->increment('download_count', 1, ['last_downloaded_at' => now()]);
if ($counted === 0) {
return false;
}
$session->put($this->downloadSessionKey($share), now()->getTimestamp());
return true;
}
/**
* The session key holding when this session's download of a share was counted.
*/
private function downloadSessionKey(Share $share): string
{
return 'share_download_'.$share->token;
}
/**
* Get total used space in bytes, files still being uploaded included.
*/
public function getTotalUsedSpace(): int
{
@@ -160,9 +390,7 @@ class ShareService
*/
public function isStorageFull(): bool
{
$maxQuota = (int) Setting::get('max_storage_quota', 20 * 1024 * 1024 * 1024);
return $this->getTotalUsedSpace() >= $maxQuota;
return $this->getTotalUsedSpace() >= $this->getMaxStorageQuota();
}
/**
@@ -172,4 +400,52 @@ class ShareService
{
return (int) Setting::get('max_storage_quota', 20 * 1024 * 1024 * 1024);
}
/**
* A registered file's chunk size, nonce prefix and chunk count, from its encrypted file's header.
*
* @return array{chunkSize: int, noncePrefix: string, chunkCount: int}
*/
public function readHeader(ShareFile $file): array
{
$header = $this->encryptionService->parseHeader(
(string) file_get_contents($this->storedFilePath($file), false, null, 0, FileEncryptionService::HEADER_LENGTH),
);
return [...$header, 'chunkCount' => $this->encryptionService->chunkCount($file->file_size, $header['chunkSize'])];
}
/**
* Where a file's encrypted content is stored on disk.
*/
public function storedFilePath(ShareFile $file): string
{
return Storage::disk('shares')->path($file->share->token.'/'.basename($file->stored_path));
}
/**
* A relative path from a dropped folder, or null when it could reach outside the share.
*/
private function sanitizeRelativePath(?string $relativePath): ?string
{
if ($relativePath === null) {
return null;
}
$relativePath = str_replace('\\', '/', $relativePath);
if (str_starts_with($relativePath, '/') || str_contains($relativePath, '..')) {
return null;
}
return $relativePath;
}
/**
* @throws ValidationException
*/
private function rejectFile(string $message): never
{
throw ValidationException::withMessages(['files' => $message]);
}
}
+7 -2
View File
@@ -6,13 +6,18 @@
"guidelines": true,
"herd_mcp": false,
"mcp": true,
"packages": [
"nonameweb/livewire-material"
],
"sail": false,
"skills": [
"infer-conventions",
"fortify-development",
"laravel-best-practices",
"testing-best-practices",
"octane-development",
"livewire-development",
"pest-testing",
"tailwindcss-development"
"livewire-material-development",
"material-3-design"
]
}
+2 -4
View File
@@ -5,7 +5,6 @@ use App\Http\Middleware\EnsureSetupComplete;
use App\Http\Middleware\SecurityHeaders;
use App\Http\Middleware\SystemPasswordGate;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
@@ -27,6 +26,5 @@ return Application::configure(basePath: dirname(__DIR__))
'admin' => EnsureAdmin::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
->withExceptions()
->create();
+18 -10
View File
@@ -10,23 +10,24 @@
"license": "MIT",
"require": {
"php": "^8.5",
"bacon/bacon-qr-code": "^3.0",
"laravel/fortify": "^1.30",
"laravel/framework": "^13.0",
"laravel/octane": "^2.13",
"laravel/tinker": "^3.0",
"livewire/livewire": "^4.0",
"robsontenorio/mary": "^2.7"
"maennchen/zipstream-php": "^3.2",
"nonameweb/livewire-material": "^2.0"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/boost": "^2.0",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"pestphp/pest": "^4.3",
"pestphp/pest-plugin-laravel": "^4.0"
"pestphp/pest": "^5.1",
"pestphp/pest-plugin-browser": "^5.0",
"pestphp/pest-plugin-laravel": "^5.0"
},
"autoload": {
"psr-4": {
@@ -49,10 +50,6 @@
"npm install",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan octane:frankenphp --host=127.0.0.1 --port=8000 --watch\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"lint": [
"pint --parallel"
],
@@ -82,6 +79,11 @@
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
],
"screenshots": [
"Composer\\Config::disableProcessTimeout",
"npm run build",
"@php vendor/bin/pest tests/Screenshots"
]
},
"extra": {
@@ -99,5 +101,11 @@
}
},
"minimum-stability": "stable",
"prefer-stable": true
"prefer-stable": true,
"repositories": {
"livewire-material": {
"type": "vcs",
"url": "https://gitea.nonameweb.ch/noNameWEB/livewire-material.git"
}
}
}
Generated
+2916 -1467
View File
File diff suppressed because it is too large Load Diff
+15 -111
View File
@@ -1,126 +1,30 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application
|--------------------------------------------------------------------------
|
| Only what differs from the framework's config/app.php; Laravel merges
| every other key from its own defaults.
|
*/
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
return [
'name' => env('APP_NAME', 'SealShare'),
/*
|--------------------------------------------------------------------------
| Application Environment
| SealShare Version
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
| The release this code is, shown on the admin dashboard. Bump it together
| with the release's heading in CHANGELOG.md: tests/Feature/AppVersionTest
| fails while the two differ.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
'version' => '2.2.0',
];
-117
View File
@@ -1,117 +0,0 @@
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];
+10 -122
View File
@@ -1,130 +1,18 @@
<?php
use Illuminate\Support\Str;
/*
|--------------------------------------------------------------------------
| Serializable Classes
|--------------------------------------------------------------------------
|
| No PHP classes are unserialized from the cache, to prevent gadget chain
| attacks if the APP_KEY is leaked. The framework's default (null) would
| allow every class. Every other key comes from the framework's defaults.
|
*/
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
/*
|--------------------------------------------------------------------------
| Serializable Classes
|--------------------------------------------------------------------------
|
| This value determines the classes that can be unserialized from cache
| storage. By default, no PHP classes will be unserialized from your
| cache to prevent gadget chain attacks if your APP_KEY is leaked.
|
*/
'serializable_classes' => false,
];
-184
View File
@@ -1,184 +0,0 @@
<?php
use Illuminate\Support\Str;
use Pdo\Mysql;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];
+10 -71
View File
@@ -1,52 +1,19 @@
<?php
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| The encrypted share files. Laravel merges this disk into its own default
| disks (local, public, s3).
|
*/
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
'shares' => [
'driver' => 'local',
'root' => storage_path('app/shares'),
@@ -54,34 +21,6 @@ return [
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
+1 -3
View File
@@ -73,7 +73,7 @@ return [
|
*/
'home' => '/dashboard',
'home' => '/admin/dashboard',
/*
|--------------------------------------------------------------------------
@@ -144,9 +144,7 @@ return [
*/
'features' => [
// Features::registration(), // Disabled - admin created via setup wizard
Features::resetPasswords(),
Features::emailVerification(),
Features::twoFactorAuthentication([
'confirm' => true,
'confirmPassword' => true,
+178
View File
@@ -0,0 +1,178 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Component prefix
|--------------------------------------------------------------------------
|
| Every component is an anonymous Blade component. Without a prefix they are
| <x-button>, <x-card> and so on; set a prefix such as 'm' when a name
| clashes with one of the application's own components, and they become
| <x-m::button>, <x-m::card>. They are always <x-livewire-material::button>
| as well.
|
*/
'prefix' => '',
/*
|--------------------------------------------------------------------------
| Theme
|--------------------------------------------------------------------------
|
| The head script decides the theme before the first paint and writes it to
| <html data-theme>. 'default' is used until the visitor chooses: 'light',
| 'dark' or 'system' (follow the operating system). The choice is kept in
| localStorage under 'storage_key'; values found under 'legacy_keys' (an
| earlier theme toggle's key) are adopted once and then removed.
|
*/
'theme' => [
'default' => 'system',
'storage_key' => 'sealshare-theme',
'legacy_keys' => ['mary-theme'],
],
/*
|--------------------------------------------------------------------------
| Navigation rail
|--------------------------------------------------------------------------
|
| Whether a collapsible navigation rail starts 'expanded' or 'collapsed'
| until the visitor toggles it. The head script applies the choice before
| the first paint, from localStorage under 'storage_key'.
|
*/
'rail' => [
'default' => 'expanded',
'storage_key' => 'material-rail',
],
/*
|--------------------------------------------------------------------------
| Fields
|--------------------------------------------------------------------------
|
| Text fields, selects and pickers come in M3's two styles: 'outlined' (a
| notched outline) and 'filled' (a tinted box with an indicator line). This
| is the style a field takes when its `variant` is not given.
|
*/
'fields' => [
'variant' => 'outlined',
],
/*
|--------------------------------------------------------------------------
| Pagination
|--------------------------------------------------------------------------
|
| Draw Laravel's and Livewire's paginators in M3: the package's views are
| put in front of `pagination::tailwind` and `livewire::tailwind` (and
| their simple versions). An application's own published pagination views
| still win.
|
*/
'pagination' => true,
/*
|--------------------------------------------------------------------------
| Node
|--------------------------------------------------------------------------
|
| `php artisan material:scheme` runs Google's colour utilities through Node.
| Set the binary when `node` is not on the PATH of the user running Artisan.
|
*/
'node' => env('MATERIAL_NODE', 'node'),
/*
|--------------------------------------------------------------------------
| Scheme data
|--------------------------------------------------------------------------
|
| The light and dark hexes `php artisan material:scheme` writes beside the
| stylesheet. The mail theme reads its colours here, and so does an error
| page when the build is missing; without the file both use the package's
| default scheme.
|
*/
'scheme' => resource_path('css/material-scheme.json'),
/*
|--------------------------------------------------------------------------
| Colour profiles
|--------------------------------------------------------------------------
|
| The profiles an admin chooses between in Admin settings. Each one is a
| 'label', a 'seed' (#rrggbb), a 'variant' and an optional 'contrast'.
| `php artisan material:scheme` (without a seed) generates them all into
| resources/css/material-scheme.css; regenerate after changing this list.
| 'profile' is the default, until an admin chooses.
|
*/
'profiles' => [
'indigo' => ['label' => 'Indigo', 'seed' => '#4f46e5', 'variant' => 'vibrant'],
'blue' => ['label' => 'Blue', 'seed' => '#0b57d0', 'variant' => 'vibrant'],
'teal' => ['label' => 'Teal', 'seed' => '#00897b', 'variant' => 'vibrant'],
'green' => ['label' => 'Green', 'seed' => '#2e7d32', 'variant' => 'vibrant'],
'amber' => ['label' => 'Amber', 'seed' => '#e8710a', 'variant' => 'vibrant'],
'rose' => ['label' => 'Rose', 'seed' => '#c2185b', 'variant' => 'vibrant'],
'violet' => ['label' => 'Violet', 'seed' => '#6750a4', 'variant' => 'vibrant'],
'graphite' => ['label' => 'Graphite', 'seed' => '#5f6368', 'variant' => 'neutral'],
],
'profile' => 'indigo',
/*
|--------------------------------------------------------------------------
| Mail
|--------------------------------------------------------------------------
|
| Markdown mail takes the theme when `mail.markdown.theme` (MAIL_MARKDOWN_THEME)
| is 'livewire-material::mail.theme'. 'components' puts this package's mail
| header and message after the application's own mail components — or
| publish them with `vendor:publish --tag=livewire-material-mail` instead.
| 'logo' replaces the app name in that header with an image: an absolute
| 'src', with 'width' and 'height' in pixels, which Outlook sizes it by.
|
*/
'mail' => [
'components' => (bool) env('MATERIAL_MAIL_COMPONENTS', false),
'logo' => [
'src' => null,
'width' => null,
'height' => null,
],
],
/*
|--------------------------------------------------------------------------
| Showcase
|--------------------------------------------------------------------------
|
| Every component in every variant, rendered in the application's own
| scheme. Off unless the application runs locally. 'vite' names the entry
| points that import this package's CSS and JavaScript; the error pages
| load them too, showcase or not.
|
*/
'showcase' => [
'enabled' => (bool) env('MATERIAL_SHOWCASE', env('APP_ENV', 'production') === 'local'),
'path' => 'material',
'middleware' => ['web'],
'vite' => ['resources/css/app.css', 'resources/js/app.js'],
],
];
+19 -254
View File
@@ -1,275 +1,39 @@
<?php
/*
|--------------------------------------------------------------------------
| Livewire
|--------------------------------------------------------------------------
|
| Only what differs from Livewire's own config; every other key comes from
| its defaults. Livewire merges top-level keys only, so a nested key such
| as "payload" is given whole.
|
*/
return [
/*
|---------------------------------------------------------------------------
| Component Locations
|---------------------------------------------------------------------------
|
| This value sets the root directories that'll be used to resolve view-based
| components like single and multi-file components. The make command will
| use the first directory in this array to add new component files to.
|
*/
'component_locations' => [
resource_path('views/components'),
resource_path('views/livewire'),
],
/*
|---------------------------------------------------------------------------
| Component Namespaces
|---------------------------------------------------------------------------
|
| This value sets default namespaces that will be used to resolve view-based
| components like single-file and multi-file components. These folders'll
| also be referenced when creating new components via the make command.
|
*/
'component_namespaces' => [
'layouts' => resource_path('views/layouts'),
'pages' => resource_path('views/pages'),
],
/*
|---------------------------------------------------------------------------
| Page Layout
|---------------------------------------------------------------------------
| The view that will be used as the layout when rendering a single component as
| an entire page via `Route::livewire('/post/create', 'pages::create-post')`.
| In this case, the content of pages::create-post will render into $slot.
|
*/
'component_layout' => 'layouts::app',
/*
|---------------------------------------------------------------------------
| Lazy Loading Placeholder
|---------------------------------------------------------------------------
| Livewire allows you to lazy load components that would otherwise slow down
| the initial page load. Every component can have a custom placeholder or
| you can define the default placeholder view for all components below.
|
*/
'component_placeholder' => null, // Example: 'placeholders::skeleton'
/*
|---------------------------------------------------------------------------
| Make Command
|---------------------------------------------------------------------------
| This value determines the default configuration for the artisan make command
| You can configure the component type (sfc, mfc, class) and whether to use
| the high-voltage (⚡) emoji as a prefix in the sfc|mfc component names.
|
*/
'make_command' => [
'type' => 'sfc', // Options: 'sfc', 'mfc', 'class'
'emoji' => true, // Options: true, false
'with' => [
'js' => false,
'css' => false,
'test' => false,
],
],
/*
|---------------------------------------------------------------------------
| Class Namespace
|---------------------------------------------------------------------------
|
| This value sets the root class namespace for Livewire component classes in
| your application. This value will change where component auto-discovery
| finds components. It's also referenced by the file creation commands.
|
*/
'class_namespace' => 'App\\Livewire',
/*
|---------------------------------------------------------------------------
| Class Path
|---------------------------------------------------------------------------
|
| This value is used to specify the path where Livewire component class files
| are created when running creation commands like `artisan make:livewire`.
| This path is customizable to match your projects directory structure.
|
*/
'class_path' => app_path('Livewire'),
/*
|---------------------------------------------------------------------------
| View Path
|---------------------------------------------------------------------------
|
| This value is used to specify where Livewire component Blade templates are
| stored when running file creation commands like `artisan make:livewire`.
| It is also used if you choose to omit a component's render() method.
|
*/
'view_path' => resource_path('views/livewire'),
/*
|---------------------------------------------------------------------------
| Temporary File Uploads
|---------------------------------------------------------------------------
|
| Livewire handles file uploads by storing uploads in a temporary directory
| before the file is stored permanently. All file uploads are directed to
| a global endpoint for temporary storage. You may configure this below:
|
*/
'temporary_file_upload' => [
'disk' => env('LIVEWIRE_TEMPORARY_FILE_UPLOAD_DISK'), // Example: 'local', 's3' | Default: 'default'
'rules' => ['required', 'file', 'max:4194304'], // 4GB — fine-grained limits enforced per-component
'directory' => null, // Example: 'tmp' | Default: 'livewire-tmp'
'middleware' => null, // Example: 'throttle:5,1' | Default: 'throttle:60,1'
'preview_mimes' => [ // Supported file types for temporary pre-signed file URLs...
'png', 'gif', 'bmp', 'svg', 'wav', 'mp4',
'mov', 'avi', 'wmv', 'mp3', 'm4a',
'jpg', 'jpeg', 'mpga', 'webp', 'wma',
],
'max_upload_time' => 30, // Max duration (in minutes) before an upload is invalidated...
'cleanup' => true, // Should cleanup temporary uploads older than 24 hrs...
],
/*
|---------------------------------------------------------------------------
| Render On Redirect
|---------------------------------------------------------------------------
|
| This value determines if Livewire will run a component's `render()` method
| after a redirect has been triggered using something like `redirect(...)`
| Setting this to true will render the view once more before redirecting
|
*/
'render_on_redirect' => false,
/*
|---------------------------------------------------------------------------
| Eloquent Model Binding
|---------------------------------------------------------------------------
|
| Previous versions of Livewire supported binding directly to eloquent model
| properties using wire:model by default. However, this behavior has been
| deemed too "magical" and has therefore been put under a feature flag.
|
*/
'legacy_model_binding' => false,
/*
|---------------------------------------------------------------------------
| Auto-inject Frontend Assets
|---------------------------------------------------------------------------
|
| By default, Livewire automatically injects its JavaScript and CSS into the
| <head> and <body> of pages containing Livewire components. By disabling
| this behavior, you need to use @livewireStyles and @livewireScripts.
|
*/
'inject_assets' => true,
/*
|---------------------------------------------------------------------------
| Navigate (SPA mode)
|---------------------------------------------------------------------------
|
| By adding `wire:navigate` to links in your Livewire application, Livewire
| will prevent the default link handling and instead request those pages
| via AJAX, creating an SPA-like effect. Configure this behavior here.
|
*/
'navigate' => [
'show_progress_bar' => true,
'progress_bar_color' => '#2299dd',
],
/*
|---------------------------------------------------------------------------
| HTML Morph Markers
|---------------------------------------------------------------------------
|
| Livewire intelligently "morphs" existing HTML into the newly rendered HTML
| after each update. To make this process more reliable, Livewire injects
| "markers" into the rendered Blade surrounding @if, @class & @foreach.
|
*/
'inject_morph_markers' => true,
/*
|---------------------------------------------------------------------------
| Smart Wire Keys
|---------------------------------------------------------------------------
|
| Livewire uses loops and keys used within loops to generate smart keys that
| are applied to nested components that don't have them. This makes using
| nested components more reliable by ensuring that they all have keys.
|
*/
'smart_wire_keys' => true,
/*
|---------------------------------------------------------------------------
| Pagination Theme
|---------------------------------------------------------------------------
|
| When enabling Livewire's pagination feature by using the `WithPagination`
| trait, Livewire will use Tailwind templates to render pagination views
| on the page. If you want Bootstrap CSS, you can specify: "bootstrap"
| livewire-material takes this over itself while it still reads as
| Livewire's own default ("tailwind", or the key missing), so this stays
| explicit: SealShare states the choice itself rather than relying on
| the package to silently switch it.
|
*/
'pagination_theme' => 'tailwind',
/*
|---------------------------------------------------------------------------
| Release Token
|---------------------------------------------------------------------------
|
| This token is stored client-side and sent along with each request to check
| a users session to see if a new release has invalidated it. If there is
| a mismatch it will throw an error and prompt for a browser refresh.
|
*/
'release_token' => 'a',
/*
|---------------------------------------------------------------------------
| CSP Safe
|---------------------------------------------------------------------------
|
| This config is used to determine if Livewire will use the CSP-safe version
| of Alpine in its bundle. This is useful for applications that are using
| strict Content Security Policy (CSP) to protect against XSS attacks.
|
*/
'csp_safe' => false,
'pagination_theme' => 'material',
/*
|---------------------------------------------------------------------------
| Payload Guards
|---------------------------------------------------------------------------
|
| These settings protect against malicious or oversized payloads that could
| cause denial of service. The default values should feel reasonable for
| most web applications. Each can be set to null to disable the limit.
| Livewire's defaults, with at most 20 components per batch request
| instead of 200.
|
*/
@@ -279,4 +43,5 @@ return [
'max_calls' => 50, // Maximum method calls per request
'max_components' => 20, // Maximum components per batch request
],
];
-132
View File
@@ -1,132 +0,0 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
+15 -109
View File
@@ -1,118 +1,24 @@
<?php
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| Markdown mail wears Livewire Material's theme, coloured from the light
| scheme in resources/css/material-scheme.json. Every other key comes from
| the framework's defaults.
|
*/
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'markdown' => [
'theme' => env('MAIL_MARKDOWN_THEME', 'livewire-material::mail.theme'),
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
'paths' => [
resource_path('views/vendor/mail'),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];
+11 -206
View File
@@ -1,222 +1,27 @@
<?php
use Laravel\Octane\Contracts\OperationTerminated;
use Laravel\Octane\Events\RequestHandled;
use Laravel\Octane\Events\RequestReceived;
use Laravel\Octane\Events\RequestTerminated;
use Laravel\Octane\Events\TaskReceived;
use Laravel\Octane\Events\TaskTerminated;
use Laravel\Octane\Events\TickReceived;
use Laravel\Octane\Events\TickTerminated;
use Laravel\Octane\Events\WorkerErrorOccurred;
use Laravel\Octane\Events\WorkerStarting;
use Laravel\Octane\Events\WorkerStopping;
use Laravel\Octane\Listeners\CloseMonologHandlers;
use Laravel\Octane\Listeners\CollectGarbage;
use Laravel\Octane\Listeners\DisconnectFromDatabases;
use Laravel\Octane\Listeners\EnsureUploadedFilesAreValid;
use Laravel\Octane\Listeners\EnsureUploadedFilesCanBeMoved;
use Laravel\Octane\Listeners\FlushOnce;
use Laravel\Octane\Listeners\FlushTemporaryContainerInstances;
use Laravel\Octane\Listeners\FlushUploadedFiles;
use Laravel\Octane\Listeners\ReportException;
use Laravel\Octane\Listeners\StopWorkerIfNecessary;
use Laravel\Octane\Octane;
/*
|--------------------------------------------------------------------------
| Octane
|--------------------------------------------------------------------------
|
| Only what differs from Octane's own config; every other key (listeners,
| warm and flush lists, watch paths, ...) comes from its defaults.
|
*/
return [
/*
|--------------------------------------------------------------------------
| Octane Server
|--------------------------------------------------------------------------
|
| This value determines the default "server" that will be used by Octane
| when starting, restarting, or stopping your server via the CLI. You
| are free to change this to the supported server of your choosing.
|
| Supported: "roadrunner", "swoole", "frankenphp"
|
*/
'server' => env('OCTANE_SERVER', 'frankenphp'),
/*
|--------------------------------------------------------------------------
| Force HTTPS
|--------------------------------------------------------------------------
|
| When this configuration value is set to "true", Octane will inform the
| framework that all absolute links must be generated using the HTTPS
| protocol. Otherwise your links may be generated using plain HTTP.
|
| Absolute links use HTTPS whenever APP_URL does.
*/
'https' => env('OCTANE_HTTPS', str_starts_with(env('APP_URL', ''), 'https://')),
/*
|--------------------------------------------------------------------------
| Octane Listeners
|--------------------------------------------------------------------------
|
| All of the event listeners for Octane's events are defined below. These
| listeners are responsible for resetting your application's state for
| the next request. You may even add your own listeners to the list.
|
*/
'listeners' => [
WorkerStarting::class => [
EnsureUploadedFilesAreValid::class,
EnsureUploadedFilesCanBeMoved::class,
],
RequestReceived::class => [
...Octane::prepareApplicationForNextOperation(),
...Octane::prepareApplicationForNextRequest(),
//
],
RequestHandled::class => [
//
],
RequestTerminated::class => [
// FlushUploadedFiles::class,
],
TaskReceived::class => [
...Octane::prepareApplicationForNextOperation(),
//
],
TaskTerminated::class => [
//
],
TickReceived::class => [
...Octane::prepareApplicationForNextOperation(),
//
],
TickTerminated::class => [
//
],
OperationTerminated::class => [
FlushOnce::class,
FlushTemporaryContainerInstances::class,
// DisconnectFromDatabases::class,
// CollectGarbage::class,
],
WorkerErrorOccurred::class => [
ReportException::class,
StopWorkerIfNecessary::class,
],
WorkerStopping::class => [
CloseMonologHandlers::class,
],
],
/*
|--------------------------------------------------------------------------
| Warm / Flush Bindings
|--------------------------------------------------------------------------
|
| The bindings listed below will either be pre-warmed when a worker boots
| or they will be flushed before every new request. Flushing a binding
| will force the container to resolve that binding again when asked.
|
*/
'warm' => [
...Octane::defaultServicesToWarm(),
],
'flush' => [
//
],
/*
|--------------------------------------------------------------------------
| Octane Swoole Tables
|--------------------------------------------------------------------------
|
| While using Swoole, you may define additional tables as required by the
| application. These tables can be used to store data that needs to be
| quickly accessed by other workers on the particular Swoole server.
|
*/
'tables' => [
'example:1000' => [
'name' => 'string:1000',
'votes' => 'int',
],
],
/*
|--------------------------------------------------------------------------
| Octane Swoole Cache Table
|--------------------------------------------------------------------------
|
| While using Swoole, you may leverage the Octane cache, which is powered
| by a Swoole table. You may set the maximum number of rows as well as
| the number of bytes per row using the configuration options below.
|
*/
'cache' => [
'rows' => 1000,
'bytes' => 10000,
],
/*
|--------------------------------------------------------------------------
| File Watching
|--------------------------------------------------------------------------
|
| The following list of files and directories will be watched when using
| the --watch option offered by Octane. If any of the directories and
| files are changed, Octane will automatically reload your workers.
|
*/
'watch' => [
'app',
'bootstrap',
'config/**/*.php',
'database/**/*.php',
'public/**/*.php',
'resources/**/*.php',
'routes',
'composer.lock',
'.env',
],
/*
|--------------------------------------------------------------------------
| Garbage Collection Threshold
|--------------------------------------------------------------------------
|
| When executing long-lived PHP scripts such as Octane, memory can build
| up before being cleared by PHP. You can force Octane to run garbage
| collection if your application consumes this amount of megabytes.
|
*/
'garbage' => 50,
/*
|--------------------------------------------------------------------------
| Maximum Execution Time
|--------------------------------------------------------------------------
|
| The following setting configures the maximum execution time for requests
| being handled by Octane. You may set this value to 0 to indicate that
| there isn't a specific time limit on Octane request execution time.
|
| Requests may run for up to 300 seconds instead of Octane's default 30.
*/
'max_execution_time' => env('OCTANE_MAX_EXECUTION_TIME', 300),
-129
View File
@@ -1,129 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];
-38
View File
@@ -1,38 +0,0 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];
+11 -205
View File
@@ -2,216 +2,22 @@
use Illuminate\Support\Str;
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Kept from earlier releases, where it differs from the framework's
| "<app>_session": renaming the cookie would sign everyone out. Every
| other key comes from the framework's defaults.
|
*/
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];
+19
View File
@@ -0,0 +1,19 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Upload Chunk Size
|--------------------------------------------------------------------------
|
| The uploader's browser encrypts every file in chunks of this many bytes
| and sends each chunk as a request of its own. The size is written into
| each file's header, so changing it never affects files already stored.
| A reverse proxy in front must accept request bodies a little larger.
|
*/
'chunk_size' => (int) env('UPLOAD_CHUNK_SIZE_MB', 16) * 1024 * 1024,
];
+13
View File
@@ -27,9 +27,22 @@ class ShareFactory extends Factory
'max_downloads' => null,
'download_count' => 0,
'total_size' => 0,
'completed_at' => now(),
];
}
/**
* A share whose files are still being uploaded.
*/
public function pending(): static
{
return $this->state(fn (array $attributes) => [
'encryption_key' => bin2hex(random_bytes(32)),
'encryption_salt' => null,
'completed_at' => null,
]);
}
public function withPassword(string $password = 'secret'): static
{
return $this->state(fn (array $attributes) => [
+14
View File
@@ -25,6 +25,20 @@ class ShareFileFactory extends Factory
'stored_path' => 'shares/'.fake()->uuid().'.enc',
'file_size' => fake()->numberBetween(1024, 10485760),
'mime_type' => 'text/plain',
'uploaded_chunks' => 1,
'completed_at' => now(),
];
}
/**
* A file whose chunks have not all arrived yet.
*/
public function uploading(): static
{
return $this->state(fn (array $attributes) => [
'mime_type' => null,
'uploaded_chunks' => 0,
'completed_at' => null,
]);
}
}
-10
View File
@@ -36,16 +36,6 @@ class UserFactory extends Factory
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
/**
* Indicate that the user is an admin.
*/

Some files were not shown because too many files have changed in this diff Show More