Compare commits
@@ -8,4 +8,6 @@ Before planning or editing, find the row whose globs match the file's path and r
|
|||||||
| resources/css/material-scheme.* | .ai/rules/css.md |
|
| resources/css/material-scheme.* | .ai/rules/css.md |
|
||||||
| resources/views/livewire/share-download.blade.php | .ai/rules/livewire.md |
|
| resources/views/livewire/share-download.blade.php | .ai/rules/livewire.md |
|
||||||
| tests/Screenshots/** | .ai/rules/screenshots.md |
|
| tests/Screenshots/** | .ai/rules/screenshots.md |
|
||||||
|
| app/Services/** | .ai/rules/services.md |
|
||||||
|
| resources/views/** | .ai/rules/views.md |
|
||||||
| website/** | .ai/rules/website.md |
|
| website/** | .ai/rules/website.md |
|
||||||
|
|||||||
@@ -6,4 +6,4 @@ paths:
|
|||||||
# Screenshots
|
# Screenshots
|
||||||
|
|
||||||
## Screenshots come from composer screenshots, before a release
|
## 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; Livewire's temporary-upload cleanup must stay off under the frozen clock or it deletes the selected files; the in-process server's random port is shown as https://files.example.com and the QR redrawn for it; upload_max_filesize/post_max_size are set to 4G by the script so the admin settings hint does not show the machine's PHP limit.
|
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.
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -6,4 +6,4 @@ paths:
|
|||||||
# Website
|
# Website
|
||||||
|
|
||||||
## website/ is the live site, uploaded by hand
|
## 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 (the JSON's top-level light/dark) in resources/css/material-scheme.json — copy them again if indigo is regenerated differently; the site does not follow the admin's colour profile. 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 (it encrypts at rest on the server). Nothing may load from another host except plausible.io. tests/Feature/WebsiteTest.php guards all of this.
|
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.
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
---
|
---
|
||||||
name: infer-conventions
|
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. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."
|
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, API responses), 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
|
license: MIT
|
||||||
metadata:
|
metadata:
|
||||||
author: laravel
|
author: laravel
|
||||||
---
|
---
|
||||||
|
|
||||||
# Infer Conventions
|
# 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.
|
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)
|
## 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.
|
- 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.
|
- 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. Record that against-the-grain hold.
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
@@ -24,11 +25,11 @@ Learn how this application writes Laravel, then record what you learn as durable
|
|||||||
|
|
||||||
Each step ends on a checkable completion criterion. Do not advance until it holds.
|
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.
|
Fan out when you can. The checklist groups are independent, so they can run in 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. Fanning out is much faster on a real app. Without subagents, run the steps in sequence, with the same bar and the same output.
|
||||||
|
|
||||||
### Step 0: Orient
|
### 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.
|
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 candidate for a high-value rule: `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.
|
This app ships a frontend stack, so the frontend checklist group applies. Sweep it.
|
||||||
|
|
||||||
@@ -39,7 +40,7 @@ Done when: you have the applicable checklist groups, the dimensions already reco
|
|||||||
Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:
|
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.
|
- 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.
|
- 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.
|
- 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).
|
- 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.
|
- Tooling-owned or Already-recorded. Skip per the ground rules.
|
||||||
@@ -50,13 +51,13 @@ Done when: every applicable dimension carries exactly one of those verdicts.
|
|||||||
|
|
||||||
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.
|
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.
|
Then find the other patterns specific to this codebase: 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).
|
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
|
### 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.
|
Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Present conflicts 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.
|
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.
|
||||||
|
|
||||||
@@ -64,7 +65,7 @@ Done when: every candidate is approved, rejected, or (conflicts) decided.
|
|||||||
|
|
||||||
### Step 4: Record
|
### 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.
|
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:
|
Record this:
|
||||||
|
|
||||||
@@ -82,23 +83,23 @@ List recorded rules (file and title), conflicts the user deferred, notable no-si
|
|||||||
|
|
||||||
## Glob mapping
|
## 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.
|
Attach each rule to the most specific path that covers its evidence. Do not use `app/**` when a subtree fits. Match the glob to where the code 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:
|
Examples:
|
||||||
|
|
||||||
- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.
|
- 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.
|
- 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.
|
- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app uses.
|
||||||
- Tests: `tests/**`.
|
- Tests: `tests/**`.
|
||||||
- Migrations and database: `database/migrations/**`.
|
- Migrations and database: `database/migrations/**`.
|
||||||
- Truly app-wide (rare, e.g. auth retrieval): `app/**`.
|
- 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.
|
`record-rule` takes one glob. When a convention 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
|
## 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.
|
- 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.
|
- Tiny or fresh app: most dimensions land on no-signal. Say so ("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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
|
|||||||
@@ -1,101 +1,101 @@
|
|||||||
# Detection Checklist
|
# 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`).
|
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.
|
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
|
## A. Validation & HTTP input
|
||||||
|
|
||||||
1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.
|
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`.
|
- 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.
|
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`.
|
- 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.
|
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`.
|
- Hint: grep -- `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.
|
||||||
4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.
|
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`.
|
- Hint: `ls lang`. Grep `function messages`, `function attributes` in `app/Http/Requests`.
|
||||||
|
|
||||||
## B. Controllers & routing
|
## B. Controllers & routing
|
||||||
|
|
||||||
5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.
|
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.
|
- Hint: grep `__invoke` in controllers. `Route::resource` / `apiResource` vs verb routes.
|
||||||
6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.
|
6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.
|
||||||
- Hint: read a few controller methods; `ls app/Actions app/Services`.
|
- Hint: read a few controller methods. `ls app/Actions app/Services`.
|
||||||
7. Route handler style: closures in `routes/*.php` vs controller classes.
|
7. Route handler style: closures in `routes/*.php` vs controller classes.
|
||||||
- Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.
|
- 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.
|
8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.
|
||||||
- Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.
|
- 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`.
|
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`.
|
- 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`.
|
10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.
|
||||||
- Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.
|
- Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.
|
||||||
|
|
||||||
## C. Authorization
|
## C. Authorization
|
||||||
|
|
||||||
11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.
|
11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.
|
||||||
- Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`.
|
- 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.
|
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(`.
|
- Hint: grep -- `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.
|
||||||
|
|
||||||
## D. Eloquent & models
|
## D. Eloquent & models
|
||||||
|
|
||||||
13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.
|
13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.
|
||||||
- Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.
|
- 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.
|
14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, because it goes against the tool's grain.
|
||||||
- Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.
|
- Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.
|
||||||
15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.
|
15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.
|
||||||
- Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`.
|
- 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.
|
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.
|
- 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`).
|
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.
|
- Hint: `ls app/Repositories app/Queries`. See where non-trivial queries are built.
|
||||||
18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.
|
18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.
|
||||||
- Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`.
|
- Hint: grep `function scope` / `#[Scope]` in models. `ls app/*/Builders`.
|
||||||
19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.
|
19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.
|
||||||
- Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`.
|
- 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.
|
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/`.
|
- Hint: grep -- `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.
|
||||||
|
|
||||||
## E. Architecture & organization
|
## 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.
|
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.
|
- 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.
|
22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.
|
||||||
- Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`.
|
- Hint: `ls app/Data`. Grep `extends Data`, `readonly class` in `app/`.
|
||||||
23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.
|
23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.
|
||||||
- Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.
|
- Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.
|
||||||
24. Decoupling: events + listeners vs direct service calls.
|
24. Decoupling: events + listeners vs direct service calls.
|
||||||
- Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`.
|
- Hint: `ls app/Events app/Listeners`. Grep `event(`, `::dispatch(`.
|
||||||
25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).
|
25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).
|
||||||
- Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.
|
- Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.
|
||||||
26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).
|
26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).
|
||||||
- Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.
|
- Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.
|
||||||
27. Enums: backed vs pure; case naming; where they live.
|
27. Enums: backed vs pure, case naming, and where they live.
|
||||||
- Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`.
|
- Hint: `ls app/Enums`. Grep `enum .*: string`, `enum .*: int`.
|
||||||
|
|
||||||
## F. Frontend & views
|
## F. Frontend & views
|
||||||
|
|
||||||
This app ships a frontend stack, so the items below apply.
|
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.
|
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`.
|
- Hint: `composer.json` + `package.json`. `ls resources/js/pages`, `resources/views`.
|
||||||
29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.
|
29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.
|
||||||
- Hint: `ls app/View/Components`; grep `<x-`, `@include` in `resources/views`.
|
- 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.
|
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.
|
- 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')`).
|
32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).
|
||||||
- Hint: `ls lang`; grep dotted `__('` vs sentence keys.
|
- Hint: `ls lang`. Grep dotted `__('` vs sentence keys.
|
||||||
|
|
||||||
## G. Database & migrations
|
## G. Database & migrations
|
||||||
|
|
||||||
33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.
|
33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.
|
||||||
- Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.
|
- Hint: grep -- `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.
|
||||||
34. `down()` methods: real reverse logic vs omitted / one-way migrations.
|
34. `down()` methods: real reverse logic vs omitted / one-way migrations.
|
||||||
- Hint: grep `function down` vs the migration count.
|
- Hint: grep `function down` vs the migration count.
|
||||||
35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.
|
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.
|
- Hint: grep -- `->enum(` in migrations vs string columns cast to enums.
|
||||||
36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.
|
36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.
|
||||||
- Hint: grep `DB::transaction`, `beginTransaction` in `app/`.
|
- Hint: grep `DB::transaction`, `beginTransaction` in `app/`.
|
||||||
37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.
|
37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.
|
||||||
@@ -104,20 +104,20 @@ This app ships a frontend stack, so the items below apply.
|
|||||||
## H. Testing
|
## H. Testing
|
||||||
|
|
||||||
38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.
|
38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.
|
||||||
- Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`.
|
- Hint: `ls tests/Pest.php`. Grep `it(` / `test(` vs `extends TestCase`.
|
||||||
39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.
|
39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.
|
||||||
- Hint: grep those trait names in `tests/`.
|
- 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.
|
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.
|
- 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.
|
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/`.
|
- Hint: grep -- `->mock(`, `->spy(`, `Mockery::` in `tests/`.
|
||||||
42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.
|
42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.
|
||||||
- Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.
|
- Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.
|
||||||
|
|
||||||
## I. Responses & API resources
|
## I. Responses & API resources
|
||||||
|
|
||||||
43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.
|
43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.
|
||||||
- Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.
|
- 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.
|
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`.
|
- 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.
|
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.
|
||||||
@@ -128,11 +128,11 @@ This app ships a frontend stack, so the items below apply.
|
|||||||
## J. Strings, collections & dates
|
## J. Strings, collections & dates
|
||||||
|
|
||||||
47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.
|
47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.
|
||||||
- Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.
|
- 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`).
|
48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).
|
||||||
- Hint: grep `Str::of(` vs `Str::` vs native string funcs.
|
- 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.
|
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.
|
- Hint: grep `now(` and `Carbon::` for call style. Separately inspect `CarbonImmutable` and `Date::use` for mutability policy.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -6,26 +6,26 @@ metadata:
|
|||||||
author: laravel
|
author: laravel
|
||||||
---
|
---
|
||||||
|
|
||||||
# Laravel Best Practices
|
# Laravel best practices
|
||||||
|
|
||||||
Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.
|
Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.
|
||||||
|
|
||||||
## Consistency First
|
## Consistency first
|
||||||
|
|
||||||
Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.
|
Before applying any rule, check what the application already does. Laravel offers several valid approaches. The best choice is the one the codebase already uses, even if another pattern would be better in theory. Inconsistency is worse than a suboptimal pattern.
|
||||||
|
|
||||||
Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
|
Check sibling files and related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.
|
||||||
|
|
||||||
## How to Apply
|
## How to apply
|
||||||
|
|
||||||
1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.
|
1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.
|
||||||
2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.
|
2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.
|
||||||
3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.
|
3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.
|
||||||
4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable.
|
4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when `search-docs` is unavailable.
|
||||||
5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.
|
5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.
|
||||||
6. Re-read the diff against every mapped rule before finishing.
|
6. Re-read the diff against every mapped rule before finishing.
|
||||||
|
|
||||||
## Rule Index
|
## Rule index
|
||||||
|
|
||||||
Cross-cutting changes often need more than one rule file.
|
Cross-cutting changes often need more than one rule file.
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ Cross-cutting changes often need more than one rule file.
|
|||||||
| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |
|
| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |
|
||||||
| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |
|
| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |
|
||||||
|
|
||||||
## Decision Rules
|
## Decision rules
|
||||||
|
|
||||||
- Prefer framework features and existing application abstractions over new helpers or dependencies.
|
- Prefer framework features and existing application abstractions over new helpers or dependencies.
|
||||||
- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.
|
- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Advanced Query Best Practices
|
# Advanced query best practices
|
||||||
|
|
||||||
## Select Single Relationship Values with Subqueries
|
## Select single relationship values with subqueries
|
||||||
|
|
||||||
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.
|
When you need only one value from a has-many relationship, consider a correlated subquery with `addSelect()` instead of loading the entire relationship. The subquery selects the value as part of the main query, without an additional relationship query.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function scopeWithLastLoginAt($query): void
|
public function scopeWithLastLoginAt($query): void
|
||||||
@@ -16,9 +16,9 @@ public function scopeWithLastLoginAt($query): void
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Create Dynamic Relationships with a Subquery Foreign Key
|
## Create dynamic relationships with a subquery foreign key
|
||||||
|
|
||||||
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.
|
The same pattern can select a foreign key and expose the selected model through a `belongsTo` relationship. Eager loading that relationship still runs a separate query, but the pattern avoids loading the full has-many collection.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function lastLogin(): BelongsTo
|
public function lastLogin(): BelongsTo
|
||||||
@@ -37,9 +37,9 @@ public function scopeWithLastLogin($query): void
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Combine Related Counts with Conditional Aggregates
|
## Combine related counts with conditional aggregates
|
||||||
|
|
||||||
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.
|
Use conditional aggregates to combine several counts over the same filtered data set into one query. Use `toBase()` when you need only scalar values and model hydration adds nothing. Confirm the expression syntax against the application's database engine.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$statuses = Feature::toBase()
|
$statuses = Feature::toBase()
|
||||||
@@ -49,18 +49,18 @@ $statuses = Feature::toBase()
|
|||||||
->first();
|
->first();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Reuse Loaded Parent Models with `setRelation()`
|
## Reuse loaded parent models with `setRelation()`
|
||||||
|
|
||||||
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.
|
When a parent and its children are already loaded and code also accesses `$child->parent`, set the inverse relationship to the existing parent instance. Setting the inverse relationship avoids an extra lazy-loading query for each child.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$feature->load('comments.user');
|
$feature->load('comments.user');
|
||||||
$feature->comments->each->setRelation('feature', $feature);
|
$feature->comments->each->setRelation('feature', $feature);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Compare `whereHas()` with an `IN` Subquery
|
## Compare `whereHas()` with an `IN` subquery
|
||||||
|
|
||||||
`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.
|
`whereHas()` typically produces an `EXISTS` subquery, while `whereIn()` can express the same filter with an `IN` subquery. Either form can 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.
|
||||||
|
|
||||||
Option using `EXISTS`:
|
Option using `EXISTS`:
|
||||||
|
|
||||||
@@ -74,13 +74,13 @@ Option using `IN`:
|
|||||||
$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
|
$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id'));
|
||||||
```
|
```
|
||||||
|
|
||||||
## Measure Two Simple Queries Against One Complex Query
|
## Measure two simple queries against one complex query
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Design Composite Indexes for the Query
|
## Design composite indexes for the query
|
||||||
|
|
||||||
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.
|
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 the engine uses the index. Verify the query plan.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
// Migration
|
// Migration
|
||||||
@@ -90,7 +90,7 @@ $table->index(['last_name', 'first_name']);
|
|||||||
User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
|
User::query()->orderBy('last_name')->orderBy('first_name')->paginate();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Consider a Correlated Subquery for Has-Many Ordering
|
## Consider a correlated subquery for has-many ordering
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Architecture Best Practices
|
# Architecture best practices
|
||||||
|
|
||||||
## Extract Focused Business Operations
|
## Extract focused business operations
|
||||||
|
|
||||||
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.
|
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
|
```php
|
||||||
class CreateOrderAction
|
class CreateOrderAction
|
||||||
@@ -19,9 +19,9 @@ class CreateOrderAction
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Inject Required Dependencies
|
## Inject required dependencies
|
||||||
|
|
||||||
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.
|
Prefer constructor injection for dependencies required throughout an object's lifetime. Use method injection for a dependency that one controller action, listener, job handler, or other container-invoked method needs. Avoid `app()` and `resolve()` when normal injection can make a dependency explicit.
|
||||||
|
|
||||||
Hidden dependency:
|
Hidden dependency:
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ class OrderController extends Controller
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Depend on Contracts at Boundaries
|
## Depend on contracts at boundaries
|
||||||
|
|
||||||
Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction.
|
Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction.
|
||||||
|
|
||||||
@@ -82,7 +82,7 @@ Bind in a service provider:
|
|||||||
$this->app->bind(PaymentGateway::class, StripeGateway::class);
|
$this->app->bind(PaymentGateway::class, StripeGateway::class);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Specify a Deterministic Sort Order
|
## Specify a deterministic sort order
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -101,9 +101,9 @@ $posts = Post::query()
|
|||||||
->paginate();
|
->paginate();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use Atomic Locks for Race Conditions
|
## Use atomic locks for race conditions
|
||||||
|
|
||||||
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.
|
Use a lock when concurrent processes must run one at a time. `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. Set the lease (`10` below) longer than the callback can ever run. Once the lease expires, another process can acquire the lock while the first process is still working.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
|
Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) {
|
||||||
@@ -118,7 +118,7 @@ DB::transaction(function () use ($id) {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use `mb_*` String Functions
|
## Use `mb_*` string functions
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -140,9 +140,9 @@ Str::length('José'); // 4
|
|||||||
Str::lower('MÜNCHEN'); // 'münchen'
|
Str::lower('MÜNCHEN'); // 'münchen'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use `defer()` for Post-Response Work
|
## Use `defer()` for post-response work
|
||||||
|
|
||||||
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.
|
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 Laravel sends the response, but it still runs in the same PHP process.
|
||||||
|
|
||||||
Queued and durable:
|
Queued and durable:
|
||||||
|
|
||||||
@@ -158,7 +158,7 @@ defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id
|
|||||||
|
|
||||||
Use a queued job when the work needs retries, queue controls, or durability across process failures.
|
Use a queued job when the work needs retries, queue controls, or durability across process failures.
|
||||||
|
|
||||||
## Use `Context` for Request-Scoped Data
|
## Use `Context` for request-scoped data
|
||||||
|
|
||||||
The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer.
|
The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer.
|
||||||
|
|
||||||
@@ -170,9 +170,9 @@ Context::add('tenant_id', $request->header('X-Tenant-ID'));
|
|||||||
$tenantId = Context::get('tenant_id');
|
$tenantId = Context::get('tenant_id');
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
Laravel adds visible context to log context. It also captures both visible and hidden context and restores them 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 you intend that propagation.
|
||||||
|
|
||||||
## Use `Concurrency::run()` for Parallel Execution
|
## Use `Concurrency::run()` for parallel execution
|
||||||
|
|
||||||
Run independent operations concurrently through Laravel's configured concurrency driver.
|
Run independent operations concurrently through Laravel's configured concurrency driver.
|
||||||
|
|
||||||
@@ -185,9 +185,9 @@ use Illuminate\Support\Facades\Concurrency;
|
|||||||
]);
|
]);
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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 runs closures sequentially and is mainly useful during testing.
|
||||||
|
|
||||||
## Follow Framework Conventions
|
## Follow framework conventions
|
||||||
|
|
||||||
Follow Laravel conventions unless the domain or an existing schema requires an override.
|
Follow Laravel conventions unless the domain or an existing schema requires an override.
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Blade and View Best Practices
|
# Blade and view best practices
|
||||||
|
|
||||||
## Use `$attributes->merge()` in Component Templates
|
## Use `$attributes->merge()` in component templates
|
||||||
|
|
||||||
Use the component attribute bag so callers can add attributes. `merge()` combines default attributes with caller-provided values; class values receive special merging behavior.
|
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
|
```blade
|
||||||
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
|
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
|
||||||
@@ -10,19 +10,19 @@ Use the component attribute bag so callers can add attributes. `merge()` combine
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use `@pushOnce` for Per-Component Scripts
|
## Use `@pushOnce` for per-component scripts
|
||||||
|
|
||||||
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.
|
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 Components for Explicit Interfaces
|
## Prefer components for explicit interfaces
|
||||||
|
|
||||||
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 a Blade component when a reusable interface benefits from explicit props, an attribute bag, or slots. An include still suits a small partial that intentionally uses the current view data. Pass an explicit data array when implicit variable sharing would hide the partial's dependencies.
|
||||||
|
|
||||||
## Share Compatible View Data with a View Composer
|
## Share compatible view data with a view composer
|
||||||
|
|
||||||
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 a view composer to centralize the data that one or more named Blade views need every time Laravel renders them. 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.
|
||||||
|
|
||||||
## Return Blade Fragments for Partial Rendering
|
## Return Blade fragments for partial rendering
|
||||||
|
|
||||||
A route can return either a full view or a named fragment for clients such as htmx or Turbo.
|
A route can return either a full view or a named fragment for clients such as htmx or Turbo.
|
||||||
|
|
||||||
@@ -31,6 +31,6 @@ return view('dashboard', compact('users'))
|
|||||||
->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
|
->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
|
||||||
```
|
```
|
||||||
|
|
||||||
## Share Parent Component Props with `@aware`
|
## Share parent component props with `@aware`
|
||||||
|
|
||||||
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.
|
Use `@aware` when a nested component needs a prop explicitly passed to an ancestor component. `@aware` does not expose an ancestor's default prop value unless that value was passed through the attribute bag.
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
# Caching Best Practices
|
# Caching best practices
|
||||||
|
|
||||||
## Use `Cache::remember()` for Cache-Aside Reads
|
## Use `Cache::remember()` for cache-aside reads
|
||||||
|
|
||||||
`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.
|
`Cache::remember()` implements a cache-aside read without a separate truthiness check. It does not prevent concurrent requests from computing the same missing value. When you must prevent duplicate computation, use an atomic lock.
|
||||||
|
|
||||||
The manual version below incorrectly treats valid falsy values, such as `false` or `0`, as cache misses.
|
The manual version below treats valid falsy values, such as `false` or `0`, as cache misses.
|
||||||
|
|
||||||
Incorrect:
|
Incorrect:
|
||||||
|
|
||||||
@@ -22,9 +22,9 @@ Correct:
|
|||||||
$val = Cache::remember('stats', 60, fn () => $this->computeStats());
|
$val = Cache::remember('stats', 60, fn () => $this->computeStats());
|
||||||
```
|
```
|
||||||
|
|
||||||
## Consider `Cache::flexible()` for Stale-While-Revalidate
|
## Consider `Cache::flexible()` for stale-while-revalidate
|
||||||
|
|
||||||
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.
|
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. The refresh is not a durable background job. After the stale period ends, the request recomputes the value synchronously.
|
||||||
|
|
||||||
Synchronous expiration:
|
Synchronous expiration:
|
||||||
|
|
||||||
@@ -38,11 +38,11 @@ Stale-while-revalidate tradeoff:
|
|||||||
Cache::flexible('users', [300, 600], fn () => User::all());
|
Cache::flexible('users', [300, 600], fn () => User::all());
|
||||||
```
|
```
|
||||||
|
|
||||||
This value is fresh for five minutes and may be served stale until ten minutes after it was cached.
|
In this example, the value is fresh for five minutes. Laravel may serve the stale value until ten minutes after it was cached.
|
||||||
|
|
||||||
## Use `Cache::memo()` to Avoid Redundant Hits Within an Execution
|
## 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.
|
When code reads the same cache key repeatedly during one request or job, `memo()` decorates a cache store and keeps resolved values in memory for that execution.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$settings = Cache::memo()->get('settings');
|
$settings = Cache::memo()->get('settings');
|
||||||
@@ -50,15 +50,15 @@ $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.
|
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
|
## Use cache tags to invalidate related groups
|
||||||
|
|
||||||
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.
|
Tags group related entries for invalidation without tracking each key. The `file`, `dynamodb`, and `database` drivers do not support cache tags. Confirm that a store supports tags before you choose it.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Cache::tags(['user-1'])->flush();
|
Cache::tags(['user-1'])->flush();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use `Cache::add()` for Atomic Conditional Writes
|
## Use `Cache::add()` for atomic conditional writes
|
||||||
|
|
||||||
`add()` atomically writes a value only when the key does not already exist.
|
`add()` atomically writes a value only when the key does not already exist.
|
||||||
|
|
||||||
@@ -76,9 +76,9 @@ Correct:
|
|||||||
Cache::add('lock', true, 10);
|
Cache::add('lock', true, 10);
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `Cache::lock()` rather than an ordinary cache key when lock ownership and safe release are required.
|
When you need lock ownership and safe release, use `Cache::lock()` instead of an ordinary cache key.
|
||||||
|
|
||||||
## Use `once()` for In-Process Memoization
|
## 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.
|
`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.
|
||||||
|
|
||||||
@@ -91,9 +91,9 @@ public function roles(): Collection
|
|||||||
|
|
||||||
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.
|
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
|
## Configure failover cache stores in production
|
||||||
|
|
||||||
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.
|
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 it does not replicate data between stores.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
|
'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']],
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Collection Best Practices
|
# Collection best practices
|
||||||
|
|
||||||
## Use Higher-Order Messages for Simple Operations
|
## Use higher-order messages for simple operations
|
||||||
|
|
||||||
Explicit closure:
|
Explicit closure:
|
||||||
|
|
||||||
@@ -16,11 +16,11 @@ Concise equivalent:
|
|||||||
$users->each->markAsVip();
|
$users->each->markAsVip();
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
Higher-order messages work with supported collection methods such as `each`, `map`, `filter`, and `sum`. Use an explicit closure when arguments or nontrivial logic would be clearer.
|
||||||
|
|
||||||
## Choose Between `cursor()` and `lazy()`
|
## Choose between `cursor()` and `lazy()`
|
||||||
|
|
||||||
`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.
|
`cursor()` executes one query and hydrates one model at a time, but it cannot eager load relationships. The database driver's result buffering can still use a lot of memory for very large results. Use it for low-memory, attribute-only iteration when one long-running query is acceptable.
|
||||||
|
|
||||||
`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.
|
`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.
|
||||||
|
|
||||||
@@ -40,11 +40,11 @@ User::cursor()->each(function (User $user) {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use `lazyById()` When Updating Records While Iterating
|
## Use `lazyById()` when updating records while iterating
|
||||||
|
|
||||||
`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.
|
`lazy()` uses offset pagination, so updating a column that affects the query can shift rows and make the iteration skip records or process them twice. `lazyById()` paginates by a monotonic key and is safer when you update other columns during iteration. Do not change the pagination key itself while iterating.
|
||||||
|
|
||||||
## Use `toQuery()` for Bulk Operations on Collections
|
## Use `toQuery()` for bulk operations on collections
|
||||||
|
|
||||||
Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause.
|
Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause.
|
||||||
|
|
||||||
@@ -60,9 +60,9 @@ Collection query:
|
|||||||
$users->toQuery()->update(['active' => false]);
|
$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.
|
`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 you don't need those events.
|
||||||
|
|
||||||
## Use `#[CollectedBy]` for Custom Collection Classes
|
## Use `#[CollectedBy]` for custom collection classes
|
||||||
|
|
||||||
The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override.
|
The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override.
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Configuration Best Practices
|
# Configuration best practices
|
||||||
|
|
||||||
## Read Environment Variables in Configuration Files
|
## Read environment variables in configuration files
|
||||||
|
|
||||||
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()`.
|
Call `env()` only from configuration files. After you cache the configuration, Laravel does not load the application's `.env` file, so read configuration values in application code through `config()`.
|
||||||
|
|
||||||
Incorrect:
|
Incorrect:
|
||||||
|
|
||||||
@@ -22,16 +22,16 @@ return [
|
|||||||
$key = config('services.key');
|
$key = config('services.key');
|
||||||
```
|
```
|
||||||
|
|
||||||
## Protect Production Secrets
|
## Protect production secrets
|
||||||
|
|
||||||
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.
|
Do not commit plaintext production secrets. Laravel can encrypt an environment file so you can store the encrypted file safely. Deployment platforms can also supply secrets through their native secret stores.
|
||||||
|
|
||||||
Incorrect:
|
Incorrect:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# A plaintext .env file committed to the repository
|
# A plaintext .env file committed to the repository
|
||||||
STRIPE_SECRET=sk_live_abc123
|
STRIPE_SECRET=<your-stripe-secret>
|
||||||
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI
|
AWS_SECRET_ACCESS_KEY=<your-aws-secret>
|
||||||
```
|
```
|
||||||
|
|
||||||
Encrypted environment file:
|
Encrypted environment file:
|
||||||
@@ -43,7 +43,7 @@ php artisan env:decrypt --env=production
|
|||||||
|
|
||||||
For hosted deployments, consider the platform's native secret store, such as AWS Secrets Manager or Vault, and inject secrets 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
|
## Use `App::environment()` for environment checks
|
||||||
|
|
||||||
Incorrect:
|
Incorrect:
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ if (App::environment('production')) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Name Repeated Domain Values
|
## Name repeated domain values
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Database Performance Best Practices
|
# Database performance best practices
|
||||||
|
|
||||||
## Eager Load Relationships Before Iterating
|
## Eager load relationships before iterating
|
||||||
|
|
||||||
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.
|
When code accesses a relationship on many models, eager load the relationship with `with()`. Eager loading avoids the N+1 query pattern: one initial query plus one relationship query per model. Lazy loading is reasonable when the code may not need the relationship or when only one model is involved.
|
||||||
|
|
||||||
Lazy-loaded version:
|
Lazy-loaded version:
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ foreach ($posts as $post) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
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:
|
Constrain an eager load when the code does not need the large columns. 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, and selecting `posts.id` keeps each related model's primary key:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$users = User::with(['posts' => function ($query) {
|
$users = User::with(['posts' => function ($query) {
|
||||||
@@ -33,9 +33,9 @@ $users = User::with(['posts' => function ($query) {
|
|||||||
}])->get();
|
}])->get();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Prevent Lazy Loading in Development
|
## Prevent lazy loading in development
|
||||||
|
|
||||||
Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development.
|
Enable lazy-loading prevention in `AppServiceProvider::boot()` to catch N+1 queries during development.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function boot(): void
|
public function boot(): void
|
||||||
@@ -44,11 +44,11 @@ public function boot(): void
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
By default, accessing an unloaded relationship then throws a `LazyLoadingViolationException`. Applications can customize violation handling with `handleLazyLoadingViolationUsing()`.
|
With prevention enabled, accessing an unloaded relationship throws a `LazyLoadingViolationException` by default. To customize violation handling, use `handleLazyLoadingViolationUsing()`.
|
||||||
|
|
||||||
## Select Only Needed Columns
|
## Select only the columns you need
|
||||||
|
|
||||||
Select only the columns the operation needs when omitting large text, binary, or JSON columns provides a meaningful benefit.
|
When omitting large text, binary, or JSON columns gives a meaningful benefit, select only the columns the operation needs.
|
||||||
|
|
||||||
All columns:
|
All columns:
|
||||||
|
|
||||||
@@ -64,11 +64,11 @@ $posts = Post::select('id', 'title', 'user_id', 'created_at')
|
|||||||
->get();
|
->get();
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
When you limit the selected columns, keep 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.
|
||||||
|
|
||||||
## Process Large Data Sets Incrementally
|
## Process large data sets incrementally
|
||||||
|
|
||||||
Use chunking or lazy iteration when loading an entire result set would exceed the application's practical memory budget.
|
When loading the entire result set would exceed the application's practical memory budget, use chunking or lazy iteration.
|
||||||
|
|
||||||
Loads the complete result set:
|
Loads the complete result set:
|
||||||
|
|
||||||
@@ -89,7 +89,7 @@ User::where('subscribed', true)->chunk(200, function ($users) {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, whose result positions can shift as rows change:
|
Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, so result positions can shift as rows change:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
User::where('active', false)->chunkById(200, function ($users) {
|
User::where('active', false)->chunkById(200, function ($users) {
|
||||||
@@ -97,11 +97,11 @@ User::where('active', false)->chunkById(200, function ($users) {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
For read-only iteration that uses only model attributes, `cursor()` runs one query and hydrates one model at a time. Some database drivers still buffer the raw results. Use `lazy()` when you need to eager load relationships in chunks. Use `lazyById()` or `chunkById()` when updates can change which rows match the query. See the collection rules for detailed tradeoffs.
|
||||||
|
|
||||||
## Add Indexes for Measured Query Patterns
|
## 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.
|
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:
|
Schema without an application-specific query index:
|
||||||
|
|
||||||
@@ -126,11 +126,11 @@ Schema::create('orders', function (Blueprint $table) {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
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 production-like data and the database's query-plan tools to confirm the column order of a composite index and whether the index helps. Before you add an index for a foreign key, check whether the database already created one.
|
||||||
|
|
||||||
## Count Relationships Without Loading Them
|
## Count relationships without loading them
|
||||||
|
|
||||||
Use `withCount()` when only relationship counts are needed; loading and hydrating every related model wastes memory.
|
Use `withCount()` when you need only the relationship counts. Loading and hydrating every related model wastes memory.
|
||||||
|
|
||||||
Loads related models:
|
Loads related models:
|
||||||
|
|
||||||
@@ -161,9 +161,9 @@ $posts = Post::withCount([
|
|||||||
])->get();
|
])->get();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Keep Queries Out of Blade Templates
|
## Keep queries out of Blade templates
|
||||||
|
|
||||||
Prepare data before rendering a Blade template, such as in a controller, query service, or view composer. This keeps query behavior visible and testable.
|
Prepare data before rendering a Blade template, for example in a controller, a query service, or a view composer. Queries outside the template stay visible and testable.
|
||||||
|
|
||||||
Query in the template:
|
Query in the template:
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Eloquent Best Practices
|
# Eloquent best practices
|
||||||
|
|
||||||
## Define Precise Relationship Types
|
## Define precise relationship types
|
||||||
|
|
||||||
Define the relationship that matches the database association, and declare its concrete return type.
|
Define the relationship that matches the database association, and declare its concrete return type.
|
||||||
|
|
||||||
@@ -16,7 +16,7 @@ public function author(): BelongsTo
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use Local Scopes for Reusable Queries
|
## Use local scopes for reusable queries
|
||||||
|
|
||||||
Extract reusable query constraints into local scopes to avoid duplication.
|
Extract reusable query constraints into local scopes to avoid duplication.
|
||||||
|
|
||||||
@@ -43,9 +43,9 @@ $active = User::active()->get();
|
|||||||
$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
|
$articles = Article::whereHas('user', fn ($q) => $q->active())->get();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Apply Global Scopes Sparingly
|
## Apply global scopes sparingly
|
||||||
|
|
||||||
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.
|
A global scope silently modifies every query on the model, so queries become hard to debug. Prefer local scopes, and reserve global scopes for universal constraints such as soft deletes or multi-tenancy.
|
||||||
|
|
||||||
Global scope tradeoff:
|
Global scope tradeoff:
|
||||||
|
|
||||||
@@ -74,9 +74,9 @@ Post::published()->paginate(); // Explicit
|
|||||||
Post::paginate(); // Admin sees all
|
Post::paginate(); // Admin sees all
|
||||||
```
|
```
|
||||||
|
|
||||||
## Define Attribute Casts
|
## Define attribute casts
|
||||||
|
|
||||||
Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion.
|
Use the `casts()` method for automatic type conversion. If the project convention is the `$casts` property, follow that convention.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
@@ -89,7 +89,7 @@ protected function casts(): array
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Cast Date and Time Attributes
|
## Cast date and time attributes
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -115,9 +115,9 @@ protected function casts(): array
|
|||||||
{{ $order->ordered_at->format('m-d') }}
|
{{ $order->ordered_at->format('m-d') }}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use `whereBelongsTo()` for Relationship Queries
|
## Use `whereBelongsTo()` for relationship queries
|
||||||
|
|
||||||
`whereBelongsTo()` expresses the relationship constraint without manually specifying its foreign key.
|
`whereBelongsTo()` expresses the relationship constraint without naming its foreign key.
|
||||||
|
|
||||||
Foreign key constraint:
|
Foreign key constraint:
|
||||||
|
|
||||||
@@ -132,9 +132,9 @@ Post::whereBelongsTo($user)->get();
|
|||||||
Post::whereBelongsTo($user, 'author')->get();
|
Post::whereBelongsTo($user, 'author')->get();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Keep Application Queries Model-Aware
|
## Keep application queries model-aware
|
||||||
|
|
||||||
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.
|
Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL require table names. Use them when you intend their lower-level behavior.
|
||||||
|
|
||||||
Lower-level alternatives:
|
Lower-level alternatives:
|
||||||
|
|
||||||
@@ -153,6 +153,6 @@ User::where('active', true)->get();
|
|||||||
Order::where('status', 'pending')->get();
|
Order::where('status', 'pending')->get();
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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. When the schema can change, cover those table references with tests.
|
||||||
|
|
||||||
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.
|
In migrations, use explicit table names rather than application models. Migrations are historical snapshots, but models and their scopes can change after you deploy a migration.
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Error Handling Best Practices
|
# Error handling best practices
|
||||||
|
|
||||||
## Choose Where to Report and Render Exceptions
|
## Choose where to report and render exceptions
|
||||||
|
|
||||||
Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern already established by the project.
|
Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern the project already uses.
|
||||||
|
|
||||||
Exception methods keep behavior beside the exception definition:
|
Exception methods keep behavior beside the exception definition:
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ Centralized callbacks in `bootstrap/app.php` keep the application's exception po
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Mark Exceptions the Handler Should Not Report
|
## Mark exceptions the handler should not report
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -44,17 +44,17 @@ Implementing `ShouldntReport` prevents Laravel's exception handler from reportin
|
|||||||
class PodcastProcessingException extends Exception implements ShouldntReport {}
|
class PodcastProcessingException extends Exception implements ShouldntReport {}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Throttle High-Volume Exception Reports
|
## Throttle high-volume exception reports
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Prevent Duplicate Reports of One Exception Instance
|
## Prevent duplicate reports of one exception instance
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Define JSON Rendering for API Routes
|
## Define 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.
|
By default, Laravel 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
|
```php
|
||||||
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
|
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
|
||||||
@@ -62,7 +62,7 @@ $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Add Context to Exception Classes
|
## Add context to exception classes
|
||||||
|
|
||||||
Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it.
|
Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it.
|
||||||
|
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
# Events and Notifications Best Practices
|
# Events and notifications best practices
|
||||||
|
|
||||||
## Rely on Event Discovery
|
## Rely on event discovery
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Cache Event Discovery During Production Deployment
|
## Cache event discovery during production deployment
|
||||||
|
|
||||||
Cache discovered listeners during production deployment with `php artisan optimize` or `php artisan event:cache`. Rebuild the cache whenever listener definitions change.
|
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
|
## Use `ShouldDispatchAfterCommit` inside transactions
|
||||||
|
|
||||||
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.
|
When you dispatch an event inside a database transaction, `ShouldDispatchAfterCommit` delays dispatch until all open database transactions commit. If a transaction rolls back, Laravel discards the event. The delay affects synchronous and queued listeners. It is not limited to queue timing.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
class OrderShipped implements ShouldDispatchAfterCommit {}
|
class OrderShipped implements ShouldDispatchAfterCommit {}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Queue Slow Notifications
|
## Queue slow notifications
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -27,19 +27,19 @@ class InvoicePaid extends Notification implements ShouldQueue
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dispatch Queued Notifications After Commit
|
## Dispatch queued notifications after commit
|
||||||
|
|
||||||
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.
|
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. Neither option has a scheduling effect on a synchronous notification.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$user->notify((new InvoicePaid($invoice))->afterCommit());
|
$user->notify((new InvoicePaid($invoice))->afterCommit());
|
||||||
```
|
```
|
||||||
|
|
||||||
## Route Notification Channels to Dedicated Queues
|
## Route notification channels to dedicated queues
|
||||||
|
|
||||||
Different notification channels can have different latency and priority requirements. Implement `viaQueues()` when channels should use 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
|
## Use on-demand notifications for non-user recipients
|
||||||
|
|
||||||
Avoid creating dummy models to send notifications to arbitrary addresses.
|
Avoid creating dummy models to send notifications to arbitrary addresses.
|
||||||
|
|
||||||
@@ -47,6 +47,6 @@ Avoid creating dummy models to send notifications to arbitrary addresses.
|
|||||||
Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
|
Notification::route('mail', 'admin@example.com')->notify(new SystemAlert());
|
||||||
```
|
```
|
||||||
|
|
||||||
## Implement `HasLocalePreference` on Notifiable Models
|
## Implement `HasLocalePreference` on notifiable models
|
||||||
|
|
||||||
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.
|
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,8 +1,8 @@
|
|||||||
# HTTP Client Best Practices
|
# HTTP client best practices
|
||||||
|
|
||||||
## Set Explicit Timeouts
|
## Set explicit timeouts
|
||||||
|
|
||||||
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.
|
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. Retries can multiply the total elapsed time.
|
||||||
|
|
||||||
Less resilient:
|
Less resilient:
|
||||||
|
|
||||||
@@ -31,7 +31,7 @@ Http::macro('github', function () {
|
|||||||
$response = Http::github()->get('/repos/laravel/framework');
|
$response = Http::github()->get('/repos/laravel/framework');
|
||||||
```
|
```
|
||||||
|
|
||||||
## Retry Only Safe Operations
|
## Retry only safe operations
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -69,9 +69,9 @@ $response = Http::withHeaders(['Idempotency-Key' => $paymentAttempt->uuid])
|
|||||||
->post('https://api.example.com/v1/charges', $data);
|
->post('https://api.example.com/v1/charges', $data);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Handle Errors Explicitly
|
## Handle errors explicitly
|
||||||
|
|
||||||
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.
|
By default, the HTTP client returns responses for `4xx` and `5xx` status codes instead of throwing. Inspect the expected statuses or call `throw()` before consuming a success payload.
|
||||||
|
|
||||||
Unsafe when a success payload is expected:
|
Unsafe when a success payload is expected:
|
||||||
|
|
||||||
@@ -89,7 +89,7 @@ $user = Http::connectTimeout(3)
|
|||||||
->json();
|
->json();
|
||||||
```
|
```
|
||||||
|
|
||||||
Handle expected alternatives explicitly when graceful degradation is required:
|
When graceful degradation is required, handle expected alternatives explicitly:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$response = Http::connectTimeout(3)
|
$response = Http::connectTimeout(3)
|
||||||
@@ -107,9 +107,9 @@ if ($response->notFound()) {
|
|||||||
$response->throw();
|
$response->throw();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Pool Independent Requests
|
## Pool independent requests
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
use Illuminate\Http\Client\Pool;
|
use Illuminate\Http\Client\Pool;
|
||||||
@@ -125,7 +125,7 @@ $users = $responses['users']->throw()->json();
|
|||||||
$posts = $responses['posts']->throw()->json();
|
$posts = $responses['posts']->throw()->json();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Fake HTTP Requests in Tests
|
## Fake HTTP requests in tests
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -148,7 +148,7 @@ it('syncs a user from the API', function () {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
For example, fake a connection failure when testing the integration's failure path:
|
For example, to test the integration's failure path, fake a connection failure:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Http::fake([
|
Http::fake([
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Mail Best Practices
|
# Mail best practices
|
||||||
|
|
||||||
## Queue Slow Mail Delivery
|
## Queue slow mail delivery
|
||||||
|
|
||||||
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()`.
|
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()`.
|
||||||
|
|
||||||
@@ -13,9 +13,9 @@ class OrderShipped extends Mailable implements ShouldQueue
|
|||||||
|
|
||||||
Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available.
|
Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available.
|
||||||
|
|
||||||
## Dispatch Queued Mail After Commit
|
## Dispatch queued mail after commit
|
||||||
|
|
||||||
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.
|
A queue worker can process a queued mailable dispatched during a database transaction 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.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Mail::to($user)->send(
|
Mail::to($user)->send(
|
||||||
@@ -23,9 +23,9 @@ Mail::to($user)->send(
|
|||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
If the transaction rolls back, an after-commit mailable is not dispatched. This setting affects queued mail only; it does not defer synchronous delivery.
|
If the transaction rolls back, Laravel does not dispatch an after-commit mailable. The after-commit setting affects only queued mail. It does not defer synchronous delivery.
|
||||||
|
|
||||||
## Assert the Delivery Mode
|
## Assert the delivery mode
|
||||||
|
|
||||||
Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables.
|
Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables.
|
||||||
|
|
||||||
@@ -41,14 +41,14 @@ Correct:
|
|||||||
Mail::assertQueued(OrderShipped::class);
|
Mail::assertQueued(OrderShipped::class);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use Markdown Mailables When They Fit
|
## 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.
|
Markdown mailables render HTML and plain-text versions from Laravel's mail components and support publishable themes. They suit conventional transactional messages. A custom HTML and text pair may fit a specialized design better.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
php artisan make:mail OrderShipped --markdown=mail.orders.shipped
|
php artisan make:mail OrderShipped --markdown=mail.orders.shipped
|
||||||
```
|
```
|
||||||
|
|
||||||
## Separate Content and Delivery Tests
|
## 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.
|
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.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Migration Best Practices
|
# Migration best practices
|
||||||
|
|
||||||
## Generate Migrations with Artisan
|
## Generate migrations with Artisan
|
||||||
|
|
||||||
Use `php artisan make:migration` to generate the timestamped filename and migration structure.
|
Use `php artisan make:migration` to generate the timestamped filename and migration structure.
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ php artisan make:migration create_posts_table
|
|||||||
php artisan make:migration add_slug_to_posts_table
|
php artisan make:migration add_slug_to_posts_table
|
||||||
```
|
```
|
||||||
|
|
||||||
## Define Foreign-Key Constraints Deliberately
|
## Define foreign-key constraints deliberately
|
||||||
|
|
||||||
Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not.
|
Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not.
|
||||||
|
|
||||||
@@ -20,19 +20,19 @@ $table->foreignId('author_id')->constrained('users');
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Treat Deployed Migrations as Immutable
|
## 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.
|
After a migration has run in a shared or production environment, create a new migration for later 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.
|
For a local migration that has not been shared or deployed, editing and rerunning it may be simpler.
|
||||||
|
|
||||||
## Design Indexes for Real Queries
|
## 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.
|
Add indexes based on query patterns, selectivity, write cost, and the database's ability to use composite indexes. A column that appears 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.
|
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. 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
|
## 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.
|
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.
|
||||||
|
|
||||||
@@ -42,11 +42,11 @@ Do not assume this migration is safe on a populated table:
|
|||||||
$table->string('slug')->unique();
|
$table->string('slug')->unique();
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
Large backfills usually work better as an observable, restartable command or job than inside a schema migration. Small deterministic data changes may be reasonable in a migration when you understand their locking, transaction, and deployment behavior.
|
||||||
|
|
||||||
## Mirror Defaults Only When Unsaved Models Need Them
|
## Mirror defaults only when unsaved models need them
|
||||||
|
|
||||||
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.
|
The database applies a default when it inserts a row, not when you instantiate a model. Mirror the value in the model's `$attributes` only when application code must observe that default before persistence, and keep both definitions in sync.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
// Migration
|
// Migration
|
||||||
@@ -58,10 +58,10 @@ protected $attributes = [
|
|||||||
];
|
];
|
||||||
```
|
```
|
||||||
|
|
||||||
## Make Rollbacks Honest
|
## Make rollbacks honest
|
||||||
|
|
||||||
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.
|
Implement `down()` when you can safely reverse the change. 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
|
## Keep migrations focused
|
||||||
|
|
||||||
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.
|
Keep each migration small enough to reason about, deploy, and reverse. Separate long-running backfills from schema changes when the split reduces locks and supports phased deployment. Do not split related operations only to enforce a blanket separation between data definition and data manipulation.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Queue and Job Best Practices
|
# Queue and job best practices
|
||||||
|
|
||||||
## Keep Reservation Time Longer Than Execution Time
|
## Keep reservation time longer than execution time
|
||||||
|
|
||||||
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`.
|
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`.
|
||||||
|
|
||||||
@@ -12,9 +12,9 @@ public $timeout = 120;
|
|||||||
'retry_after' => 150,
|
'retry_after' => 150,
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Back Off Transient Failures
|
## Back off transient failures
|
||||||
|
|
||||||
Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures.
|
Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures.
|
||||||
|
|
||||||
@@ -29,9 +29,9 @@ class SyncWithStripe implements ShouldQueue
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Use Unique Jobs for Dispatch Deduplication
|
## 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.
|
Implement `ShouldBeUnique` when only one queued instance of a logical job should exist. Uniqueness uses a cache lock. It does not replace idempotent processing or a database constraint.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
class GenerateInvoice implements ShouldQueue, ShouldBeUnique
|
class GenerateInvoice implements ShouldQueue, ShouldBeUnique
|
||||||
@@ -47,7 +47,7 @@ class GenerateInvoice implements ShouldQueue, ShouldBeUnique
|
|||||||
|
|
||||||
All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches.
|
All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches.
|
||||||
|
|
||||||
Use `ShouldBeUniqueUntilProcessing` only when the lock should be released immediately before processing begins, allowing another instance to be dispatched while the first is running:
|
Use `ShouldBeUniqueUntilProcessing` only when the lock should release immediately before processing begins. Another instance can then be dispatched while the first is running:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
|
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
|
||||||
@@ -56,11 +56,11 @@ class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Handle Terminal Failure When Needed
|
## 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.
|
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.
|
Laravel invokes `failed()` on a new job instance, so changes made to the job during `handle()` are not available in `failed()`.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function failed(?Throwable $exception): void
|
public function failed(?Throwable $exception): void
|
||||||
@@ -74,7 +74,7 @@ public function failed(?Throwable $exception): void
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Rate Limit External Calls
|
## Rate limit external calls
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -85,9 +85,9 @@ public function middleware(): array
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Batch Jobs for Group Coordination
|
## Batch jobs for group coordination
|
||||||
|
|
||||||
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.
|
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. Laravel does not roll back completed jobs when another job fails. By default, one failed job cancels the batch. Call `allowFailures()` only when partial failure is acceptable.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Bus::batch([
|
Bus::batch([
|
||||||
@@ -101,9 +101,9 @@ Bus::batch([
|
|||||||
->dispatch();
|
->dispatch();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configure Time-Based Retry Limits Deliberately
|
## Configure time-based retry limits deliberately
|
||||||
|
|
||||||
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.
|
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. `retryUntil()` takes precedence over attempt-based limits, so you do not need to set `$tries = 0`.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function retryUntil(): DateTimeInterface
|
public function retryUntil(): DateTimeInterface
|
||||||
@@ -112,6 +112,6 @@ public function retryUntil(): DateTimeInterface
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use Horizon for Redis Queue Operations
|
## Use Horizon for Redis queue operations
|
||||||
|
|
||||||
Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers.
|
Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Routing and Controller Best Practices
|
# Routing and controller best practices
|
||||||
|
|
||||||
## Use Implicit Route Model Binding
|
## Use implicit route model binding
|
||||||
|
|
||||||
Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint.
|
Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint.
|
||||||
|
|
||||||
@@ -24,9 +24,9 @@ public function show(Post $post): View
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Scope Nested Bindings
|
## Scope nested bindings
|
||||||
|
|
||||||
Use scoped bindings when a nested resource must belong to its parent. This constrains model resolution; it does not replace authorization.
|
Use scoped bindings when a nested resource must belong to its parent. Scoped bindings constrain model resolution. They do not replace authorization.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
|
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
|
||||||
@@ -34,7 +34,7 @@ Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
|
|||||||
})->scopeBindings();
|
})->scopeBindings();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use Resource Routes for Resourceful Actions
|
## Use resource routes for resourceful actions
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -45,11 +45,11 @@ Route::resource('posts', PostController::class);
|
|||||||
Route::apiResource('posts', ApiPostController::class);
|
Route::apiResource('posts', ApiPostController::class);
|
||||||
```
|
```
|
||||||
|
|
||||||
`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.
|
`apiResource()` omits the HTML-oriented `create` and `edit` routes. It does not add an `/api` prefix. That prefix comes from the application's API route configuration.
|
||||||
|
|
||||||
## Organize Controllers Around Resources
|
## 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.
|
By default, organize each controller around one resource and use Laravel's standard resource actions: `index`, `show`, `create`, `store`, `edit`, `update`, and `destroy`. This convention 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.
|
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.
|
||||||
|
|
||||||
@@ -90,9 +90,9 @@ class PublishedPodcastController extends Controller
|
|||||||
|
|
||||||
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.
|
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
|
## 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.
|
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 only to satisfy an arbitrary line limit.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse
|
public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse
|
||||||
@@ -103,4 +103,4 @@ public function store(StorePostRequest $request, CreatePostAction $create): Redi
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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 details.
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Task Scheduling Best Practices
|
# Task scheduling best practices
|
||||||
|
|
||||||
## Prevent Unwanted Overlap
|
## Prevent unwanted overlap
|
||||||
|
|
||||||
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.
|
Use `withoutOverlapping()` when a second run must not begin while the previous run holds the lock. Use it for variable-duration tasks that are not safe to run concurrently.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Schedule::command('reports:generate')
|
Schedule::command('reports:generate')
|
||||||
@@ -10,9 +10,9 @@ Schedule::command('reports:generate')
|
|||||||
->withoutOverlapping(30);
|
->withoutOverlapping(30);
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
The optional value is the lock expiration time in minutes, not the task timeout. Choose the value carefully. The default is 24 hours, and an expiration that is too short can permit overlap while the first task still runs. Clear stale locks with `php artisan schedule:clear-cache`. The task itself should still tolerate retries and partial execution where practical.
|
||||||
|
|
||||||
## Run a Task on One Server
|
## Run a task on one server
|
||||||
|
|
||||||
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`.
|
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`.
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ 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.
|
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
|
## 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.
|
Tasks due at the same time run sequentially by default. Use `runInBackground()` when an independent, long-running scheduled command should not delay later tasks.
|
||||||
|
|
||||||
@@ -30,11 +30,11 @@ Tasks due at the same time run sequentially by default. Use `runInBackground()`
|
|||||||
Schedule::command('analytics:process')->hourly()->runInBackground();
|
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.
|
Laravel restricts `runInBackground()` to tasks scheduled with `command()` and `exec()`. It is not available for scheduled closures. Give background processes logging and failure monitoring.
|
||||||
|
|
||||||
## Restrict Tasks by Environment
|
## 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.
|
Use `environments()` when a task should run only in named application environments. Treat `environments()` as an operational safeguard, not an authorization control.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Schedule::command('billing:charge')
|
Schedule::command('billing:charge')
|
||||||
@@ -42,9 +42,9 @@ Schedule::command('billing:charge')
|
|||||||
->environments(['production']);
|
->environments(['production']);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Group Shared Configuration
|
## Group shared configuration
|
||||||
|
|
||||||
Use schedule groups when several tasks genuinely share frequency or constraints.
|
Use schedule groups when several tasks share frequency or constraints.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Schedule::daily()
|
Schedule::daily()
|
||||||
@@ -56,6 +56,6 @@ Schedule::daily()
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Bound Work Inside the Task
|
## 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.
|
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,8 +1,8 @@
|
|||||||
# Security Best Practices
|
# Security best practices
|
||||||
|
|
||||||
## Control Mass Assignment
|
## Control mass assignment
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
class User extends Model
|
class User extends Model
|
||||||
@@ -15,9 +15,9 @@ class User extends Model
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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 Protected Actions
|
## Authorize protected actions
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -43,9 +43,9 @@ public function authorize(): bool
|
|||||||
|
|
||||||
Public actions intentionally available to everyone do not need a redundant authorization check.
|
Public actions intentionally available to everyone do not need a redundant authorization check.
|
||||||
|
|
||||||
## Bind Query Parameters
|
## 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.
|
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:
|
Incorrect:
|
||||||
|
|
||||||
@@ -60,9 +60,9 @@ User::where('name', $request->name)->get();
|
|||||||
User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();
|
User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Escape Output in Its Context
|
## Escape output in its context
|
||||||
|
|
||||||
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.
|
Blade's `{{ }}` syntax HTML-escapes output. Use `{!! !!}` only for content sanitized for the exact HTML context where it renders. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets.
|
||||||
|
|
||||||
Incorrect for untrusted content:
|
Incorrect for untrusted content:
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ Correct:
|
|||||||
{{ $user->bio }}
|
{{ $user->bio }}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Apply Cross-Site Request Forgery Protection
|
## Apply cross-site request forgery protection
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -87,11 +87,11 @@ Include `@csrf` in state-changing Blade forms handled by Laravel's `web` middlew
|
|||||||
</form>
|
</form>
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. When you use another HTTP client, confirm equivalent configuration. Do not disable CSRF protection only to fix a token mismatch.
|
||||||
|
|
||||||
## Rate Limit Sensitive Endpoints
|
## 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.
|
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. An account identifier alone can enable targeted denial of service.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
RateLimiter::for('login', function (Request $request) {
|
RateLimiter::for('login', function (Request $request) {
|
||||||
@@ -103,11 +103,11 @@ RateLimiter::for('login', function (Request $request) {
|
|||||||
Route::post('/login', LoginController::class)->middleware('throttle:login');
|
Route::post('/login', LoginController::class)->middleware('throttle:login');
|
||||||
```
|
```
|
||||||
|
|
||||||
Rate limiting reduces abuse; it does not replace authentication, authorization, or upstream denial-of-service protection.
|
Rate limiting reduces abuse. It does not replace authentication, authorization, or upstream denial-of-service protection.
|
||||||
|
|
||||||
## Validate and Store Uploads Safely
|
## 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.
|
Validate the expected content type, the size, and the dimensions where relevant. 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. Do not use it by itself.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
@@ -124,11 +124,11 @@ Use Laravel's storage methods to generate a filename, and store untrusted files
|
|||||||
$path = $request->file('avatar')->store('avatars');
|
$path = $request->file('avatar')->store('avatars');
|
||||||
```
|
```
|
||||||
|
|
||||||
## Keep Secrets Out of Application Code
|
## Keep secrets out of application code
|
||||||
|
|
||||||
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.
|
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. See the configuration rules for encrypted environment files and external secret stores.
|
||||||
|
|
||||||
## Audit Dependencies
|
## Audit dependencies
|
||||||
|
|
||||||
Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.
|
Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly.
|
||||||
|
|
||||||
@@ -136,9 +136,9 @@ Run `composer audit` regularly and in continuous integration. Review findings fo
|
|||||||
composer audit
|
composer audit
|
||||||
```
|
```
|
||||||
|
|
||||||
## Encrypt Sensitive Attributes When Appropriate
|
## Encrypt sensitive attributes when appropriate
|
||||||
|
|
||||||
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.
|
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. You cannot meaningfully query encrypted values. Store them in a `TEXT` or larger column because ciphertext length varies.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
class Integration extends Model
|
class Integration extends Model
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Convention and Style Best Practices
|
# Convention and style best practices
|
||||||
|
|
||||||
## Follow Project Naming Conventions
|
## Follow project naming conventions
|
||||||
|
|
||||||
Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.
|
Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile.
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ Prefer Laravel's conventions in new code, but preserve an established project co
|
|||||||
| Column | snake_case | `meta_title` |
|
| Column | snake_case | `meta_title` |
|
||||||
| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` |
|
| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` |
|
||||||
| Resource URI | Plural resource | `articles/1` |
|
| Resource URI | Plural resource | `articles/1` |
|
||||||
| Route name | Dotted segments; snake_case within a segment when needed | `users.show_active` |
|
| Route name | Dotted segments, with snake_case within a segment when needed | `users.show_active` |
|
||||||
| Method | camelCase | `getAll` |
|
| Method | camelCase | `getAll` |
|
||||||
| Variable | camelCase | `$articlesWithAuthor` |
|
| Variable | camelCase | `$articlesWithAuthor` |
|
||||||
| Collection | Descriptive and plural | `$activeUsers` |
|
| Collection | Descriptive and plural | `$activeUsers` |
|
||||||
@@ -22,7 +22,7 @@ Prefer Laravel's conventions in new code, but preserve an established project co
|
|||||||
| Configuration file | snake_case | `google_calendar.php` |
|
| Configuration file | snake_case | `google_calendar.php` |
|
||||||
| Enumeration | Singular StudlyCase | `UserType` |
|
| Enumeration | Singular StudlyCase | `UserType` |
|
||||||
|
|
||||||
## Prefer Clear, Idiomatic Syntax
|
## 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.
|
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.
|
||||||
|
|
||||||
@@ -39,9 +39,9 @@ Use Laravel helpers and query methods when they communicate intent more directly
|
|||||||
|
|
||||||
Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation.
|
Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation.
|
||||||
|
|
||||||
## Use Utilities When They Clarify Intent
|
## 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.
|
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 a replacement for every built-in function.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$slug = Str::slug($title);
|
$slug = Str::slug($title);
|
||||||
@@ -57,7 +57,7 @@ $name = Arr::get($array, 'user.name', 'default');
|
|||||||
$public = Arr::only($attributes, ['name', 'email']);
|
$public = Arr::only($attributes, ['name', 'email']);
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `Number` for localized display formatting rather than values that will be stored or calculated:
|
Use `Number` for localized display formatting, not for values you store or calculate:
|
||||||
|
|
||||||
```php
|
```php
|
||||||
Number::format(1000000);
|
Number::format(1000000);
|
||||||
@@ -65,20 +65,20 @@ Number::currency(1500, 'USD');
|
|||||||
Number::fileSize(1024 * 1024);
|
Number::fileSize(1024 * 1024);
|
||||||
```
|
```
|
||||||
|
|
||||||
Use `Uri` when constructing or transforming a uniform resource identifier (URI) benefits from a structured API:
|
Use `Uri` when a structured API helps you build or transform a uniform resource identifier (URI):
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$uri = Uri::of('https://example.com/search')
|
$uri = Uri::of('https://example.com/search')
|
||||||
->withQuery(['q' => 'laravel', 'page' => 1]);
|
->withQuery(['q' => 'laravel', 'page' => 1]);
|
||||||
```
|
```
|
||||||
|
|
||||||
Check the documentation for the Laravel version supported by the project before using newer utility classes or methods.
|
Before using newer utility classes or methods, check the documentation for the project's Laravel version.
|
||||||
|
|
||||||
## Keep Presentation Code Maintainable
|
## Keep presentation code maintainable
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
Pass server data with an encoding mechanism appropriate to its context. For example, Blade's `Js::from()` safely formats data for JavaScript:
|
Pass server data with an encoding that fits its context. For example, Blade's `Js::from()` safely formats data for JavaScript:
|
||||||
|
|
||||||
```blade
|
```blade
|
||||||
<script>
|
<script>
|
||||||
@@ -88,9 +88,9 @@ Pass server data with an encoding mechanism appropriate to its context. For exam
|
|||||||
|
|
||||||
Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.
|
Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping.
|
||||||
|
|
||||||
## Write Comments That Explain Why
|
## Write comments that explain why
|
||||||
|
|
||||||
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.
|
Prefer clear names and small units of code over comments that 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.
|
||||||
|
|
||||||
Unhelpful:
|
Unhelpful:
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Validation and Forms Best Practices
|
# Validation and forms best practices
|
||||||
|
|
||||||
## Extract Validation When It Improves the Boundary
|
## Extract validation when it improves the boundary
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -13,11 +13,11 @@ public function store(StorePostRequest $request): RedirectResponse
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
A form request's `authorize()` method can enforce access to the operation. Validation checks the shape and values of the input. Validation alone does not authorize the user.
|
||||||
|
|
||||||
## Prefer Readable Rule Syntax
|
## Prefer readable rule syntax
|
||||||
|
|
||||||
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.
|
Array syntax combines with rule objects and avoids delimiter problems. Prefer array syntax in new code when it improves readability, and keep the local style consistent.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
'email' => ['required', 'email', Rule::unique('users')],
|
'email' => ['required', 'email', Rule::unique('users')],
|
||||||
@@ -29,9 +29,9 @@ String syntax remains valid for simple rules:
|
|||||||
'email' => 'required|email|unique:users',
|
'email' => 'required|email|unique:users',
|
||||||
```
|
```
|
||||||
|
|
||||||
## Use Only Intended Validated Data
|
## Use only the validated data you intend
|
||||||
|
|
||||||
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.
|
Use `validated()` or `safe()` instead of `$request->all()` when passing request data onward. When the validation rules also cover control fields or nested data, select only the fields intended for the operation.
|
||||||
|
|
||||||
Unsafe:
|
Unsafe:
|
||||||
|
|
||||||
@@ -45,9 +45,9 @@ Preferred:
|
|||||||
$post = Post::create($request->safe()->only(['title', 'body']));
|
$post = Post::create($request->safe()->only(['title', 'body']));
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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 only to make mass assignment convenient.
|
||||||
|
|
||||||
## Express Conditional Rules Clearly
|
## 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.
|
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.
|
||||||
|
|
||||||
@@ -63,9 +63,9 @@ Use conditional rules such as `Rule::when()`, `required_if`, or `exclude_unless`
|
|||||||
],
|
],
|
||||||
```
|
```
|
||||||
|
|
||||||
## Add Cross-Field Validation After Base Rules
|
## Add cross-field validation after base rules
|
||||||
|
|
||||||
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.
|
Use a form request's `after()` method for validation that depends on multiple fields or application state. Skip expensive queries when prerequisite fields already failed validation.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
public function after(): array
|
public function after(): array
|
||||||
|
|||||||
@@ -6,15 +6,15 @@ metadata:
|
|||||||
author: laravel
|
author: laravel
|
||||||
---
|
---
|
||||||
|
|
||||||
# Livewire Development
|
# Livewire development
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
Use `search-docs` for detailed Livewire 4 patterns and documentation.
|
Use `search-docs` for detailed Livewire 4 patterns and documentation.
|
||||||
|
|
||||||
## Basic Usage
|
## Basic usage
|
||||||
|
|
||||||
### Creating Components
|
### Creating components
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Single-file component (SFC - default in v4)
|
# Single-file component (SFC - default in v4)
|
||||||
@@ -38,17 +38,17 @@ php artisan make:livewire create-post --class
|
|||||||
php artisan make:livewire Posts/CreatePost
|
php artisan make:livewire Posts/CreatePost
|
||||||
```
|
```
|
||||||
|
|
||||||
### Converting Between Formats
|
### Converting between formats
|
||||||
|
|
||||||
Use `php artisan livewire:convert create-post` to convert between single-file, multi-file, and class-based formats.
|
Use `php artisan livewire:convert create-post` to convert between single-file, multi-file, and class-based formats.
|
||||||
|
|
||||||
### Choosing a Component Format
|
### Choosing a component format
|
||||||
|
|
||||||
> **Always follow the project's existing conventions first.** Before creating any component, inspect the project's existing Livewire components to determine the established format (SFC, MFC, or class-based) and directory structure. Check `app/Livewire/`, `resources/views/components/`, and `resources/views/livewire/` for existing components. If the project already uses a consistent format, **use that same format** — even if it differs from the Livewire v4 defaults below. Only fall back to the v4 defaults (SFC in `resources/views/components/`) when no existing convention is established.
|
> **Always follow the project's existing conventions first.** Before creating any component, inspect the project's existing Livewire components to find the established format (SFC, MFC, or class-based) and directory structure. Check `app/Livewire/`, `resources/views/components/`, and `resources/views/livewire/` for existing components. If the project already uses a consistent format, **use that same format**, even if it differs from the Livewire v4 defaults below. Fall back to the v4 defaults (SFC in `resources/views/components/`) only when the project has no established convention.
|
||||||
|
|
||||||
Also check `config/livewire.php` for `make_command.type`, `make_command.emoji`, `component_locations`, and `component_namespaces` overrides, which change the default format and where files are stored.
|
Also check `config/livewire.php` for `make_command.type`, `make_command.emoji`, `component_locations`, and `component_namespaces` overrides, which change the default format and where Livewire stores files.
|
||||||
|
|
||||||
### Component Format Reference
|
### Component format reference
|
||||||
|
|
||||||
| Format | Flag | Class Path | View Path |
|
| Format | Flag | Class Path | View Path |
|
||||||
|--------|------|------------|-----------|
|
|--------|------|------------|-----------|
|
||||||
@@ -58,11 +58,11 @@ Also check `config/livewire.php` for `make_command.type`, `make_command.emoji`,
|
|||||||
| Class-based | `--class` | `app/Livewire/CreatePost.php` | `resources/views/livewire/create-post.blade.php` |
|
| Class-based | `--class` | `app/Livewire/CreatePost.php` | `resources/views/livewire/create-post.blade.php` |
|
||||||
| View-based | default (Blade-only) | — | `resources/views/components/⚡create-post.blade.php` (Blade-only with functional state) |
|
| View-based | default (Blade-only) | — | `resources/views/components/⚡create-post.blade.php` (Blade-only with functional state) |
|
||||||
|
|
||||||
> **Important:** The ⚡ prefix shown above is the **default** behavior in Livewire v4 — it is **configurable**. Check `config/livewire.php` for the `make_command.emoji` setting. When `true` (default), always include the ⚡ prefix in filenames you create. When `false`, omit the ⚡ prefix from all paths above.
|
> **Important:** The ⚡ prefix shown above is the **default** behavior in Livewire v4. It is **configurable**. Check `config/livewire.php` for the `make_command.emoji` setting. When the setting is `true` (the default), always include the ⚡ prefix in filenames you create. When `false`, omit the ⚡ prefix from all paths above.
|
||||||
|
|
||||||
Namespaced components map to subdirectories: `make:livewire Posts/CreatePost` creates `resources/views/components/posts/⚡create-post.blade.php` (single-file by default). Use `make:livewire Posts/CreatePost --mfc` for multi-file output at `resources/views/components/posts/⚡create-post/create-post.php` and `resources/views/components/posts/⚡create-post/create-post.blade.php`.
|
Namespaced components map to subdirectories: `make:livewire Posts/CreatePost` creates `resources/views/components/posts/⚡create-post.blade.php` (single-file by default). Use `make:livewire Posts/CreatePost --mfc` for multi-file output at `resources/views/components/posts/⚡create-post/create-post.php` and `resources/views/components/posts/⚡create-post/create-post.blade.php`.
|
||||||
|
|
||||||
### Single-File Component Example
|
### Single-file component example
|
||||||
|
|
||||||
<!-- Single-File Component Example -->
|
<!-- Single-File Component Example -->
|
||||||
```php
|
```php
|
||||||
@@ -84,22 +84,22 @@ new class extends Component {
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
## Livewire 4 Specifics
|
## Livewire 4 specifics
|
||||||
|
|
||||||
### Key Changes From Livewire 3
|
### Key changes from Livewire 3
|
||||||
|
|
||||||
These things changed in Livewire 4, but may not have been updated in this application. Verify this application's setup to ensure you follow existing conventions.
|
These things changed in Livewire 4, but this application may not use them yet. Check the application's setup and follow its existing conventions.
|
||||||
|
|
||||||
- Use `Route::livewire()` for full-page components (e.g., `Route::livewire('/posts/create', CreatePost::class)`); config keys renamed: `layout` → `component_layout`, `lazy_placeholder` → `component_placeholder`.
|
- For full-page components, use `Route::livewire()`, for example `Route::livewire('/posts/create', CreatePost::class)`. Config keys are renamed: `layout` is now `component_layout`, and `lazy_placeholder` is now `component_placeholder`.
|
||||||
- `wire:model` now ignores child events by default (use `wire:model.deep` for old behavior); `wire:scroll` renamed to `wire:navigate:scroll`.
|
- `wire:model` now ignores child events by default. For the old behavior, use `wire:model.deep`. `wire:scroll` is renamed to `wire:navigate:scroll`.
|
||||||
- Component tags must be properly closed; `wire:transition` now uses View Transitions API (modifiers removed).
|
- Component tags must be properly closed. `wire:transition` now uses the View Transitions API, and its modifiers are removed.
|
||||||
- JavaScript: `$wire.$js('name', fn)` → `$wire.$js.name = fn`; `commit`/`request` hooks → `interceptMessage()`/`interceptRequest()`.
|
- In JavaScript, `$wire.$js('name', fn)` becomes `$wire.$js.name = fn`, and the `commit` and `request` hooks become `interceptMessage()` and `interceptRequest()`.
|
||||||
|
|
||||||
### New Features
|
### New features
|
||||||
|
|
||||||
- Component formats: single-file (SFC), multi-file (MFC), view-based components.
|
- Component formats: single-file (SFC), multi-file (MFC), and view-based components.
|
||||||
- Islands (`@island`) for isolated updates; async actions (`wire:click.async`, `#[Async]`) for parallel execution.
|
- Islands (`@island`) for isolated updates. Async actions (`wire:click.async`, `#[Async]`) for parallel execution.
|
||||||
- Deferred/bundled loading: `defer`, `lazy.bundle` for optimized component loading.
|
- Deferred and bundled component loading with `defer` and `lazy.bundle`.
|
||||||
|
|
||||||
| Feature | Usage | Purpose |
|
| Feature | Usage | Purpose |
|
||||||
|---------|-------|---------|
|
|---------|-------|---------|
|
||||||
@@ -108,10 +108,10 @@ These things changed in Livewire 4, but may not have been updated in this applic
|
|||||||
| Deferred | `defer` attribute | Load after page render |
|
| Deferred | `defer` attribute | Load after page render |
|
||||||
| Bundled | `lazy.bundle` | Load multiple together |
|
| Bundled | `lazy.bundle` | Load multiple together |
|
||||||
|
|
||||||
### New Directives
|
### New directives
|
||||||
|
|
||||||
- `wire:sort`, `wire:intersect`, `wire:ref`, `.renderless`, `.preserve-scroll` are available for use.
|
- `wire:sort`, `wire:intersect`, `wire:ref`, `.renderless`, and `.preserve-scroll` are available.
|
||||||
- `data-loading` attribute automatically added to elements triggering network requests.
|
- Livewire adds a `data-loading` attribute to elements that trigger network requests.
|
||||||
|
|
||||||
| Directive | Purpose |
|
| Directive | Purpose |
|
||||||
|-----------|---------|
|
|-----------|---------|
|
||||||
@@ -121,20 +121,20 @@ These things changed in Livewire 4, but may not have been updated in this applic
|
|||||||
| `.renderless` | Component without rendering |
|
| `.renderless` | Component without rendering |
|
||||||
| `.preserve-scroll` | Preserve scroll position |
|
| `.preserve-scroll` | Preserve scroll position |
|
||||||
|
|
||||||
## Best Practices
|
## Best practices
|
||||||
|
|
||||||
- Always use `wire:key` in loops
|
- Always use `wire:key` in loops
|
||||||
- Use `wire:loading` for loading states
|
- Use `wire:loading` for loading states
|
||||||
- Use `wire:model.live` for live updates; `wire:model` is deferred by default
|
- Use `wire:model.live` for live updates. `wire:model` is deferred by default
|
||||||
- Validate and authorize in actions (treat like HTTP requests)
|
- Validate and authorize in actions (treat them like HTTP requests)
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
- `smart_wire_keys` defaults to `true`; new configs: `component_locations`, `component_namespaces`, `make_command`, `csp_safe`.
|
- `smart_wire_keys` defaults to `true`. New config keys: `component_locations`, `component_namespaces`, `make_command`, and `csp_safe`.
|
||||||
|
|
||||||
## Alpine & JavaScript
|
## Alpine and JavaScript
|
||||||
|
|
||||||
- `wire:transition` uses browser View Transitions API; `$errors` and `$intercept` magic properties available.
|
- `wire:transition` uses the browser View Transitions API. The `$errors` and `$intercept` magic properties are available.
|
||||||
- Non-blocking `wire:poll` and parallel `wire:model.live` updates improve performance.
|
- Non-blocking `wire:poll` and parallel `wire:model.live` updates improve performance.
|
||||||
|
|
||||||
For interceptors and hooks, see [reference/javascript-hooks.md](reference/javascript-hooks.md).
|
For interceptors and hooks, see [reference/javascript-hooks.md](reference/javascript-hooks.md).
|
||||||
@@ -151,14 +151,14 @@ Livewire::test(Counter::class)
|
|||||||
|
|
||||||
## Verification
|
## Verification
|
||||||
|
|
||||||
1. Browser console: Check for JS errors
|
1. Check the browser console for JS errors
|
||||||
2. Network tab: Verify Livewire requests return 200
|
2. In the network tab, verify that Livewire requests return 200
|
||||||
3. Ensure `wire:key` on all `@foreach` loops
|
3. Confirm that every `@foreach` loop has a `wire:key`
|
||||||
|
|
||||||
## Common Pitfalls
|
## Common pitfalls
|
||||||
|
|
||||||
- Missing `wire:key` in loops → unexpected re-rendering
|
- Missing `wire:key` in loops, which causes unexpected re-rendering
|
||||||
- Expecting `wire:model` real-time → use `wire:model.live`
|
- Expecting real-time updates from `wire:model` instead of using `wire:model.live`
|
||||||
- Unclosed component tags → syntax errors in v4
|
- Unclosed component tags, which cause syntax errors in v4
|
||||||
- Using deprecated config keys or JS hooks
|
- Using deprecated config keys or JS hooks
|
||||||
- Including Alpine.js separately (already bundled in Livewire 4)
|
- Including Alpine.js separately, though Livewire 4 already bundles it
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Livewire 4 JavaScript Integration
|
# Livewire 4 JavaScript integration
|
||||||
|
|
||||||
## Interceptor System (v4)
|
## Interceptor system (v4)
|
||||||
|
|
||||||
### Intercept Messages
|
### Intercept messages
|
||||||
|
|
||||||
```js
|
```js
|
||||||
Livewire.interceptMessage(({ component, message, onFinish, onSuccess, onError }) => {
|
Livewire.interceptMessage(({ component, message, onFinish, onSuccess, onError }) => {
|
||||||
@@ -12,7 +12,7 @@ Livewire.interceptMessage(({ component, message, onFinish, onSuccess, onError })
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Intercept Requests
|
### Intercept requests
|
||||||
|
|
||||||
```js
|
```js
|
||||||
Livewire.interceptRequest(({ request, onResponse, onSuccess, onError, onFailure }) => {
|
Livewire.interceptRequest(({ request, onResponse, onSuccess, onError, onFailure }) => {
|
||||||
@@ -23,7 +23,7 @@ Livewire.interceptRequest(({ request, onResponse, onSuccess, onError, onFailure
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Component-Scoped Interceptors
|
### Component-scoped interceptors
|
||||||
|
|
||||||
```blade
|
```blade
|
||||||
<script>
|
<script>
|
||||||
@@ -33,7 +33,7 @@ Livewire.interceptRequest(({ request, onResponse, onSuccess, onError, onFailure
|
|||||||
</script>
|
</script>
|
||||||
```
|
```
|
||||||
|
|
||||||
## Magic Properties
|
## Magic properties
|
||||||
|
|
||||||
- `$errors` - Access validation errors from JavaScript
|
- `$errors` gives JavaScript access to validation errors.
|
||||||
- `$intercept` - Component-scoped interceptors
|
- `$intercept` registers component-scoped interceptors.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -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/`.
|
||||||
@@ -1,96 +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 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
|
|
||||||
@@ -6,12 +6,12 @@ metadata:
|
|||||||
author: laravel
|
author: laravel
|
||||||
---
|
---
|
||||||
|
|
||||||
# Testing Best Practices
|
# 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 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.
|
This project uses Pest. Follow the corresponding guidance in each rule.
|
||||||
|
|
||||||
## Consistency First
|
## Consistency first
|
||||||
|
|
||||||
Read nearby tests before you choose syntax and organization.
|
Read nearby tests before you choose syntax and organization.
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ A pattern repeated throughout the project is a convention, and project conventio
|
|||||||
|
|
||||||
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.
|
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
|
## What to test
|
||||||
|
|
||||||
Read this section before you write a test.
|
Read this section before you write a test.
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ Read this section before you write a test.
|
|||||||
- 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.
|
- 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.
|
- 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
|
## How to apply
|
||||||
|
|
||||||
1. Read the code under test. Read the tests in the same directory. Identify every decision in the code.
|
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.
|
2. Select every applicable branch in the rule index. Read every selected rule file.
|
||||||
@@ -41,11 +41,11 @@ Read this section before you write a test.
|
|||||||
4. Write the tests. Run the smallest set of tests that covers the change. The tests must pass.
|
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.
|
5. Check every applicable item in `rules/review.md` and every selected rule file. Resolve every mismatch before completion.
|
||||||
|
|
||||||
## Rule Index
|
## Rule index
|
||||||
|
|
||||||
Most changes need more than one rule file.
|
Most changes need more than one rule file.
|
||||||
|
|
||||||
| Subject | Rule File |
|
| Subject | Rule file |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Test framework features that may already do the work | [`rules/finding-features.md`](rules/finding-features.md) |
|
| 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) |
|
| File layout, test names, and groups | [`rules/naming.md`](rules/naming.md) |
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
# Assertions
|
# Assertions
|
||||||
|
|
||||||
## Arrange, Act, Assert
|
## 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.
|
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.
|
Keep each test self-contained. Do not use values created by another test.
|
||||||
|
|
||||||
## How to Find the Correct Assertion
|
## 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.
|
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.
|
||||||
|
|
||||||
@@ -26,19 +26,19 @@ Use the assertion in this table for each subject.
|
|||||||
|
|
||||||
Use a PHPUnit assertion only if no Pest expectation and no Laravel assertion exists for the subject.
|
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.
|
Assert each fact once, but status and content are separate facts. `assertSee` passes on an error page that contains the text, so keep `assertOk()` alongside it when the status is part of the behavior.
|
||||||
|
|
||||||
## Named Response Assertions
|
## 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.
|
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.
|
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
|
## 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.
|
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
|
## 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.
|
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.
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ travelTo('2025-01-01 00:00:00');
|
|||||||
expect($from)->toBe('2024-12-31T00:00:00.000000Z');
|
expect($from)->toBe('2024-12-31T00:00:00.000000Z');
|
||||||
```
|
```
|
||||||
|
|
||||||
## Assert the Complete Result
|
## 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:
|
A status code is not the complete result of a write operation. Assert each of the following if the operation changes it:
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
# Endpoint Tests
|
# Endpoint tests
|
||||||
|
|
||||||
## How to Write the Test
|
## 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.
|
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.
|
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
|
## Endpoint coverage
|
||||||
|
|
||||||
Write a test for each applicable case:
|
Write a test for each applicable case:
|
||||||
|
|
||||||
@@ -19,27 +19,27 @@ Write a test for each applicable case:
|
|||||||
|
|
||||||
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.
|
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
|
## 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.
|
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
|
## 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`.
|
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.
|
- 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.
|
- 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.
|
- If the project has a helper that asserts the ability and the arguments of the gate, use that helper.
|
||||||
|
|
||||||
## Browser Tests
|
## 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.
|
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.
|
- 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.
|
- Wait until the test reaches the required state. Do not wait for a fixed number of seconds. A fixed wait can fail on a slower machine.
|
||||||
- Call `assertNoJavaScriptErrors()` in each browser test. An error in the console is a defect.
|
- Call `assertNoJavaScriptErrors()` in each browser test. An error in the console is a defect.
|
||||||
|
|
||||||
### Where a Browser Test Lives and How to Run It
|
### 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.
|
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.
|
||||||
|
|
||||||
@@ -49,15 +49,15 @@ The plugin runs browser tests as normal Pest tests, so they need no separate sui
|
|||||||
- The run needs Playwright and a browser on the machine. Follow the plugin documentation for local and CI installation commands.
|
- 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.
|
- Fetch `https://pestphp.com/docs/browser-testing` for the interactions, the assertions, and the devices that the plugin gives.
|
||||||
|
|
||||||
### Browser Test Pitfalls
|
### 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.
|
- The plugin waits five seconds for an element. For a slower page, raise the value with `pest()->browser()->timeout(10000)` in `Pest.php`. 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.
|
- 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.
|
- 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.
|
- 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.
|
- Interact inside the callback of `withinFrame()`. An interaction outside the callback does not reach the frame.
|
||||||
|
|
||||||
## Testing Validation
|
## Testing validation
|
||||||
|
|
||||||
- Write one test for each validation rule when each failure represents a separate contract.
|
- 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.
|
- Write one test with an empty payload to assert several required fields together.
|
||||||
@@ -66,7 +66,7 @@ The plugin runs browser tests as normal Pest tests, so they need no separate sui
|
|||||||
|
|
||||||
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.
|
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
|
### 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# How to Find Test Framework Features
|
# 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.
|
Pest adds features faster than this skill can list them. Find an existing feature before implementing the behavior by hand.
|
||||||
|
|
||||||
@@ -22,11 +22,11 @@ Search for a feature in this table before you write the code by hand.
|
|||||||
| Assert that a value has a known format | validation expectations |
|
| Assert that a value has a known format | validation expectations |
|
||||||
| Run one test while you debug | filtering, `--bail`, `--dirty` |
|
| Run one test while you debug | filtering, `--bail`, `--dirty` |
|
||||||
|
|
||||||
## Built-in Laravel Assertion Methods
|
## 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()`.
|
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 you build 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.
|
A hand-built check fails with `false is not true`. That message identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure shows what to fix.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
// The failure says that false is not true. Instead of this...
|
// The failure says that false is not true. Instead of this...
|
||||||
|
|||||||
@@ -1,52 +1,52 @@
|
|||||||
# Fakes, Mocks, and Determinism
|
# 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.
|
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
|
## 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.
|
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.
|
Identify the dependency, then choose the first option that applies. 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.
|
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.
|
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.
|
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.
|
4. Use the real implementation for everything else, including the database.
|
||||||
|
|
||||||
## Framework Fakes
|
## Framework fakes
|
||||||
|
|
||||||
- Create each fake inside the test that needs it. Do not create fakes in a file-level `beforeEach()`.
|
- 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.
|
- 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()`.
|
- 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.
|
- 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.
|
- If the data of a job or an event is part of the behavior, assert that data.
|
||||||
- Use `Exceptions::fake()` to assert that the application reports the correct exception. Do not use `withoutExceptionHandling()`, because it changes the response under test.
|
- 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.
|
Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID. A fake without class names suppresses those events, and the factory can then produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.
|
||||||
|
|
||||||
## Mocking
|
## 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.
|
Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. If an equality check cannot state the expected argument, such as a check of one field of a value object, use `Mockery::on()` or `withArgs()`.
|
||||||
|
|
||||||
Import the mock function before you use it: `use function Pest\Laravel\mock;`.
|
Import the mock function before you use it: `use function Pest\Laravel\mock;`.
|
||||||
|
|
||||||
## Outbound HTTP Testing
|
## Outbound HTTP testing
|
||||||
|
|
||||||
Call `Http::preventStrayRequests()`. Any request without a matching fake then fails without reaching the network.
|
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.
|
Fake the exact endpoint that each test calls. Do not call `Http::fake()` without an endpoint, because a fake without an endpoint accepts unexpected requests and can hide defects.
|
||||||
|
|
||||||
## Time and Randomness
|
## Time and randomness
|
||||||
|
|
||||||
- Freeze the time or move the time in each test that depends on a date, a period, or a timestamp.
|
- 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 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.
|
- If the test asserts an identifier or a slug, use `Str::createRandomStringsUsing()` to fix the generated string.
|
||||||
- Use `Sleep::fake()` instead of a real sleep, and assert the sleeps that the code requests.
|
- 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.
|
- If the suite does not restore the time and the randomness for every test, restore them after each test.
|
||||||
|
|
||||||
## Database
|
## 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.
|
- 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.
|
- If the shape of the serialized model is a contract, assert the exact keys of `toArray()`. 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.
|
- 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.
|
- Use `LazilyRefreshDatabase` instead of `RefreshDatabase`. A test that does not use the database then does not run the migrations.
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
# Naming and Structure
|
# Naming and structure
|
||||||
|
|
||||||
## File Layout
|
## File layout
|
||||||
|
|
||||||
- Name each test file `{ClassName}Test.php`.
|
- 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`.
|
- 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.
|
- 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.
|
- Move large literal values out of the test body and into fixture files.
|
||||||
|
|
||||||
## Test Function
|
## Test function
|
||||||
|
|
||||||
Use the test function used by other files in the same directory. If no neighboring test files exist:
|
Use the test function that other files in the same directory use. If no neighboring test files exist:
|
||||||
|
|
||||||
- Use `it()` for the behavior of the code, and write the name as a verb phrase.
|
- 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 `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.
|
Use one Pest declaration style in each file. Use either `it()` or `test()` consistently.
|
||||||
|
|
||||||
## Naming Tests
|
## Naming tests
|
||||||
|
|
||||||
The name of a test is a specification. State the user-visible result and the condition that causes it.
|
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.
|
- Name the behavior, 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.
|
- 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.
|
- Do not write `Given`, `When`, or `Then` in the name.
|
||||||
|
|
||||||
@@ -32,11 +32,11 @@ 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`.
|
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.
|
Do not write `it('works correctly')` or `it('returns data')`, because neither names a result. Do not write `it('handleMethod creates record')`, because that name gives a method rather than a behavior.
|
||||||
|
|
||||||
## Grouping
|
## 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`.
|
If one file covers separate actions in a lifecycle, use `describe()`. An example is a controller with the actions `index`, `show`, `store`, `update`, and `destroy`.
|
||||||
|
|
||||||
Do not use `describe()` in these cases:
|
Do not use `describe()` in these cases:
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Test Suite Performance
|
# Test suite performance
|
||||||
|
|
||||||
These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.
|
These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.
|
||||||
|
|
||||||
@@ -7,52 +7,52 @@ 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.
|
Measure before changing a setting. Find the slow test first, and apply a project-wide setting only after identifying the costly work.
|
||||||
|
|
||||||
## Test Environment
|
## 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.
|
- 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 Xdebug. Unless the run needs coverage, disable pcov too.
|
||||||
- Disable packages that perform work on every request in the test environment. Examples are Pulse, Telescope, and Nightwatch.
|
- 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.
|
- 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.
|
- Call `withoutVite()`, or `withoutMix()`, so the framework does not resolve a built asset.
|
||||||
|
|
||||||
## Global Fakes
|
## Global fakes
|
||||||
|
|
||||||
Put these three calls in the base `Pest.php` of the project:
|
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.
|
- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. It catches requests that go 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.
|
- `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.
|
- `Exceptions::fake()`, so the suite does not report an exception to an external service.
|
||||||
|
|
||||||
## How to Run the Suite in Parallel
|
## 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.
|
Run `vendor/bin/pest --parallel` to spread tests across the machine's CPU cores. If the default count does not suit the machine or CI, add `--processes=N`.
|
||||||
|
|
||||||
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:
|
A parallel run gives each process a separate database. Each test must meet the conditions below. 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 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 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.
|
- 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
|
## 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.
|
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.
|
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
|
## 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.
|
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.
|
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
|
## 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.
|
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.
|
If the cause of a slow test is unclear, add an event listener or temporary log entry to identify the work the test does.
|
||||||
|
|
||||||
## Common Errors
|
## Common errors
|
||||||
|
|
||||||
- The run loads XDebug for a test that does not need it.
|
- 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`.
|
- `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.
|
- The code under test calls the real `sleep()`, and `Sleep::fake()` then does not help.
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
# Reviewing Tests
|
# 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.
|
Check every item in this file. A test can pass and 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.
|
Report each finding. Do not delete or rewrite a test without the user's approval. If an issue appears throughout the suite as a convention, report the pattern once rather than once for each affected file.
|
||||||
|
|
||||||
## Test Value
|
## 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.
|
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 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 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.
|
- [ ] Each test detects a distinct defect that no other test covers. Reduce a duplicate at the higher layer to the one case that proves the wiring.
|
||||||
- [ ] Every changed decision and each applicable high-value failure mode has coverage.
|
- [ ] Every changed decision and each applicable high-value failure mode has coverage.
|
||||||
|
|
||||||
## Names and Structure
|
## Names and structure
|
||||||
|
|
||||||
- [ ] Each file has the name `{ClassName}Test.php` and the relative path of the class under test.
|
- [ ] 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 name states a result, the condition that causes it, and the status code for an API error.
|
||||||
@@ -24,16 +24,16 @@ Apply this section to behavioral tests. An architecture test states a convention
|
|||||||
- [ ] HTTP tests cover authentication, authorization, role, scope, and validation when applicable.
|
- [ ] 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.
|
- [ ] 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.
|
- [ ] 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.
|
- [ ] Each validation rule has one test that asserts the user-visible message. If a unit test covers a matrix, reduce the 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.
|
- [ ] Rendered user input and each dynamic part of a query have a security test.
|
||||||
|
|
||||||
## Data and Determinism
|
## 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 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 `beforeEach()` holds configuration only.
|
||||||
- [ ] Each factory state and each relationship gives the meaning of the data.
|
- [ ] 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.
|
- [ ] Each call to `make()` is in a test that does not need the database.
|
||||||
- [ ] Time, randomness, sleep, and outbound HTTP are controlled.
|
- [ ] Each test controls time, randomness, sleep, and outbound HTTP.
|
||||||
- [ ] Each test passes alone, and passes in the complete suite in any order.
|
- [ ] Each test passes alone, and passes in the complete suite in any order.
|
||||||
|
|
||||||
## Assertions
|
## Assertions
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
# Security Tests
|
# 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.
|
Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary is hard to detect, because the feature can keep working.
|
||||||
|
|
||||||
Write a test for each of these cases:
|
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`.
|
- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for when the response should be `404` rather than `403`.
|
||||||
- **Each unprivileged role.** Use a dataset over the roles that the endpoint must refuse.
|
- **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.
|
- **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 can decode it.
|
||||||
- **Injection into dynamic query components.** Examples include sort columns, filter fields, and sort directions.
|
- **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.
|
- **An unexpected key** in a payload or configuration array. A merge that accepts every key can set an attribute the user must not control.
|
||||||
|
|
||||||
@@ -24,4 +24,4 @@ it('escapes dangerous content in the notification', function () {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the correct defense to each attribute, route, and template.
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
# Factories and Test Data
|
# Factories and test data
|
||||||
|
|
||||||
## Each Test Makes Its Own 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.
|
Create mutable records inside the test that uses them. The setup then stays visible, and each test can select its factory state.
|
||||||
|
|
||||||
Use `beforeEach()` only for configuration that applies to every test in the file. Do not create records in it.
|
Use `beforeEach()` only for configuration that applies to every test in the file. Do not create records in it.
|
||||||
|
|
||||||
## Record Construction
|
## Record construction
|
||||||
|
|
||||||
- Use `create()` if the test needs the record in the database.
|
- 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 `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 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 `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.
|
- If several records must share one parent record, use `recycle()`.
|
||||||
- Use `sequence()` if several records need different attributes.
|
- If several records need different attributes, use `sequence()`.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();
|
$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();
|
||||||
@@ -51,6 +51,6 @@ Use parameterized tests for:
|
|||||||
- input values that are invalid in the same way
|
- input values that are invalid in the same way
|
||||||
- input and output value pairs
|
- 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.
|
If the cases need a different setup, a different behavior, or different assertions, write separate tests. 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.
|
Give each dataset case a name that states the difference. A failure then identifies the case without requiring you to count positions.
|
||||||
|
|||||||
+16
-1
@@ -69,5 +69,20 @@ VITE_APP_NAME="${APP_NAME}"
|
|||||||
# OCTANE_HTTPS=false
|
# OCTANE_HTTPS=false
|
||||||
# OCTANE_MAX_EXECUTION_TIME=300
|
# 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
|
# SERVER_NAME=share.example.com
|
||||||
|
|||||||
+13
-14
@@ -2,8 +2,6 @@ name: docker
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
tags:
|
tags:
|
||||||
- "v*.*.*"
|
- "v*.*.*"
|
||||||
pull_request:
|
pull_request:
|
||||||
@@ -24,7 +22,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Setup PHP
|
- name: Setup PHP
|
||||||
uses: shivammathur/setup-php@v2
|
uses: shivammathur/setup-php@v2
|
||||||
@@ -35,9 +33,9 @@ jobs:
|
|||||||
coverage: xdebug
|
coverage: xdebug
|
||||||
|
|
||||||
- name: Setup Node
|
- name: Setup Node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: "24"
|
node-version: "26"
|
||||||
|
|
||||||
- name: Install Node Dependencies
|
- name: Install Node Dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
@@ -65,25 +63,28 @@ jobs:
|
|||||||
needs: test
|
needs: test
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
# The runner is an arm64 server, so the amd64 image's final stage is emulated. QEMU 8.x
|
# 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
|
# 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
|
# 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.
|
# checked on the runner's host: node, composer and install-php-extensions all run.
|
||||||
|
# reset: the emulators are registered on the host for all jobs, and binfmt skips one that
|
||||||
|
# is already registered, so without it an older QEMU from another job stays in use.
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3
|
uses: docker/setup-qemu-action@v4
|
||||||
with:
|
with:
|
||||||
image: tonistiigi/binfmt:qemu-v9.2.2
|
image: tonistiigi/binfmt:qemu-v9.2.2
|
||||||
|
reset: true
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v4
|
||||||
|
|
||||||
# Gitea's job token cannot publish packages yet: REGISTRY_TOKEN is an access token with
|
# 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).
|
# package write rights, owned by the account that pushes (gitea.actor).
|
||||||
- name: Log in to the Gitea container registry
|
- name: Log in to the Gitea container registry
|
||||||
if: gitea.event_name != 'pull_request'
|
if: gitea.event_name != 'pull_request'
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v4
|
||||||
with:
|
with:
|
||||||
registry: gitea.nonameweb.ch
|
registry: gitea.nonameweb.ch
|
||||||
username: ${{ gitea.actor }}
|
username: ${{ gitea.actor }}
|
||||||
@@ -91,18 +92,16 @@ jobs:
|
|||||||
|
|
||||||
- name: Extract Docker metadata
|
- name: Extract Docker metadata
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v5
|
uses: docker/metadata-action@v6
|
||||||
with:
|
with:
|
||||||
images: gitea.nonameweb.ch/nonameweb/sealshare
|
images: gitea.nonameweb.ch/nonameweb/sealshare
|
||||||
tags: |
|
tags: |
|
||||||
type=semver,pattern={{version}}
|
type=semver,pattern={{version}}
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
type=semver,pattern={{major}}
|
type=semver,pattern={{major}}
|
||||||
type=ref,event=branch
|
|
||||||
type=sha
|
|
||||||
|
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v7
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
@@ -118,7 +117,7 @@ jobs:
|
|||||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Take the release notes from the changelog
|
- name: Take the release notes from the changelog
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
environment: Testing
|
environment: Testing
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Setup PHP
|
- name: Setup PHP
|
||||||
uses: shivammathur/setup-php@v2
|
uses: shivammathur/setup-php@v2
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Setup PHP
|
- name: Setup PHP
|
||||||
uses: shivammathur/setup-php@v2
|
uses: shivammathur/setup-php@v2
|
||||||
@@ -35,9 +35,9 @@ jobs:
|
|||||||
coverage: xdebug
|
coverage: xdebug
|
||||||
|
|
||||||
- name: Setup Node
|
- name: Setup Node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: '24'
|
node-version: '26'
|
||||||
|
|
||||||
- name: Install Node Dependencies
|
- name: Install Node Dependencies
|
||||||
run: npm i
|
run: npm i
|
||||||
|
|||||||
@@ -27,3 +27,6 @@ frankenphp
|
|||||||
frankenphp-worker.php
|
frankenphp-worker.php
|
||||||
|
|
||||||
/tests/Browser/Screenshots
|
/tests/Browser/Screenshots
|
||||||
|
|
||||||
|
# Planning notes stay local
|
||||||
|
/docs/plans
|
||||||
|
|||||||
+140
-2
@@ -5,7 +5,138 @@ 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/),
|
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).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
## [Unreleased]
|
## [2.4.3] - 2026-11-19
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Updated to Laravel 13.43, Laravel Octane 2.25 and Laravel Fortify 1.43, and Vite 8.3.8.
|
||||||
|
- The Docker image builds its assets with Node.js 26 and runs FrankenPHP 1.13.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Security: Laravel 13.43 and the Symfony components 8.1.10 and 8.1.11 fix advisories in Laravel's concurrency processes and in Symfony's HTTP foundation (trusted proxies, HEAD requests, generated URLs), HTTP kernel, routing, MIME (e-mail header injection), serializer and YAML parser. Update with `docker compose pull` and `docker compose up -d`.
|
||||||
|
|
||||||
|
## [2.4.2] - 2026-10-22
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Whoever entered the system password enters it once more after the update. A change of the system password now ends every earlier entry.
|
||||||
|
- The page after an upload, with the link and the QR code, opens only in the browser session that created the share, and only while the share can still be downloaded. Other visitors get "not found".
|
||||||
|
- The admin password in the setup wizard follows the same rules as a changed password (in production: at least 12 characters, upper and lower case, numbers and symbols).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Security: an anonymous uploader could reserve the whole storage quota with declared file sizes and send no data. Uploads that are not complete now count only the bytes received, and a chunk that goes above the quota is refused.
|
||||||
|
- Security: password attempts are limited per share, per login e-mail and for the system password (20 per minute), in addition to the limit per address (5 per minute), which a forged `X-Forwarded-For` header could change. The share password limit counts an attempt before the check, so parallel attempts cannot pass it. The system password had no limit.
|
||||||
|
- Security: the system password also protects the upload page's actions, so a page opened before the system password was set cannot register files.
|
||||||
|
- Security: the page after an upload showed a share's details to everyone with its link, also for a password-protected or expired share.
|
||||||
|
- Security: a password change or reset signs the admin's other sessions out.
|
||||||
|
- Security: the only admin can no longer delete their account, which opened the setup page to every visitor.
|
||||||
|
|
||||||
|
## [2.4.1] - 2026-10-22
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Updated to Laravel 13.38, Livewire 4.4.8 and Laravel Octane 2.22, and Vite 8.3.5.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Security: the Docker image runs PHP 8.5.12, which fixes PHP2Shell (CVE-2026-109618, CVE-2026-109619): two flaws that let an attacker without an account run code on the server when a request ends abnormally. Every earlier image runs an affected PHP (2.4.0 runs PHP 8.5.8). Update now: `docker compose pull` and `docker compose up -d`.
|
||||||
|
|
||||||
|
## [2.4.0] - 2026-10-08
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- "Download all to a folder" on the download page, in Chrome and Edge on a computer. The recipient picks a folder, and the files are saved into it one at a time, in their folder paths, with progress. A connection that breaks off is resumed where it stopped, files already in the folder are skipped, and files that still fail can be retried. Each request is only as long as one file, so large shares get through proxies that cut long requests. Other browsers keep the ZIP and the per-file buttons.
|
||||||
|
- Single-file downloads can be resumed: they answer HTTP Range requests, so the browser continues an interrupted download instead of starting over.
|
||||||
|
- The download page shows how many files a share holds and their total size, and marks the files this browser has downloaded. During a folder download it marks the file on its way and scrolls the list to it.
|
||||||
|
- "Browse Folder" on the upload page picks a whole folder. Each file keeps its path in it, as when a folder is dropped.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The ZIP download sends its size, so the browser shows its progress and notices a download that was cut short.
|
||||||
|
- A long file list on the download page scrolls on its own, so the download buttons stay on the first screen.
|
||||||
|
- A recipient's 1-hour download window restarts with each download they start, so downloading a large share file by file does not use up another download partway through.
|
||||||
|
- Updated to Laravel 13.35, Livewire 4.4.7, Laravel Octane 2.21 and Laravel Fortify 1.41, and Vite 8.3.4.
|
||||||
|
- The Gitea workflows use the current versions of the checkout, setup-node and Docker actions, which run on Node 24 instead of the end-of-life Node 20.
|
||||||
|
- Sessions are encrypted (unless `SESSION_ENCRYPT=false`), because they hold the keys of the password shares a recipient unlocked. Every share stays readable, but everyone is signed out once by the update: admins sign in again, and recipients enter a share's password again. A recipient who was inside their download window on a share that had reached its download limit can no longer download it.
|
||||||
|
- The Docker image no longer starts without `APP_KEY`. It used to generate one, print it to the logs and generate another on the next start, which left every share without a password unreadable. `docker-compose.example.yml` now requires it for both services. **Before updating an install that never set `APP_KEY`, copy the key from the container's logs (`Generated APP_KEY: …`) and set it for the app and the scheduler**, so the shares created since its last start stay readable. A new key is created with `docker run --rm --entrypoint php <image> artisan key:generate --show`; the command in the README did not run it before.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Downloads of large shares stopped after 5 minutes (`OCTANE_MAX_EXECUTION_TIME`, 300 seconds by default) and left a broken ZIP. Downloads no longer have a time limit.
|
||||||
|
- Security: a visitor with a password-protected share's link but not its password could reveal its file list (names, folder paths, sizes, and whether it holds a text) by changing the page's state in the browser. The files and the text themselves stayed protected.
|
||||||
|
- Security: the password-reset link is built from `APP_URL`, never from the request's host, which a forged `X-Forwarded-Host` header could set.
|
||||||
|
- Security: league/commonmark 2.10.3 fixes a denial of service in the GitHub Flavored Markdown table extension and a bypass of its raw-HTML filter. source-map-js, used by the asset build, is updated past a high-severity advisory.
|
||||||
|
|
||||||
|
## [2.3.0] - 2026-09-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Private text: a share can hold a text, such as a password, a key or a short note, with its files or on its own. It is typed into the new "Private text" card on the upload page (up to 100 KB) and encrypted in the browser like a file, so it gets the share's password, expiry and download limit. The recipient sees it only after pressing "Show text", which counts as their download, so a link preview cannot use up a share limited to one download. The text is left out of the file list, the ZIP and the file counts; the admin dashboard marks shares that hold one with "Text".
|
||||||
|
|
||||||
|
## [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
|
## [2.0.0] - 2026-09-13
|
||||||
|
|
||||||
@@ -107,5 +238,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
- Dark themed UI built with Livewire, Alpine.js, Tailwind CSS and DaisyUI.
|
- 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.
|
- Docker images published to `ghcr.io/surtic86/sealshare`, served by FrankenPHP via Laravel Octane.
|
||||||
|
|
||||||
[Unreleased]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.0.0...main
|
[2.4.3]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.4.2...v2.4.3
|
||||||
|
[2.4.2]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.4.1...v2.4.2
|
||||||
|
[2.4.1]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.4.0...v2.4.1
|
||||||
|
[2.4.0]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.3.0...v2.4.0
|
||||||
|
[2.3.0]: https://gitea.nonameweb.ch/noNameWEB/SealShare/compare/v2.2.0...v2.3.0
|
||||||
|
[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
|
[2.0.0]: https://gitea.nonameweb.ch/noNameWEB/SealShare/releases/tag/v2.0.0
|
||||||
|
|||||||
@@ -3,11 +3,9 @@
|
|||||||
|
|
||||||
# Laravel Boost Guidelines
|
# Laravel Boost Guidelines
|
||||||
|
|
||||||
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications.
|
|
||||||
|
|
||||||
## Foundational Context
|
## Foundational Context
|
||||||
|
|
||||||
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.
|
This application is a Laravel application running on PHP 8.5. Always use the APIs that match the installed major version of each package — do not assume a version.
|
||||||
|
|
||||||
Before relying on a package's API, confirm its installed version:
|
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.
|
- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show <vendor/package>` for a single package.
|
||||||
@@ -34,16 +32,12 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
|
|||||||
|
|
||||||
## Frontend Bundling
|
## Frontend Bundling
|
||||||
|
|
||||||
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.
|
- If a frontend change doesn't show in the UI or you get a "Unable to locate file in Vite manifest" error, run `npm run build` or ask the user to run `npm run dev`.
|
||||||
|
|
||||||
## Documentation Files
|
## Documentation Files
|
||||||
|
|
||||||
- You must only create documentation files if explicitly requested by the user.
|
- You must only create documentation files if explicitly requested by the user.
|
||||||
|
|
||||||
## Replies
|
|
||||||
|
|
||||||
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
|
|
||||||
|
|
||||||
=== boost rules ===
|
=== boost rules ===
|
||||||
|
|
||||||
# Laravel Boost
|
# Laravel Boost
|
||||||
@@ -72,8 +66,7 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
|
|||||||
|
|
||||||
## Project Rules
|
## 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.
|
- This project contains committed, area-grouped rules in `.ai/rules` when that directory exists, including path-scoped framework guidelines under `.ai/rules/boost`. 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 durable rules with `record-rule` so the next agent or teammate inherits them instead of working them out again. Pass a `glob` (e.g. `app/Http/Controllers/**`), a short `title`, and a few-line `note`. Always use `record-rule`, never your native memory or notes tool — native memory is personal and session-scoped; only `.ai/rules` is shared with the team and persists in the repo.
|
|
||||||
|
|
||||||
## Artisan
|
## Artisan
|
||||||
|
|
||||||
@@ -103,16 +96,6 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
|
|||||||
# Deployment
|
# Deployment
|
||||||
|
|
||||||
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
|
- 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
|
|
||||||
|
|
||||||
- Test every code change by adding or updating a test.
|
|
||||||
- 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 ===
|
=== laravel/core rules ===
|
||||||
|
|
||||||
@@ -140,10 +123,6 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac
|
|||||||
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
|
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
|
||||||
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
|
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
|
||||||
|
|
||||||
## Vite Error
|
|
||||||
|
|
||||||
- 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`.
|
|
||||||
|
|
||||||
=== laravel-octane/core rules ===
|
=== laravel-octane/core rules ===
|
||||||
|
|
||||||
# Laravel Octane
|
# Laravel Octane
|
||||||
@@ -185,18 +164,91 @@ When working on Octane-specific features (concurrency, shared tables, memory, dr
|
|||||||
- Run the narrowest set of tests that covers the change. Pass a file path or `--filter=testName` to `php artisan test --compact`.
|
- 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.
|
- 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.
|
- 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 ===
|
=== nonameweb/livewire-material/core rules ===
|
||||||
|
|
||||||
## Livewire Material
|
## Livewire Material
|
||||||
|
|
||||||
This application uses `nonameweb/livewire-material`: Material 3 Expressive components for Laravel and Livewire, built on Tailwind CSS. It replaces UI kits such as maryUI, daisyUI and Flux in this application.
|
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.
|
- 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.
|
||||||
- Never write maryUI tags (`<x-mary-*>`) or daisyUI classes (`btn`, `card`, `badge`, `bg-base-200`, `text-base-content`…). They compile to nothing and fail silently.
|
- 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()`.
|
- 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).
|
- 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`.
|
- 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>
|
</laravel-boost-guidelines>
|
||||||
|
|||||||
+50
-21
@@ -25,7 +25,7 @@ RUN composer dump-autoload --optimize --no-dev
|
|||||||
# ============================================
|
# ============================================
|
||||||
# After Composer: the stylesheet and script import Livewire Material from vendor/. On the build
|
# 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.
|
# machine's platform too: the output is CSS and JavaScript, whatever the target.
|
||||||
FROM --platform=$BUILDPLATFORM node:24-alpine AS assets
|
FROM --platform=$BUILDPLATFORM node:26-alpine AS assets
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -39,20 +39,53 @@ COPY --from=vendor /app/vendor/nonameweb ./vendor/nonameweb
|
|||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Stage 3: Production image (FrankenPHP/Octane)
|
# Stage 3: PHP runtime, shared by development and production
|
||||||
# ============================================
|
# ============================================
|
||||||
FROM dunglas/frankenphp:php8.5-alpine AS production
|
FROM dunglas/frankenphp:php8.5-alpine AS base
|
||||||
|
|
||||||
LABEL maintainer="surtic86"
|
|
||||||
LABEL org.opencontainers.image.source="https://gitea.nonameweb.ch/noNameWEB/SealShare"
|
|
||||||
LABEL org.opencontainers.image.description="Self-hosted encrypted file sharing"
|
|
||||||
|
|
||||||
# Install required PHP extensions
|
|
||||||
RUN install-php-extensions \
|
RUN install-php-extensions \
|
||||||
intl \
|
intl \
|
||||||
pcntl \
|
pcntl \
|
||||||
zip
|
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: the same major as the asset build, which Alpine does not package.
|
||||||
|
# git for Composer: Livewire Material comes from a git repository.
|
||||||
|
RUN apk add --no-cache libstdc++ git
|
||||||
|
COPY --from=node:26-alpine /usr/local/bin/node /usr/local/bin/node
|
||||||
|
COPY --from=node:26-alpine /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/npm
|
||||||
|
RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
|
||||||
|
&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
|
||||||
|
|
||||||
|
# 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
|
# Laravel environment defaults
|
||||||
ENV APP_NAME="SealShare" \
|
ENV APP_NAME="SealShare" \
|
||||||
APP_ENV="production" \
|
APP_ENV="production" \
|
||||||
@@ -69,14 +102,6 @@ ENV APP_NAME="SealShare" \
|
|||||||
BCRYPT_ROUNDS="12" \
|
BCRYPT_ROUNDS="12" \
|
||||||
OCTANE_SERVER="frankenphp"
|
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 application code
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
@@ -87,23 +112,27 @@ COPY --from=vendor /app/vendor ./vendor
|
|||||||
COPY --from=assets /app/public/build ./public/build
|
COPY --from=assets /app/public/build ./public/build
|
||||||
|
|
||||||
# Remove dev/build files and stale cache not needed in production
|
# Remove dev/build files and stale cache not needed in production
|
||||||
RUN rm -rf node_modules tests .gitea 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 \
|
bootstrap/cache/*.php \
|
||||||
&& mkdir -p storage/app/shares storage/app/public storage/framework/cache \
|
&& mkdir -p storage/app/shares storage/app/public storage/framework/cache \
|
||||||
storage/framework/sessions storage/framework/testing storage/framework/views \
|
storage/framework/sessions storage/framework/testing storage/framework/views \
|
||||||
storage/logs database \
|
storage/logs database/sqlite \
|
||||||
&& chmod -R 777 storage database bootstrap/cache
|
&& 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
|
# Create SQLite database file if it doesn't exist
|
||||||
RUN touch database/database.sqlite \
|
RUN touch database/database.sqlite \
|
||||||
&& chmod 666 database/database.sqlite
|
&& chmod 666 database/database.sqlite
|
||||||
|
|
||||||
# Make entrypoint executable
|
# Make entrypoint and healthcheck executable
|
||||||
RUN chmod +x docker/entrypoint.sh
|
RUN chmod +x docker/entrypoint.sh docker/healthcheck.sh
|
||||||
|
|
||||||
EXPOSE 80 443 443/udp
|
EXPOSE 80 443 443/udp
|
||||||
|
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
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"]
|
ENTRYPOINT ["docker/entrypoint.sh"]
|
||||||
|
|||||||
@@ -16,13 +16,14 @@ A simple, self-hosted file sharing solution built with Laravel. Upload files, ge
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **File Uploading** — Drag & drop or browse to upload single/multiple files and folders with real-time progress
|
- **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
|
||||||
|
- **Private Text** — Share a password, a key or a short note (up to 100 KB) with the files or on its own; it is encrypted in the browser like a file and stays hidden until the recipient presses "Show text", which counts as a download
|
||||||
- **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
|
- **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 on the server as they arrive, with AES-256-GCM (chunked, streaming); with a share password the key is derived from it and never stored. It is not end-to-end encryption: the server handles the files unencrypted while they are uploaded and downloaded
|
- **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
|
- **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)
|
- **Expiration** — Shares auto-expire after a configurable duration (1 hour to 30 days)
|
||||||
- **Download Limits** — Set a maximum number of downloads per share
|
- **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)
|
- **Auto-Cleanup** — Expired shares and files are automatically deleted (hourly)
|
||||||
- **Admin Dashboard** — View, manage, and delete all shares
|
- **Admin Dashboard** — View, manage, and delete all shares
|
||||||
- **Admin Settings** — Configure upload limits, storage quotas, branding, and more
|
- **Admin Settings** — Configure upload limits, storage quotas, branding, and more
|
||||||
@@ -40,10 +41,10 @@ A simple, self-hosted file sharing solution built with Laravel. Upload files, ge
|
|||||||
|-------|-----------|
|
|-------|-----------|
|
||||||
| **Framework** | Laravel 13 |
|
| **Framework** | Laravel 13 |
|
||||||
| **Application Server** | FrankenPHP (via Laravel Octane) |
|
| **Application Server** | FrankenPHP (via Laravel Octane) |
|
||||||
| **Frontend** | Livewire 4, Tailwind CSS 4, [Livewire Material](https://gitea.nonameweb.ch/noNameWEB/livewire-material) (Material 3 Expressive) |
|
| **Frontend** | Livewire 4, [Livewire Material](https://gitea.nonameweb.ch/noNameWEB/livewire-material) (Material 3 Expressive) |
|
||||||
| **Authentication** | Laravel Fortify |
|
| **Authentication** | Laravel Fortify |
|
||||||
| **Encryption** | Chunked AES-256-GCM with PBKDF2-SHA256 key derivation |
|
| **Encryption** | Chunked AES-256-GCM (WebCrypto in the browser), keys wrapped with Argon2id |
|
||||||
| **ZIP Downloads** | Native PHP ZipArchive |
|
| **ZIP Downloads** | [ZipStream-PHP](https://packagist.org/packages/maennchen/zipstream-php) |
|
||||||
| **Testing** | Pest 5 with browser tests (Playwright) |
|
| **Testing** | Pest 5 with browser tests (Playwright) |
|
||||||
| **Code Style** | Laravel Pint |
|
| **Code Style** | Laravel Pint |
|
||||||
| **Build Tool** | Vite |
|
| **Build Tool** | Vite |
|
||||||
@@ -52,15 +53,35 @@ A simple, self-hosted file sharing solution built with Laravel. Upload files, ge
|
|||||||
|
|
||||||
### Docker (recommended)
|
### Docker (recommended)
|
||||||
|
|
||||||
```bash
|
`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.
|
||||||
# Build and start the dev container
|
|
||||||
docker compose -f docker-compose.dev.yml up -d --build
|
|
||||||
|
|
||||||
# View logs (including Vite output)
|
```bash
|
||||||
docker compose -f docker-compose.dev.yml logs -f
|
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
|
## Installation — Production
|
||||||
@@ -73,9 +94,9 @@ curl -O https://gitea.nonameweb.ch/noNameWEB/SealShare/raw/branch/main/docker-co
|
|||||||
cp docker-compose.example.yml docker-compose.yml
|
cp docker-compose.example.yml docker-compose.yml
|
||||||
|
|
||||||
# Generate an app key and paste it into docker-compose.yml
|
# Generate an app key and paste it into docker-compose.yml
|
||||||
docker run --rm gitea.nonameweb.ch/nonameweb/sealshare:latest php artisan key:generate --show
|
docker run --rm --entrypoint php gitea.nonameweb.ch/nonameweb/sealshare:latest 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:
|
# Then start:
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
```
|
```
|
||||||
@@ -88,29 +109,34 @@ Migrations run automatically on startup. Open your configured domain — the Set
|
|||||||
|----------|----------|-------------|
|
|----------|----------|-------------|
|
||||||
| `APP_KEY` | Yes | Laravel encryption key |
|
| `APP_KEY` | Yes | Laravel encryption key |
|
||||||
| `APP_URL` | Yes | Full URL (e.g. `https://share.example.com`) |
|
| `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:**
|
**Volumes:**
|
||||||
|
|
||||||
| Volume | Path | Purpose |
|
| Volume | Path | Purpose |
|
||||||
|--------|------|---------|
|
|--------|------|---------|
|
||||||
| `sealshare_storage` | `/app/storage/app` | Encrypted uploaded files |
|
| `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_data` | `/data` | TLS certificates |
|
||||||
| `caddy_config` | `/config` | Caddy configuration |
|
| `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:**
|
**Large files:**
|
||||||
|
|
||||||
Uploads beyond the defaults need these limits raised together:
|
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 |
|
| Limit | Where | Default |
|
||||||
|-------|-------|---------|
|
|-------|-------|---------|
|
||||||
| `PHP_UPLOAD_MAX_FILESIZE` / `PHP_POST_MAX_SIZE` | Environment | `4G` — hard cap per file / per upload batch |
|
|
||||||
| Max file size / Max size per share | Admin → Settings | 100 MB / 2 GB |
|
| Max file size / Max size per share | Admin → Settings | 100 MB / 2 GB |
|
||||||
| `LIVEWIRE_MAX_UPLOAD_TIME` | Environment | 30 minutes per upload |
|
| Storage quota | Admin → Settings | 20 GB — files still uploading count towards it |
|
||||||
| `OCTANE_MAX_EXECUTION_TIME` / `PHP_MAX_EXECUTION_TIME` | Environment | 300 seconds — encrypting a large file takes a while |
|
| `UPLOAD_CHUNK_SIZE_MB` | Environment | `16` |
|
||||||
|
|
||||||
Behind a reverse proxy, raise its request body limit and read timeout as well (nginx: `client_max_body_size`, `proxy_read_timeout`).
|
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)
|
### Manual (without Docker)
|
||||||
|
|
||||||
@@ -152,3 +178,5 @@ Add the scheduler to your crontab:
|
|||||||
## License
|
## License
|
||||||
|
|
||||||
This project is open-source software licensed under the [MIT License](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).
|
||||||
|
|||||||
@@ -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'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,7 @@ trait ProfileValidationRules
|
|||||||
*
|
*
|
||||||
* @return array<string, array<int, \Illuminate\Contracts\Validation\Rule|array<mixed>|string>>
|
* @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 [
|
return [
|
||||||
'name' => $this->nameRules(),
|
'name' => $this->nameRules(),
|
||||||
@@ -35,16 +35,14 @@ trait ProfileValidationRules
|
|||||||
*
|
*
|
||||||
* @return array<int, \Illuminate\Contracts\Validation\Rule|array<mixed>|string>
|
* @return array<int, \Illuminate\Contracts\Validation\Rule|array<mixed>|string>
|
||||||
*/
|
*/
|
||||||
protected function emailRules(?int $userId = null): array
|
protected function emailRules(int $userId): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'required',
|
'required',
|
||||||
'string',
|
'string',
|
||||||
'email',
|
'email',
|
||||||
'max:255',
|
'max:255',
|
||||||
$userId === null
|
Rule::unique(User::class)->ignore($userId),
|
||||||
? Rule::unique(User::class)
|
|
||||||
: Rule::unique(User::class)->ignore($userId),
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,30 +5,84 @@ namespace App\Console\Commands;
|
|||||||
use App\Models\Share;
|
use App\Models\Share;
|
||||||
use App\Services\ShareService;
|
use App\Services\ShareService;
|
||||||
use Illuminate\Console\Command;
|
use Illuminate\Console\Command;
|
||||||
|
use Livewire\Features\SupportFileUploads\FileUploadConfiguration;
|
||||||
|
|
||||||
class CleanupExpiredShares extends Command
|
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 $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
|
public function handle(ShareService $shareService): int
|
||||||
{
|
{
|
||||||
$expiredShares = Share::query()
|
$expiredShares = Share::query()
|
||||||
->where(function ($query): void {
|
->where(function ($query): void {
|
||||||
$query->where('expires_at', '<', now())
|
$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();
|
->get();
|
||||||
|
|
||||||
$count = $expiredShares->count();
|
|
||||||
|
|
||||||
foreach ($expiredShares as $share) {
|
foreach ($expiredShares as $share) {
|
||||||
$shareService->deleteShare($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;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,11 +6,14 @@ use App\Models\Share;
|
|||||||
use App\Models\ShareFile;
|
use App\Models\ShareFile;
|
||||||
use App\Services\FileEncryptionService;
|
use App\Services\FileEncryptionService;
|
||||||
use App\Services\ShareService;
|
use App\Services\ShareService;
|
||||||
|
use GuzzleHttp\Psr7\PumpStream;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
|
||||||
use Symfony\Component\HttpFoundation\HeaderUtils;
|
use Symfony\Component\HttpFoundation\HeaderUtils;
|
||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
use ZipArchive;
|
use ZipStream\CompressionMethod;
|
||||||
|
use ZipStream\OperationMode;
|
||||||
|
use ZipStream\ZipStream;
|
||||||
|
|
||||||
class DownloadController extends Controller
|
class DownloadController extends Controller
|
||||||
{
|
{
|
||||||
@@ -20,89 +23,174 @@ 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. The
|
||||||
|
* archive's size is worked out from the files' sizes first, so the browser shows its progress
|
||||||
|
* and notices a download cut short. The private text is left out: it is only ever shown on the
|
||||||
|
* page.
|
||||||
*/
|
*/
|
||||||
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');
|
$share->load(['files' => fn ($query) => $query->where('is_text', false)]);
|
||||||
$key = $this->resolveDecryptionKey($share);
|
abort_if($share->files->isEmpty(), 404);
|
||||||
|
|
||||||
$tempPath = tempnam(sys_get_temp_dir(), 'sealshare_');
|
$key = $this->shareService->sessionDecryptionKey($share, $request->session());
|
||||||
|
|
||||||
$zip = new ZipArchive;
|
// Counted before the body streams: the session is saved by then.
|
||||||
$zip->open($tempPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
|
abort_unless($this->shareService->claimDownload($share, $request->session()), 404);
|
||||||
|
|
||||||
|
$zip = new ZipStream(
|
||||||
|
operationMode: OperationMode::SIMULATE_STRICT,
|
||||||
|
defaultCompressionMethod: CompressionMethod::STORE,
|
||||||
|
defaultEnableZeroHeader: true,
|
||||||
|
sendHttpHeaders: false,
|
||||||
|
flushOutput: true,
|
||||||
|
);
|
||||||
|
|
||||||
foreach ($share->files as $file) {
|
foreach ($share->files as $file) {
|
||||||
$encryptedPath = Storage::disk('shares')->path($share->token.'/'.basename($file->stored_path));
|
$zip->addFileFromCallback(
|
||||||
$content = $this->encryptionService->decryptFile($encryptedPath, $key);
|
fileName: $this->archiveName($file),
|
||||||
|
exactSize: $file->file_size,
|
||||||
$filename = $file->relative_path ?: $file->original_name;
|
callback: fn (): PumpStream => $this->decryptedStream($share, $file, $key),
|
||||||
$filename = str_replace('\\', '/', $filename);
|
);
|
||||||
|
|
||||||
if (str_starts_with($filename, '/') || str_contains($filename, '..')) {
|
|
||||||
$filename = basename($filename);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$zip->addFromString($filename, $content);
|
$size = $zip->finish();
|
||||||
}
|
|
||||||
|
|
||||||
$zip->close();
|
return new StreamedResponse(function () use ($zip): void {
|
||||||
|
// A large share takes longer than any request limit to send.
|
||||||
|
set_time_limit(0);
|
||||||
|
|
||||||
$this->shareService->recordDownload($share);
|
$zip->executeSimulation();
|
||||||
|
}, 200, [
|
||||||
return response()->download($tempPath, 'share-'.$share->token.'.zip', [
|
|
||||||
'Content-Type' => 'application/zip',
|
'Content-Type' => 'application/zip',
|
||||||
])->deleteFileAfterSend(true);
|
'Content-Length' => $size,
|
||||||
|
'Content-Disposition' => HeaderUtils::makeDisposition('attachment', 'share-'.$share->token.'.zip'),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Download a single file.
|
* Download a single file; never the private text, which is only ever shown on the page. A
|
||||||
|
* `Range` request gets the bytes from where an interrupted download stopped, so the browser,
|
||||||
|
* or the page's folder download, resumes it instead of starting over.
|
||||||
*/
|
*/
|
||||||
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);
|
abort_if($shareFile->share_id !== $share->id || $shareFile->is_text, 404);
|
||||||
|
|
||||||
$key = $this->resolveDecryptionKey($share);
|
$key = $this->shareService->sessionDecryptionKey($share, $request->session());
|
||||||
|
|
||||||
|
$size = $shareFile->file_size;
|
||||||
|
$etag = '"'.hash('xxh128', $shareFile->stored_path).'"';
|
||||||
|
[$start, $end] = $this->requestedRange($request, $size, $etag) ?? [0, $size - 1];
|
||||||
|
|
||||||
|
abort_unless($this->shareService->claimDownload($share, $request->session()), 404);
|
||||||
|
|
||||||
$encryptedPath = Storage::disk('shares')->path($share->token.'/'.basename($shareFile->stored_path));
|
$encryptedPath = Storage::disk('shares')->path($share->token.'/'.basename($shareFile->stored_path));
|
||||||
$mimeType = $shareFile->mime_type ?? 'application/octet-stream';
|
$partial = $start > 0 || $end < $size - 1;
|
||||||
|
|
||||||
$headers = [
|
$headers = [
|
||||||
'Content-Type' => $mimeType,
|
'Content-Type' => $shareFile->mime_type ?? 'application/octet-stream',
|
||||||
'Content-Disposition' => HeaderUtils::makeDisposition(
|
'Content-Disposition' => HeaderUtils::makeDisposition(
|
||||||
'attachment',
|
'attachment',
|
||||||
$shareFile->original_name,
|
$shareFile->original_name,
|
||||||
'download',
|
'download',
|
||||||
),
|
),
|
||||||
|
'Content-Length' => max($end - $start + 1, 0),
|
||||||
|
'Accept-Ranges' => 'bytes',
|
||||||
|
'ETag' => $etag,
|
||||||
];
|
];
|
||||||
|
|
||||||
if ($shareFile->file_size !== null) {
|
if ($partial) {
|
||||||
$headers['Content-Length'] = $shareFile->file_size;
|
$headers['Content-Range'] = "bytes {$start}-{$end}/{$size}";
|
||||||
}
|
}
|
||||||
|
|
||||||
return new StreamedResponse(function () use ($encryptedPath, $key, $share): void {
|
return new StreamedResponse(function () use ($encryptedPath, $key, $start, $end): void {
|
||||||
$this->encryptionService->streamDecryptedFile($encryptedPath, $key);
|
set_time_limit(0);
|
||||||
|
|
||||||
$this->shareService->recordDownload($share);
|
$remaining = $end - $start + 1;
|
||||||
}, 200, $headers);
|
|
||||||
|
foreach ($this->encryptionService->decryptedChunks($encryptedPath, $key, $start) as $chunk) {
|
||||||
|
if (strlen($chunk) >= $remaining) {
|
||||||
|
echo substr($chunk, 0, $remaining);
|
||||||
|
flush();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
echo $chunk;
|
||||||
|
flush();
|
||||||
|
$remaining -= strlen($chunk);
|
||||||
|
}
|
||||||
|
}, $partial ? 206 : 200, $headers);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve the decryption key from session or share.
|
* The first and last byte a single `Range` request asks for, or null to send the whole file:
|
||||||
|
* without a range, with one this does not read (several ranges, another unit), or with an
|
||||||
|
* `If-Range` naming another version of the file. A range wholly past the end is refused.
|
||||||
|
*
|
||||||
|
* @return array{0: int, 1: int}|null
|
||||||
*/
|
*/
|
||||||
private function resolveDecryptionKey(Share $share): string
|
private function requestedRange(Request $request, int $size, string $etag): ?array
|
||||||
{
|
{
|
||||||
if ($share->isPasswordProtected()) {
|
$range = (string) $request->header('Range');
|
||||||
$key = session('share_key_'.$share->token);
|
|
||||||
|
|
||||||
abort_if(! $key, 403, 'Password required');
|
if ($size === 0 || ! preg_match('/^bytes=(\d*)-(\d*)$/', $range, $matches) || $matches[1].$matches[2] === ''
|
||||||
|
|| ($request->hasHeader('If-Range') && $request->header('If-Range') !== $etag)) {
|
||||||
return $key;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->shareService->getDecryptionKey($share);
|
[$start, $end] = $matches[1] === ''
|
||||||
|
? [max($size - (int) $matches[2], 0), $size - 1]
|
||||||
|
: [(int) $matches[1], $matches[2] === '' ? $size - 1 : min((int) $matches[2], $size - 1)];
|
||||||
|
|
||||||
|
abort_if($start > $end, 416, headers: ['Content-Range' => "bytes */{$size}"]);
|
||||||
|
|
||||||
|
return [$start, $end];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A file's decrypted content as a stream ZipStream reads from.
|
||||||
|
*/
|
||||||
|
private function decryptedStream(Share $share, ShareFile $file, string $key): PumpStream
|
||||||
|
{
|
||||||
|
$chunks = $this->encryptionService->decryptedChunks(
|
||||||
|
Storage::disk('shares')->path($share->token.'/'.basename($file->stored_path)),
|
||||||
|
$key,
|
||||||
|
);
|
||||||
|
|
||||||
|
return new PumpStream(function () use ($chunks): string|false {
|
||||||
|
while ($chunks->valid() && $chunks->current() === '') {
|
||||||
|
$chunks->next();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $chunks->valid()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$chunk = $chunks->current();
|
||||||
|
$chunks->next();
|
||||||
|
|
||||||
|
return $chunk;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,7 +17,10 @@ class SystemPasswordGate
|
|||||||
return $next($request);
|
return $next($request);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($request->session()->get('system_password_verified') === true) {
|
// A fingerprint of the current hash: changing the system password ends every earlier verification.
|
||||||
|
$verified = $request->session()->get('system_password_verified');
|
||||||
|
|
||||||
|
if (is_string($verified) && hash_equals(hash('sha256', $systemPassword), $verified)) {
|
||||||
return $next($request);
|
return $next($request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,14 +15,20 @@ class AdminDashboard extends Component
|
|||||||
use WithPagination;
|
use WithPagination;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The columns the table can be sorted by.
|
* The orders the shares list offers, each a column and a direction.
|
||||||
*
|
*
|
||||||
* @var list<string>
|
* @var array<string, array{0: string, 1: string}>
|
||||||
*/
|
*/
|
||||||
public const SORTABLE = ['token', 'files_count', 'total_size', 'download_count', 'expires_at', 'created_at'];
|
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'],
|
||||||
|
];
|
||||||
|
|
||||||
/** @var array{column: string, direction: string} */
|
public string $sort = 'newest';
|
||||||
public array $sortBy = ['column' => 'created_at', 'direction' => 'desc'];
|
|
||||||
|
|
||||||
/** The share the delete dialog is asking about, while it is open. */
|
/** The share the delete dialog is asking about, while it is open. */
|
||||||
public ?int $deletingShareId = null;
|
public ?int $deletingShareId = null;
|
||||||
@@ -35,28 +41,45 @@ class AdminDashboard extends Component
|
|||||||
$this->deletingShareId = null;
|
$this->deletingShareId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A new order starts again from the first page.
|
||||||
|
*/
|
||||||
|
public function updatedSort(): void
|
||||||
|
{
|
||||||
|
$this->resetPage();
|
||||||
|
}
|
||||||
|
|
||||||
public function render(): mixed
|
public function render(): mixed
|
||||||
{
|
{
|
||||||
$shareService = app(ShareService::class);
|
$shareService = app(ShareService::class);
|
||||||
|
|
||||||
// The sort comes from the browser: only a known column and direction reach the query.
|
// The sort comes from the browser: only a known order reaches the query.
|
||||||
$column = in_array($this->sortBy['column'] ?? null, self::SORTABLE, true) ? $this->sortBy['column'] : 'created_at';
|
[$column, $direction] = self::SORTS[$this->sort] ?? self::SORTS['newest'];
|
||||||
$direction = ($this->sortBy['direction'] ?? null) === 'asc' ? 'asc' : 'desc';
|
|
||||||
|
|
||||||
|
// Shares whose files are still being uploaded are not shares yet; their bytes do count as used space.
|
||||||
$shares = Share::query()
|
$shares = Share::query()
|
||||||
->withCount('files')
|
->whereNotNull('completed_at')
|
||||||
|
// A share's private text is not one of its files.
|
||||||
|
->withCount(['files' => fn ($query) => $query->where('is_text', false)])
|
||||||
|
->withExists('textFile')
|
||||||
|
// 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)
|
->orderBy($column, $direction)
|
||||||
|
->orderByDesc('id')
|
||||||
->paginate(15);
|
->paginate(15);
|
||||||
|
|
||||||
return view('livewire.admin.admin-dashboard', [
|
return view('livewire.admin.admin-dashboard', [
|
||||||
'shares' => $shares,
|
'shares' => $shares,
|
||||||
'totalShares' => Share::query()->count(),
|
'totalShares' => Share::query()->whereNotNull('completed_at')->count(),
|
||||||
'activeShares' => Share::query()->where(function ($q) {
|
'activeShares' => Share::query()->whereNotNull('completed_at')->where(function ($q) {
|
||||||
$q->whereNull('expires_at')->orWhere('expires_at', '>', now());
|
$q->whereNull('expires_at')->orWhere('expires_at', '>', now());
|
||||||
|
})->where(function ($q) {
|
||||||
|
$q->whereNull('max_downloads')->orWhereColumn('download_count', '<', 'max_downloads');
|
||||||
})->count(),
|
})->count(),
|
||||||
'totalFiles' => ShareFile::query()->count(),
|
'totalFiles' => ShareFile::query()->where('is_text', false)->whereHas('share', fn ($query) => $query->whereNotNull('completed_at'))->count(),
|
||||||
'usedSpace' => $shareService->getTotalUsedSpace(),
|
'usedSpace' => $shareService->getTotalUsedSpace(),
|
||||||
'maxQuota' => $shareService->getMaxStorageQuota(),
|
'maxQuota' => $shareService->getMaxStorageQuota(),
|
||||||
|
'version' => config('app.version'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,11 @@
|
|||||||
namespace App\Livewire\Admin;
|
namespace App\Livewire\Admin;
|
||||||
|
|
||||||
use App\Models\Setting;
|
use App\Models\Setting;
|
||||||
|
use App\Models\Share;
|
||||||
|
use App\Services\PasswordGeneratorService;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Livewire\Attributes\Layout;
|
use Livewire\Attributes\Layout;
|
||||||
use Livewire\Component;
|
use Livewire\Component;
|
||||||
@@ -35,6 +38,23 @@ class AdminSettings extends Component
|
|||||||
|
|
||||||
public bool $allowNeverExpire = false;
|
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 $siteTitle = '';
|
||||||
|
|
||||||
public string $siteDescription = '';
|
public string $siteDescription = '';
|
||||||
@@ -51,54 +71,39 @@ class AdminSettings extends Component
|
|||||||
{
|
{
|
||||||
$this->colorProfile = Scheme::profile() ?? '';
|
$this->colorProfile = Scheme::profile() ?? '';
|
||||||
$this->defaultExpiration = Setting::get('default_expiration', '') ?? '';
|
$this->defaultExpiration = Setting::get('default_expiration', '') ?? '';
|
||||||
$this->maxFileSize = min(
|
$this->maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024) / (1024 * 1024);
|
||||||
(int) Setting::get('max_file_size', 100 * 1024 * 1024) / (1024 * 1024),
|
|
||||||
self::phpMaxUploadMb(),
|
|
||||||
);
|
|
||||||
$this->maxStorageQuota = (int) Setting::get('max_storage_quota', 20 * 1024 * 1024 * 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->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->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->allowNeverExpire = (bool) Setting::get('allow_never_expire', false);
|
||||||
$this->siteTitle = Setting::get('site_title', '') ?? '';
|
$this->siteTitle = Setting::get('site_title', '') ?? '';
|
||||||
$this->siteDescription = Setting::get('site_description', '') ?? '';
|
$this->siteDescription = Setting::get('site_description', '') ?? '';
|
||||||
}
|
|
||||||
|
|
||||||
public static function phpMaxUploadMb(): int
|
$passwordOptions = app(PasswordGeneratorService::class)->options();
|
||||||
{
|
$this->passwordGeneratorMode = $passwordOptions['mode'];
|
||||||
$parse = function (string $value): int {
|
$this->passwordGeneratorType = $passwordOptions['type'];
|
||||||
$value = trim($value);
|
$this->passwordLength = $passwordOptions['length'];
|
||||||
$last = strtolower($value[strlen($value) - 1]);
|
$this->passwordCharacterSets = $passwordOptions['characterSets'];
|
||||||
$num = (int) $value;
|
$this->passwordAvoidAmbiguous = $passwordOptions['avoidAmbiguous'];
|
||||||
|
$this->passphraseWords = $passwordOptions['words'];
|
||||||
return match ($last) {
|
$this->passphraseSeparator = $passwordOptions['separator'];
|
||||||
'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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function saveSettings(): void
|
public function saveSettings(): void
|
||||||
{
|
{
|
||||||
$phpMaxMb = self::phpMaxUploadMb();
|
$validated = $this->validate([
|
||||||
|
|
||||||
$this->validate([
|
|
||||||
'colorProfile' => ['required', 'string', Rule::in(array_keys(Scheme::profiles()))],
|
'colorProfile' => ['required', 'string', Rule::in(array_keys(Scheme::profiles()))],
|
||||||
'maxFileSize' => ['required', 'integer', 'min:1', 'max:'.$phpMaxMb],
|
'defaultExpiration' => ['nullable', 'string', Rule::in(array_keys(Share::EXPIRATIONS))],
|
||||||
|
'maxFileSize' => ['required', 'integer', 'min:1'],
|
||||||
'maxStorageQuota' => ['required', 'integer', 'min:1'],
|
'maxStorageQuota' => ['required', 'integer', 'min:1'],
|
||||||
'maxFilesPerShare' => ['required', 'integer', 'min:1'],
|
'maxFilesPerShare' => ['required', 'integer', 'min:1'],
|
||||||
'maxSizePerShare' => ['required', 'integer', 'min:1'],
|
'maxSizePerShare' => ['required', 'integer', 'min:1'],
|
||||||
'siteTitle' => ['nullable', 'string', 'max:255'],
|
'siteTitle' => ['nullable', 'string', 'max:255'],
|
||||||
'siteDescription' => ['nullable', 'string', 'max:1000'],
|
'siteDescription' => ['nullable', 'string', 'max:1000'],
|
||||||
'siteLogo' => ['nullable', 'file', 'mimes:png,jpg,jpeg,gif,webp', 'max:2048'],
|
'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) {
|
if ($this->systemPassword) {
|
||||||
@@ -116,6 +121,8 @@ class AdminSettings extends Component
|
|||||||
Setting::set('site_title', $this->siteTitle ?: null);
|
Setting::set('site_title', $this->siteTitle ?: null);
|
||||||
Setting::set('site_description', $this->siteDescription ?: null);
|
Setting::set('site_description', $this->siteDescription ?: null);
|
||||||
|
|
||||||
|
$this->savePasswordGeneratorSettings($validated);
|
||||||
|
|
||||||
if ($this->siteLogo && is_object($this->siteLogo)) {
|
if ($this->siteLogo && is_object($this->siteLogo)) {
|
||||||
$existingLogo = Setting::get('site_logo');
|
$existingLogo = Setting::get('site_logo');
|
||||||
if ($existingLogo) {
|
if ($existingLogo) {
|
||||||
@@ -132,6 +139,77 @@ class AdminSettings extends Component
|
|||||||
$this->success(__('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
|
public function removeLogo(): void
|
||||||
{
|
{
|
||||||
$existingLogo = Setting::get('site_logo');
|
$existingLogo = Setting::get('site_logo');
|
||||||
@@ -157,10 +235,14 @@ class AdminSettings extends Component
|
|||||||
|
|
||||||
public function render(): mixed
|
public function render(): mixed
|
||||||
{
|
{
|
||||||
|
$passwordGenerator = app(PasswordGeneratorService::class);
|
||||||
|
$passwordPreviewOptions = $this->passwordPreviewOptions();
|
||||||
|
|
||||||
return view('livewire.admin.admin-settings', [
|
return view('livewire.admin.admin-settings', [
|
||||||
'hasSystemPassword' => (bool) Setting::get('system_password'),
|
'hasSystemPassword' => (bool) Setting::get('system_password'),
|
||||||
'currentLogo' => Setting::get('site_logo'),
|
'currentLogo' => Setting::get('site_logo'),
|
||||||
'phpMaxUploadMb' => self::phpMaxUploadMb(),
|
'passwordExample' => $passwordPreviewOptions ? $passwordGenerator->generate($passwordPreviewOptions) : null,
|
||||||
|
'passwordEntropy' => $passwordPreviewOptions ? $passwordGenerator->entropyBits($passwordPreviewOptions) : null,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+179
-116
@@ -3,24 +3,30 @@
|
|||||||
namespace App\Livewire;
|
namespace App\Livewire;
|
||||||
|
|
||||||
use App\Models\Setting;
|
use App\Models\Setting;
|
||||||
|
use App\Models\Share;
|
||||||
|
use App\Models\ShareFile;
|
||||||
|
use App\Services\PasswordGeneratorService;
|
||||||
use App\Services\ShareService;
|
use App\Services\ShareService;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Carbon\CarbonInterval;
|
||||||
|
use Illuminate\Support\Facades\Crypt;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Livewire\Attributes\Layout;
|
use Livewire\Attributes\Layout;
|
||||||
|
use Livewire\Attributes\Locked;
|
||||||
use Livewire\Component;
|
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')]
|
#[Layout('layouts.app')]
|
||||||
class FileUploader extends Component
|
class FileUploader extends Component
|
||||||
{
|
{
|
||||||
use WithFileUploads;
|
/** The pending share this page uploads into: created with the first file, one per page load. */
|
||||||
|
#[Locked]
|
||||||
/** @var array<int, TemporaryUploadedFile> */
|
public ?string $pendingToken = null;
|
||||||
public array $files = [];
|
|
||||||
|
|
||||||
/** @var array<int, string|null> */
|
|
||||||
public array $relativePaths = [];
|
|
||||||
|
|
||||||
public bool $usePassword = false;
|
public bool $usePassword = false;
|
||||||
|
|
||||||
@@ -38,165 +44,222 @@ class FileUploader extends Component
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle an upload the temporary upload endpoint did not accept.
|
* 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`.
|
||||||
*
|
*
|
||||||
* Validation errors (a 422) mean the whole file reached the server and was
|
* @param array<int, array{name?: mixed, size?: mixed, path?: mixed}> $files
|
||||||
* rejected there, so the real reason is logged for the administrator rather
|
* @return array<int, array{id: int, url: string, key: string, noncePrefix: string, chunkSize: int, chunkCount: int}|null>
|
||||||
* than guessed at in front of the user. Anything else is a transport failure.
|
|
||||||
*/
|
*/
|
||||||
public function _uploadErrored($name, $errorsInJson, $isMultiple): void
|
public function registerFiles(array $files, ShareService $shareService): array
|
||||||
{
|
{
|
||||||
$this->dispatch('upload:errored', name: $name)->self();
|
$this->resetErrorBag('files');
|
||||||
|
|
||||||
$errors = is_null($errorsInJson) ? null : (json_decode($errorsInJson, true)['errors'] ?? null);
|
$targets = [];
|
||||||
|
|
||||||
if ($errors) {
|
foreach ($files as $file) {
|
||||||
Log::warning('File upload rejected by the temporary upload endpoint.', ['errors' => $errors]);
|
try {
|
||||||
|
$shareFile = $shareService->registerFile(
|
||||||
throw ValidationException::withMessages([
|
$this->pendingShare(),
|
||||||
'files' => __('Upload failed: the server could not accept the file. Please try again or contact the administrator.'),
|
(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]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$maxFileSizeMb = (int) ((int) Setting::get('max_file_size', 100 * 1024 * 1024) / (1024 * 1024));
|
$targets[] = null;
|
||||||
|
|
||||||
throw ValidationException::withMessages([
|
continue;
|
||||||
'files' => __('Upload failed: file may be too large (max :max MB) or the connection was interrupted.', ['max' => $maxFileSizeMb]),
|
}
|
||||||
]);
|
|
||||||
|
$this->rememberPendingShare($shareFile->share);
|
||||||
|
|
||||||
|
$targets[] = $this->uploadTarget($shareFile, $shareService);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $targets;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate a freshly uploaded batch of files.
|
* Register the private text as the share is created, in place of any text an earlier attempt
|
||||||
|
* registered, and hand the browser what it encrypts and sends it with. Only its size in UTF-8
|
||||||
|
* bytes reaches the server here: the text itself arrives encrypted, like a file. Nothing is
|
||||||
|
* registered for an empty text; a text an admin limit refuses gets `null` and the reason under
|
||||||
|
* `text`.
|
||||||
*
|
*
|
||||||
* Dispatches `files-processed` so the front end can drop its "uploading" state.
|
* @return array{id: int, url: string, key: string, noncePrefix: string, chunkSize: int, chunkCount: int}|null
|
||||||
* This runs for every batch, including additional files added to an existing
|
|
||||||
* selection, which a one-off `x-init` on the file list cannot cover.
|
|
||||||
*/
|
*/
|
||||||
public function updatedFiles(): void
|
public function registerText(int $size, ShareService $shareService): ?array
|
||||||
{
|
{
|
||||||
$this->dispatch('files-processed')->self();
|
$this->resetErrorBag('text');
|
||||||
|
|
||||||
$maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024);
|
$existingText = $this->pendingShare()?->textFile()->first();
|
||||||
$maxFileSizeMb = $maxFileSize / (1024 * 1024);
|
|
||||||
$maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
|
if ($existingText !== null) {
|
||||||
|
$shareService->removeFile($existingText);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($size === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$shareFile = $shareService->registerFile($this->pendingShare(), 'text.txt', $size, null, isText: true);
|
||||||
|
} catch (ValidationException $e) {
|
||||||
|
$this->addError('text', $e->errors()['files'][0]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->rememberPendingShare($shareFile->share);
|
||||||
|
|
||||||
|
return $this->uploadTarget($shareFile, $shareService);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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');
|
$this->resetErrorBag('files');
|
||||||
|
|
||||||
if (count($this->files) > $maxFilesPerShare) {
|
|
||||||
$this->addError('files', __('Too many files. Maximum :max files allowed per share.', ['max' => $maxFilesPerShare]));
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($this->files as $file) {
|
/**
|
||||||
if ($file->getSize() > $maxFileSize) {
|
* Fill in a generated password as protection is switched on, when the admin chose "Prefilled".
|
||||||
$this->addError('files', __('":name" is too large (:size MB). Maximum file size is :max MB.', [
|
* A password already in the field stays.
|
||||||
'name' => $file->getClientOriginalName(),
|
*/
|
||||||
'size' => round($file->getSize() / (1024 * 1024), 1),
|
public function updatedUsePassword(bool $value): void
|
||||||
'max' => (int) $maxFileSizeMb,
|
|
||||||
]));
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function removeFile(int $index): void
|
|
||||||
{
|
{
|
||||||
unset($this->files[$index], $this->relativePaths[$index]);
|
$passwordGenerator = app(PasswordGeneratorService::class);
|
||||||
$this->files = array_values($this->files);
|
|
||||||
$this->relativePaths = array_values($this->relativePaths);
|
if ($value && $this->password === '' && $passwordGenerator->mode() === 'prefill') {
|
||||||
|
$this->password = $passwordGenerator->generate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function generatePassword(PasswordGeneratorService $passwordGenerator): void
|
||||||
|
{
|
||||||
|
if ($passwordGenerator->mode() === 'off') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->password = $passwordGenerator->generate();
|
||||||
|
$this->resetErrorBag('password');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function createShare(ShareService $shareService): void
|
public function createShare(ShareService $shareService): void
|
||||||
{
|
{
|
||||||
$maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
|
$rules = [];
|
||||||
$maxSizePerShare = (int) Setting::get('max_size_per_share', 2 * 1024 * 1024 * 1024);
|
|
||||||
$maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024);
|
|
||||||
|
|
||||||
$rules = [
|
if (! Setting::get('allow_never_expire', false)) {
|
||||||
'files' => ['required', 'array', 'min:1', 'max:'.$maxFilesPerShare],
|
$rules['expiration'] = ['required', 'string', Rule::in(array_keys(Share::EXPIRATIONS))];
|
||||||
'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 ($this->usePassword) {
|
if ($this->usePassword) {
|
||||||
$rules['password'] = ['required', 'string', 'min:8'];
|
$rules['password'] = ['required', 'string', 'min:8'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($rules !== []) {
|
||||||
$this->validate($rules, [
|
$this->validate($rules, [
|
||||||
'expiration.required' => __('An expiration time is required.'),
|
'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 ($shareService->isStorageFull()) {
|
$pendingShare = $this->pendingShare();
|
||||||
$this->addError('files', __('Storage is full. Please contact the administrator.'));
|
|
||||||
|
if ($pendingShare === null) {
|
||||||
|
$this->addError('files', __('Add files or a text to share.'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$totalSize = collect($this->files)->sum(fn ($file) => $file->getSize());
|
$share = $shareService->completeShare($pendingShare, [
|
||||||
|
|
||||||
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, [
|
|
||||||
'password' => $this->usePassword ? $this->password : null,
|
'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,
|
'max_downloads' => $this->maxDownloads ?: null,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
session()->put('pending_shares', array_values(array_diff(session('pending_shares', []), [$share->token])));
|
||||||
|
session()->push('created_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);
|
$this->redirect(route('share.created', $share), navigate: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function render(): mixed
|
public function render(): mixed
|
||||||
{
|
{
|
||||||
$shareService = app(ShareService::class);
|
$shareService = app(ShareService::class);
|
||||||
|
$pendingFiles = $this->pendingShare()?->files()->where('is_text', false)->orderBy('id')->get() ?? collect();
|
||||||
|
|
||||||
return view('livewire.file-uploader', [
|
return view('livewire.file-uploader', [
|
||||||
|
'pendingFiles' => $pendingFiles,
|
||||||
|
'allFilesUploaded' => $pendingFiles->every(fn ($file): bool => $file->completed_at !== null),
|
||||||
|
'maxTextBytes' => ShareFile::MAX_TEXT_BYTES,
|
||||||
'isStorageFull' => $shareService->isStorageFull(),
|
'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),
|
'allowNeverExpire' => (bool) Setting::get('allow_never_expire', false),
|
||||||
|
'passwordGeneratorMode' => app(PasswordGeneratorService::class)->mode(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make a share the one this page uploads into, and let this session reach it.
|
||||||
|
*/
|
||||||
|
private function rememberPendingShare(Share $share): void
|
||||||
|
{
|
||||||
|
if ($this->pendingToken !== $share->token) {
|
||||||
|
$this->pendingToken = $share->token;
|
||||||
|
session()->push('pending_shares', $this->pendingToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the browser encrypts and sends a registered file with.
|
||||||
|
*
|
||||||
|
* @return array{id: int, url: string, key: string, noncePrefix: string, chunkSize: int, chunkCount: int}
|
||||||
|
*/
|
||||||
|
private function uploadTarget(ShareFile $shareFile, ShareService $shareService): array
|
||||||
|
{
|
||||||
|
$header = $shareService->readHeader($shareFile);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,15 @@
|
|||||||
|
|
||||||
namespace App\Livewire;
|
namespace App\Livewire;
|
||||||
|
|
||||||
use App\Models\Setting;
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Validation\Rules\Password;
|
||||||
use Livewire\Attributes\Layout;
|
use Livewire\Attributes\Layout;
|
||||||
use Livewire\Attributes\Validate;
|
use Livewire\Attributes\Validate;
|
||||||
use Livewire\Component;
|
use Livewire\Component;
|
||||||
|
|
||||||
#[Layout('layouts.auth')]
|
#[Layout('layouts.app')]
|
||||||
class SetupWizard extends Component
|
class SetupWizard extends Component
|
||||||
{
|
{
|
||||||
#[Validate('required|string|max:255')]
|
#[Validate('required|string|max:255')]
|
||||||
@@ -19,11 +19,20 @@ class SetupWizard extends Component
|
|||||||
#[Validate('required|string|email|max:255|unique:users')]
|
#[Validate('required|string|email|max:255|unique:users')]
|
||||||
public string $email = '';
|
public string $email = '';
|
||||||
|
|
||||||
#[Validate('required|string|min:8|confirmed')]
|
|
||||||
public string $password = '';
|
public string $password = '';
|
||||||
|
|
||||||
public string $password_confirmation = '';
|
public string $password_confirmation = '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, array<int, mixed>>
|
||||||
|
*/
|
||||||
|
protected function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'password' => ['required', 'string', Password::defaults(), 'confirmed'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public function mount(): void
|
public function mount(): void
|
||||||
{
|
{
|
||||||
if (User::query()->where('is_admin', true)->exists()) {
|
if (User::query()->where('is_admin', true)->exists()) {
|
||||||
@@ -45,14 +54,11 @@ class SetupWizard extends Component
|
|||||||
'name' => $this->name,
|
'name' => $this->name,
|
||||||
'email' => $this->email,
|
'email' => $this->email,
|
||||||
'password' => Hash::make($this->password),
|
'password' => Hash::make($this->password),
|
||||||
'email_verified_at' => now(),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$user->is_admin = true;
|
$user->is_admin = true;
|
||||||
$user->save();
|
$user->save();
|
||||||
|
|
||||||
Setting::set('setup_complete', 'true');
|
|
||||||
|
|
||||||
Auth::login($user);
|
Auth::login($user);
|
||||||
|
|
||||||
$this->redirect(route('admin.dashboard'), navigate: true);
|
$this->redirect(route('admin.dashboard'), navigate: true);
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ namespace App\Livewire;
|
|||||||
use App\Models\Setting;
|
use App\Models\Setting;
|
||||||
use App\Models\Share;
|
use App\Models\Share;
|
||||||
use App\Services\QrCodeService;
|
use App\Services\QrCodeService;
|
||||||
|
use Illuminate\Support\Facades\Crypt;
|
||||||
use Livewire\Attributes\Layout;
|
use Livewire\Attributes\Layout;
|
||||||
|
use Livewire\Attributes\Locked;
|
||||||
use Livewire\Component;
|
use Livewire\Component;
|
||||||
|
|
||||||
#[Layout('layouts.app')]
|
#[Layout('layouts.app')]
|
||||||
@@ -13,9 +15,23 @@ class ShareCreated extends Component
|
|||||||
{
|
{
|
||||||
public Share $share;
|
public Share $share;
|
||||||
|
|
||||||
|
/** The share's password, offered once to the uploader who just set it; `null` on a reload. */
|
||||||
|
#[Locked]
|
||||||
|
public ?string $password = null;
|
||||||
|
|
||||||
public function mount(Share $share): void
|
public function mount(Share $share): void
|
||||||
{
|
{
|
||||||
|
// Only for the session that created the share, and only while recipients can still reach it.
|
||||||
|
abort_unless($share->isCompleted() && ! $share->isExpired() && ! $share->hasReachedDownloadLimit()
|
||||||
|
&& in_array($share->token, session('created_shares', []), true), 404);
|
||||||
|
|
||||||
$this->share = $share;
|
$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
|
public function render(): mixed
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
|
|
||||||
namespace App\Livewire;
|
namespace App\Livewire;
|
||||||
|
|
||||||
use App\Models\Setting;
|
|
||||||
use App\Models\Share;
|
use App\Models\Share;
|
||||||
use App\Services\ShareService;
|
use App\Services\ShareService;
|
||||||
|
use Carbon\CarbonInterval;
|
||||||
use Illuminate\Support\Facades\RateLimiter;
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
use Livewire\Attributes\Layout;
|
use Livewire\Attributes\Layout;
|
||||||
|
use Livewire\Attributes\Locked;
|
||||||
|
use Livewire\Attributes\Renderless;
|
||||||
use Livewire\Attributes\Validate;
|
use Livewire\Attributes\Validate;
|
||||||
use Livewire\Component;
|
use Livewire\Component;
|
||||||
|
|
||||||
@@ -15,34 +17,40 @@ class ShareDownload extends Component
|
|||||||
{
|
{
|
||||||
public Share $share;
|
public Share $share;
|
||||||
|
|
||||||
|
/** Set only by mount() and verifyPassword(): the browser must never unlock the file list. */
|
||||||
|
#[Locked]
|
||||||
public bool $authenticated = false;
|
public bool $authenticated = false;
|
||||||
|
|
||||||
#[Validate('required|string')]
|
#[Validate('required|string')]
|
||||||
public string $password = '';
|
public string $password = '';
|
||||||
|
|
||||||
public function mount(Share $share): void
|
public function mount(Share $share, ShareService $shareService): void
|
||||||
{
|
{
|
||||||
$this->share = $share->load('files');
|
$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);
|
abort(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $share->isPasswordProtected()) {
|
$this->authenticated = ! $share->isPasswordProtected() || (bool) session('share_key_'.$share->token);
|
||||||
$this->authenticated = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($share->isPasswordProtected() && session('share_key_'.$share->token)) {
|
|
||||||
$this->authenticated = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function verifyPassword(ShareService $shareService): void
|
public function verifyPassword(ShareService $shareService): void
|
||||||
{
|
{
|
||||||
$rateLimitKey = 'share-password:'.$this->share->token.'|'.request()->ip();
|
$ipKey = 'share-password:'.$this->share->token.'|'.request()->ip();
|
||||||
|
$shareKey = 'share-password:'.$this->share->token;
|
||||||
|
|
||||||
if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) {
|
// Count before the slow hash check, so parallel requests cannot all pass a read-only check.
|
||||||
$seconds = RateLimiter::availableIn($rateLimitKey);
|
$ipHits = RateLimiter::hit($ipKey, 60);
|
||||||
|
$shareHits = RateLimiter::hit($shareKey, 60);
|
||||||
|
|
||||||
|
if ($ipHits > 5 || $shareHits > 20) {
|
||||||
|
$seconds = max(
|
||||||
|
$ipHits > 5 ? RateLimiter::availableIn($ipKey) : 0,
|
||||||
|
$shareHits > 20 ? RateLimiter::availableIn($shareKey) : 0,
|
||||||
|
);
|
||||||
$this->addError('password', __('Too many attempts. Please try again in :seconds seconds.', ['seconds' => $seconds]));
|
$this->addError('password', __('Too many attempts. Please try again in :seconds seconds.', ['seconds' => $seconds]));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
@@ -51,25 +59,57 @@ class ShareDownload extends Component
|
|||||||
$this->validate();
|
$this->validate();
|
||||||
|
|
||||||
if (! $shareService->verifyPassword($this->share, $this->password)) {
|
if (! $shareService->verifyPassword($this->share, $this->password)) {
|
||||||
RateLimiter::hit($rateLimitKey, 60);
|
|
||||||
$this->addError('password', __('The password is incorrect.'));
|
$this->addError('password', __('The password is incorrect.'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
RateLimiter::clear($rateLimitKey);
|
RateLimiter::clear($ipKey);
|
||||||
|
RateLimiter::clear($shareKey);
|
||||||
|
|
||||||
$encryptionKey = $shareService->getDecryptionKey($this->share, $this->password);
|
$encryptionKey = $shareService->getDecryptionKey($this->share, $this->password);
|
||||||
session(['share_key_'.$this->share->token => $encryptionKey]);
|
session(['share_key_'.$this->share->token => $encryptionKey]);
|
||||||
$this->authenticated = true;
|
$this->authenticated = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The share's private text, for the recipient who pressed "Show text": counted as their
|
||||||
|
* download, as a file would be. Returned to the browser only, never kept in a property, so it
|
||||||
|
* is not in the component's snapshot. Null when the text is no longer available; no abort(),
|
||||||
|
* which would open Livewire's error modal. Renderless: a re-render would morph the download
|
||||||
|
* note Alpine just switched back into the one it hid.
|
||||||
|
*/
|
||||||
|
#[Renderless]
|
||||||
|
public function revealText(ShareService $shareService): ?string
|
||||||
|
{
|
||||||
|
$share = $this->share;
|
||||||
|
|
||||||
|
if (! $share->isCompleted() || $share->isExpired() || ! $share->hasText()
|
||||||
|
|| ($share->isPasswordProtected() && ! session('share_key_'.$share->token))
|
||||||
|
|| ! $shareService->claimDownload($share, session()->driver())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $shareService->readText($share, $shareService->sessionDecryptionKey($share, session()->driver()));
|
||||||
|
}
|
||||||
|
|
||||||
public function render(): mixed
|
public function render(): mixed
|
||||||
{
|
{
|
||||||
|
$shareService = app(ShareService::class);
|
||||||
|
$files = $this->share->files->where('is_text', false)->values();
|
||||||
|
|
||||||
return view('livewire.share-download', [
|
return view('livewire.share-download', [
|
||||||
'siteTitle' => Setting::get('site_title'),
|
'files' => $files,
|
||||||
'siteDescription' => Setting::get('site_description'),
|
'downloads' => $files->map(fn ($file): array => [
|
||||||
'siteLogo' => Setting::get('site_logo'),
|
'id' => $file->id,
|
||||||
|
'path' => $file->relative_path ?: $file->original_name,
|
||||||
|
'size' => $file->file_size,
|
||||||
|
'url' => route('share.download.file', [$this->share, $file]),
|
||||||
|
]),
|
||||||
|
'hasText' => $this->share->files->contains('is_text', true),
|
||||||
|
'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(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,12 @@ namespace App\Livewire;
|
|||||||
|
|
||||||
use App\Models\Setting;
|
use App\Models\Setting;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
use Livewire\Attributes\Layout;
|
use Livewire\Attributes\Layout;
|
||||||
use Livewire\Attributes\Validate;
|
use Livewire\Attributes\Validate;
|
||||||
use Livewire\Component;
|
use Livewire\Component;
|
||||||
|
|
||||||
#[Layout('layouts.auth')]
|
#[Layout('layouts.app')]
|
||||||
class SystemPasswordPrompt extends Component
|
class SystemPasswordPrompt extends Component
|
||||||
{
|
{
|
||||||
#[Validate('required|string')]
|
#[Validate('required|string')]
|
||||||
@@ -16,6 +17,23 @@ class SystemPasswordPrompt extends Component
|
|||||||
|
|
||||||
public function verify(): void
|
public function verify(): void
|
||||||
{
|
{
|
||||||
|
$ipKey = 'system-password|'.request()->ip();
|
||||||
|
$globalKey = 'system-password';
|
||||||
|
|
||||||
|
// Count before the slow hash check, so parallel requests cannot all pass a read-only check.
|
||||||
|
$ipHits = RateLimiter::hit($ipKey, 60);
|
||||||
|
$globalHits = RateLimiter::hit($globalKey, 60);
|
||||||
|
|
||||||
|
if ($ipHits > 5 || $globalHits > 20) {
|
||||||
|
$seconds = max(
|
||||||
|
$ipHits > 5 ? RateLimiter::availableIn($ipKey) : 0,
|
||||||
|
$globalHits > 20 ? RateLimiter::availableIn($globalKey) : 0,
|
||||||
|
);
|
||||||
|
$this->addError('password', __('Too many attempts. Please try again in :seconds seconds.', ['seconds' => $seconds]));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
$this->validate();
|
$this->validate();
|
||||||
|
|
||||||
$systemPassword = Setting::get('system_password');
|
$systemPassword = Setting::get('system_password');
|
||||||
@@ -26,7 +44,10 @@ class SystemPasswordPrompt extends Component
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
session(['system_password_verified' => true]);
|
RateLimiter::clear($ipKey);
|
||||||
|
RateLimiter::clear($globalKey);
|
||||||
|
|
||||||
|
session(['system_password_verified' => hash('sha256', $systemPassword)]);
|
||||||
|
|
||||||
$this->redirect(route('upload'), navigate: true);
|
$this->redirect(route('upload'), navigate: true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,20 +5,38 @@ namespace App\Models;
|
|||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||||
|
|
||||||
class Share extends Model
|
class Share extends Model
|
||||||
{
|
{
|
||||||
use HasFactory;
|
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 = [
|
protected $fillable = [
|
||||||
'token',
|
'token',
|
||||||
'password',
|
'password',
|
||||||
'encryption_key',
|
'encryption_key',
|
||||||
'encryption_salt',
|
'encryption_salt',
|
||||||
|
'wrapped_key',
|
||||||
'expires_at',
|
'expires_at',
|
||||||
'max_downloads',
|
'max_downloads',
|
||||||
'download_count',
|
'download_count',
|
||||||
'total_size',
|
'total_size',
|
||||||
|
'completed_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,8 +48,10 @@ class Share extends Model
|
|||||||
'expires_at' => 'datetime',
|
'expires_at' => 'datetime',
|
||||||
'max_downloads' => 'integer',
|
'max_downloads' => 'integer',
|
||||||
'download_count' => 'integer',
|
'download_count' => 'integer',
|
||||||
|
'last_downloaded_at' => 'datetime',
|
||||||
'total_size' => 'integer',
|
'total_size' => 'integer',
|
||||||
'encryption_key' => 'encrypted',
|
'encryption_key' => 'encrypted',
|
||||||
|
'completed_at' => 'datetime',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,6 +63,30 @@ class Share extends Model
|
|||||||
return $this->hasMany(ShareFile::class);
|
return $this->hasMany(ShareFile::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The share's private text, stored as one of its files.
|
||||||
|
*
|
||||||
|
* @return HasOne<ShareFile, $this>
|
||||||
|
*/
|
||||||
|
public function textFile(): HasOne
|
||||||
|
{
|
||||||
|
return $this->hasOne(ShareFile::class)->where('is_text', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasText(): bool
|
||||||
|
{
|
||||||
|
return $this->textFile()->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
public function isExpired(): bool
|
||||||
{
|
{
|
||||||
return $this->expires_at && $this->expires_at->isPast();
|
return $this->expires_at && $this->expires_at->isPast();
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ class ShareFile extends Model
|
|||||||
{
|
{
|
||||||
use HasFactory;
|
use HasFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The most a share's private text may hold, in UTF-8 bytes: one chunk of the upload pipeline.
|
||||||
|
*/
|
||||||
|
public const MAX_TEXT_BYTES = 100 * 1024;
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'share_id',
|
'share_id',
|
||||||
'original_name',
|
'original_name',
|
||||||
@@ -17,6 +22,9 @@ class ShareFile extends Model
|
|||||||
'stored_path',
|
'stored_path',
|
||||||
'file_size',
|
'file_size',
|
||||||
'mime_type',
|
'mime_type',
|
||||||
|
'is_text',
|
||||||
|
'uploaded_chunks',
|
||||||
|
'completed_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,6 +34,9 @@ class ShareFile extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'file_size' => 'integer',
|
'file_size' => 'integer',
|
||||||
|
'is_text' => 'boolean',
|
||||||
|
'uploaded_chunks' => 'integer',
|
||||||
|
'completed_at' => 'datetime',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
|
||||||
use Database\Factories\UserFactory;
|
use Database\Factories\UserFactory;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||||
use Illuminate\Notifications\Notifiable;
|
use Illuminate\Notifications\Notifiable;
|
||||||
use Illuminate\Support\Str;
|
|
||||||
use Laravel\Fortify\TwoFactorAuthenticatable;
|
use Laravel\Fortify\TwoFactorAuthenticatable;
|
||||||
|
|
||||||
class User extends Authenticatable
|
class User extends Authenticatable
|
||||||
@@ -51,16 +49,4 @@ class User extends Authenticatable
|
|||||||
'is_admin' => 'boolean',
|
'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('');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,24 +2,19 @@
|
|||||||
|
|
||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use App\Http\Middleware\EnsureAdmin;
|
||||||
|
use App\Http\Middleware\SystemPasswordGate;
|
||||||
use App\Models\Setting;
|
use App\Models\Setting;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Facades\Date;
|
use Illuminate\Support\Facades\Date;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Illuminate\Validation\Rules\Password;
|
use Illuminate\Validation\Rules\Password;
|
||||||
|
use Livewire\Livewire;
|
||||||
use NoNameWeb\LivewireMaterial\Support\Scheme;
|
use NoNameWeb\LivewireMaterial\Support\Scheme;
|
||||||
|
|
||||||
class AppServiceProvider extends ServiceProvider
|
class AppServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* Register any application services.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bootstrap any application services.
|
* Bootstrap any application services.
|
||||||
*/
|
*/
|
||||||
@@ -30,6 +25,9 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
// The colour profile the admin chose in Admin settings; asked each time a page, mail or
|
// 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.
|
// error page draws its colours, so a new choice applies at once in every Octane worker.
|
||||||
Scheme::resolveProfileUsing(fn (): ?string => Setting::get('color_profile'));
|
Scheme::resolveProfileUsing(fn (): ?string => Setting::get('color_profile'));
|
||||||
|
|
||||||
|
// Livewire updates apply a page route's middleware only when it is listed as persistent.
|
||||||
|
Livewire::addPersistentMiddleware([SystemPasswordGate::class, EnsureAdmin::class]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
use App\Actions\Fortify\CreateNewUser;
|
|
||||||
use App\Actions\Fortify\ResetUserPassword;
|
use App\Actions\Fortify\ResetUserPassword;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Auth\Notifications\ResetPassword;
|
||||||
use Illuminate\Cache\RateLimiting\Limit;
|
use Illuminate\Cache\RateLimiting\Limit;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\RateLimiter;
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
@@ -13,14 +14,6 @@ use Laravel\Fortify\Fortify;
|
|||||||
|
|
||||||
class FortifyServiceProvider extends ServiceProvider
|
class FortifyServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* Register any application services.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bootstrap any application services.
|
* Bootstrap any application services.
|
||||||
*/
|
*/
|
||||||
@@ -37,7 +30,12 @@ class FortifyServiceProvider extends ServiceProvider
|
|||||||
private function configureActions(): void
|
private function configureActions(): void
|
||||||
{
|
{
|
||||||
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
|
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
|
||||||
Fortify::createUsersUsing(CreateNewUser::class);
|
|
||||||
|
// From APP_URL, never the request's host: every proxy is trusted, so a forged X-Forwarded-Host would otherwise pick it.
|
||||||
|
ResetPassword::createUrlUsing(fn (User $user, string $token): string => rtrim((string) config('app.url'), '/').route('password.reset', [
|
||||||
|
'token' => $token,
|
||||||
|
'email' => $user->getEmailForPasswordReset(),
|
||||||
|
], false));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,7 +44,6 @@ class FortifyServiceProvider extends ServiceProvider
|
|||||||
private function configureViews(): void
|
private function configureViews(): void
|
||||||
{
|
{
|
||||||
Fortify::loginView(fn () => view('pages::auth.login'));
|
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::twoFactorChallengeView(fn () => view('pages::auth.two-factor-challenge'));
|
||||||
Fortify::confirmPasswordView(fn () => view('pages::auth.confirm-password'));
|
Fortify::confirmPasswordView(fn () => view('pages::auth.confirm-password'));
|
||||||
Fortify::resetPasswordView(fn () => view('pages::auth.reset-password'));
|
Fortify::resetPasswordView(fn () => view('pages::auth.reset-password'));
|
||||||
@@ -65,7 +62,11 @@ class FortifyServiceProvider extends ServiceProvider
|
|||||||
RateLimiter::for('login', function (Request $request) {
|
RateLimiter::for('login', function (Request $request) {
|
||||||
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());
|
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());
|
||||||
|
|
||||||
return Limit::perMinute(5)->by($throttleKey);
|
// The address comes from X-Forwarded-For behind the proxy, so a second limit per e-mail does not use it.
|
||||||
|
return [
|
||||||
|
Limit::perMinute(5)->by($throttleKey),
|
||||||
|
Limit::perMinute(20)->by(Str::transliterate(Str::lower($request->input(Fortify::username())))),
|
||||||
|
];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,30 @@ namespace App\Services;
|
|||||||
|
|
||||||
use Generator;
|
use Generator;
|
||||||
use RuntimeException;
|
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
|
class FileEncryptionService
|
||||||
{
|
{
|
||||||
|
public const HEADER_LENGTH = 19;
|
||||||
|
|
||||||
|
public const TAG_LENGTH = 16;
|
||||||
|
|
||||||
private const CIPHER = 'aes-256-gcm';
|
private const CIPHER = 'aes-256-gcm';
|
||||||
|
|
||||||
private const PBKDF2_ITERATIONS = 100000;
|
private const PBKDF2_ITERATIONS = 100000;
|
||||||
@@ -17,28 +36,23 @@ class FileEncryptionService
|
|||||||
|
|
||||||
private const NONCE_LENGTH = 12;
|
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
|
public function deriveKey(string $password, string $salt): string
|
||||||
{
|
{
|
||||||
return hash_pbkdf2('sha256', $password, hex2bin($salt), self::PBKDF2_ITERATIONS, self::KEY_LENGTH, true);
|
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).
|
* 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:
|
* The result names its algorithm and parameters, so they can be raised later without breaking
|
||||||
* [8 bytes: "SEALCHK1" magic]
|
* shares wrapped before: `argon2id$<opslimit>$<memlimit>$<salt>$<nonce>$<box>`, in hex.
|
||||||
* [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)]
|
|
||||||
*/
|
*/
|
||||||
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) {
|
$wrappingKey = $this->deriveWrappingKey($password, $salt, $opslimit, $memlimit);
|
||||||
throw new RuntimeException("Cannot read source file: {$sourcePath}");
|
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
|
||||||
|
$box = sodium_crypto_secretbox(hex2bin($dataKeyHex), $nonce, $wrappingKey);
|
||||||
|
|
||||||
|
sodium_memzero($wrappingKey);
|
||||||
|
|
||||||
|
return implode('$', [self::WRAPPED_KEY_ALGORITHM, $opslimit, $memlimit, bin2hex($salt), bin2hex($nonce), bin2hex($box)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$dest = fopen($destPath, 'wb');
|
/**
|
||||||
|
* Unwrap a share's data key with its password; returns the key as hex.
|
||||||
|
*/
|
||||||
|
public function unwrapKey(string $wrappedKey, string $password): string
|
||||||
|
{
|
||||||
|
$parts = explode('$', $wrappedKey);
|
||||||
|
|
||||||
if ($dest === false) {
|
if (count($parts) !== 6 || $parts[0] !== self::WRAPPED_KEY_ALGORITHM) {
|
||||||
fclose($source);
|
throw new RuntimeException('Unsupported wrapped key');
|
||||||
|
|
||||||
throw new RuntimeException("Cannot write encrypted file: {$destPath}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
[, $opslimit, $memlimit, $salt, $nonce, $box] = $parts;
|
||||||
$binaryKey = $this->normalizeToBinaryKey($key);
|
|
||||||
$baseNonce = random_bytes(self::NONCE_LENGTH);
|
|
||||||
$chunkSize = self::DEFAULT_CHUNK_SIZE;
|
|
||||||
|
|
||||||
// Write header
|
$wrappingKey = $this->deriveWrappingKey($password, hex2bin($salt), (int) $opslimit, (int) $memlimit);
|
||||||
fwrite($dest, self::MAGIC_HEADER);
|
$dataKey = sodium_crypto_secretbox_open(hex2bin($box), hex2bin($nonce), $wrappingKey);
|
||||||
fwrite($dest, pack('N', $chunkSize));
|
|
||||||
fwrite($dest, $baseNonce);
|
|
||||||
|
|
||||||
$chunkIndex = 0;
|
sodium_memzero($wrappingKey);
|
||||||
|
|
||||||
while (! feof($source)) {
|
if ($dataKey === false) {
|
||||||
$plaintext = fread($source, $chunkSize);
|
throw new RuntimeException('Unwrapping failed - wrong password or corrupted key');
|
||||||
|
|
||||||
if ($plaintext === false || $plaintext === '') {
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$nonce = $this->deriveChunkNonce($baseNonce, $chunkIndex);
|
return bin2hex($dataKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The header a new encrypted file starts with, with a fresh random nonce prefix.
|
||||||
|
*/
|
||||||
|
public function createHeader(int $chunkSize): string
|
||||||
|
{
|
||||||
|
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),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many chunks a file of this size is sent in; an empty file is one empty chunk.
|
||||||
|
*/
|
||||||
|
public function chunkCount(int $size, int $chunkSize): int
|
||||||
|
{
|
||||||
|
return max(1, intdiv($size + $chunkSize - 1, $chunkSize));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where chunk `$index` starts in the encrypted file.
|
||||||
|
*/
|
||||||
|
public function chunkOffset(int $index, int $chunkSize): int
|
||||||
|
{
|
||||||
|
return self::HEADER_LENGTH + $index * ($chunkSize + self::TAG_LENGTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encrypt one chunk: its ciphertext followed by its tag, as WebCrypto returns it.
|
||||||
|
*/
|
||||||
|
public function encryptChunk(string $plaintext, string $key, string $noncePrefix, int $index, bool $isLast): string
|
||||||
|
{
|
||||||
$tag = '';
|
$tag = '';
|
||||||
|
|
||||||
$ciphertext = openssl_encrypt(
|
$ciphertext = openssl_encrypt(
|
||||||
$plaintext,
|
$plaintext,
|
||||||
self::CIPHER,
|
self::CIPHER,
|
||||||
$binaryKey,
|
$this->normalizeToBinaryKey($key),
|
||||||
OPENSSL_RAW_DATA,
|
OPENSSL_RAW_DATA,
|
||||||
$nonce,
|
$this->chunkNonce($noncePrefix, $index, $isLast),
|
||||||
$tag,
|
$tag,
|
||||||
'',
|
'',
|
||||||
self::TAG_LENGTH,
|
self::TAG_LENGTH,
|
||||||
);
|
);
|
||||||
|
|
||||||
if ($ciphertext === false) {
|
if ($ciphertext === false) {
|
||||||
throw new RuntimeException('Encryption failed at chunk '.$chunkIndex);
|
throw new RuntimeException('Encryption failed at chunk '.$index);
|
||||||
}
|
}
|
||||||
|
|
||||||
fwrite($dest, $tag);
|
return $ciphertext.$tag;
|
||||||
fwrite($dest, $ciphertext);
|
|
||||||
$chunkIndex++;
|
|
||||||
}
|
|
||||||
} catch (RuntimeException $e) {
|
|
||||||
fclose($source);
|
|
||||||
fclose($dest);
|
|
||||||
@unlink($destPath);
|
|
||||||
|
|
||||||
throw $e;
|
|
||||||
}
|
|
||||||
|
|
||||||
fclose($source);
|
|
||||||
fclose($dest);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decrypt a file and return the plaintext content.
|
* Decrypt one chunk, which fails unless its index and last-chunk flag are the ones it was
|
||||||
|
* encrypted with.
|
||||||
*/
|
*/
|
||||||
public function decryptFile(string $encryptedPath, string $key): string
|
public function decryptChunk(string $chunk, string $key, string $noncePrefix, int $index, bool $isLast): string
|
||||||
{
|
{
|
||||||
if ($this->isChunkedFormat($encryptedPath)) {
|
if (strlen($chunk) < self::TAG_LENGTH) {
|
||||||
$parts = [];
|
throw new RuntimeException('Invalid encrypted file: truncated chunk '.$index);
|
||||||
|
|
||||||
foreach ($this->decryptChunks($encryptedPath, $key) as $chunk) {
|
|
||||||
$parts[] = $chunk;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return implode('', $parts);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->decryptLegacy($encryptedPath, $key);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decrypt a file and stream the response.
|
|
||||||
*/
|
|
||||||
public function decryptFileStream(string $encryptedPath, string $key, string $filename, string $mimeType, ?int $fileSize = null): StreamedResponse
|
|
||||||
{
|
|
||||||
$headers = [
|
|
||||||
'Content-Type' => $mimeType ?: 'application/octet-stream',
|
|
||||||
'Content-Disposition' => HeaderUtils::makeDisposition('attachment', $filename, 'download'),
|
|
||||||
];
|
|
||||||
|
|
||||||
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.
|
|
||||||
*/
|
|
||||||
public function streamDecryptedFile(string $encryptedPath, string $key): void
|
|
||||||
{
|
|
||||||
if ($this->isChunkedFormat($encryptedPath)) {
|
|
||||||
foreach ($this->decryptChunks($encryptedPath, $key) as $chunk) {
|
|
||||||
echo $chunk;
|
|
||||||
flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
echo $this->decryptLegacy($encryptedPath, $key);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Normalize a hex key to binary.
|
|
||||||
*/
|
|
||||||
private function normalizeToBinaryKey(string $key): string
|
|
||||||
{
|
|
||||||
return strlen($key) === 64 ? hex2bin($key) : $key;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Derive a unique nonce for a chunk by XORing the chunk index into the last 4 bytes.
|
|
||||||
*/
|
|
||||||
private function deriveChunkNonce(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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a file uses the chunked encryption format.
|
|
||||||
*/
|
|
||||||
private function isChunkedFormat(string $path): bool
|
|
||||||
{
|
|
||||||
$handle = fopen($path, 'rb');
|
|
||||||
|
|
||||||
if ($handle === false) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$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(
|
$plaintext = openssl_decrypt(
|
||||||
$ciphertext,
|
substr($chunk, 0, -self::TAG_LENGTH),
|
||||||
self::CIPHER,
|
self::CIPHER,
|
||||||
$binaryKey,
|
$this->normalizeToBinaryKey($key),
|
||||||
OPENSSL_RAW_DATA,
|
OPENSSL_RAW_DATA,
|
||||||
$nonce,
|
$this->chunkNonce($noncePrefix, $index, $isLast),
|
||||||
$tag,
|
substr($chunk, -self::TAG_LENGTH),
|
||||||
);
|
);
|
||||||
|
|
||||||
if ($plaintext === false) {
|
if ($plaintext === false) {
|
||||||
@@ -271,11 +200,73 @@ 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, from byte
|
||||||
|
* `$offset` of the plaintext on. A `SEALCHK2` file starts at the chunk holding that byte; the
|
||||||
|
* older formats are decrypted from their start and the bytes before it dropped.
|
||||||
*
|
*
|
||||||
* @return Generator<int, string>
|
* @return Generator<int, string>
|
||||||
*/
|
*/
|
||||||
private function decryptChunks(string $encryptedPath, string $key): Generator
|
public function decryptedChunks(string $encryptedPath, string $key, int $offset = 0): Generator
|
||||||
|
{
|
||||||
|
$magic = (string) file_get_contents($encryptedPath, false, null, 0, 8);
|
||||||
|
|
||||||
|
if ($magic === self::MAGIC) {
|
||||||
|
yield from $this->decryptChunks($encryptedPath, $key, $offset);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$chunks = $magic === self::LEGACY_CHUNKED_MAGIC
|
||||||
|
? $this->decryptLegacyChunks($encryptedPath, $key)
|
||||||
|
: [$this->decryptLegacy($encryptedPath, $key)];
|
||||||
|
|
||||||
|
foreach ($chunks as $chunk) {
|
||||||
|
if ($offset >= strlen($chunk)) {
|
||||||
|
$offset -= strlen($chunk);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield substr($chunk, $offset);
|
||||||
|
$offset = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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>
|
||||||
|
*/
|
||||||
|
private function decryptChunks(string $encryptedPath, string $key, int $offset = 0): Generator
|
||||||
{
|
{
|
||||||
$handle = fopen($encryptedPath, 'rb');
|
$handle = fopen($encryptedPath, 'rb');
|
||||||
|
|
||||||
@@ -284,17 +275,50 @@ class FileEncryptionService
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Read header
|
['chunkSize' => $chunkSize, 'noncePrefix' => $noncePrefix] = $this->parseHeader((string) fread($handle, self::HEADER_LENGTH));
|
||||||
$magic = fread($handle, 8);
|
|
||||||
|
|
||||||
if ($magic !== self::MAGIC_HEADER) {
|
$storedChunkSize = $chunkSize + self::TAG_LENGTH;
|
||||||
throw new RuntimeException('Invalid chunked file format');
|
$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);
|
$firstIndex = min(intdiv($offset, max($chunkSize, 1)), $chunkCount - 1);
|
||||||
$chunkSize = unpack('N', $chunkSizeData)[1];
|
$skip = $offset - $firstIndex * $chunkSize;
|
||||||
|
fseek($handle, $this->chunkOffset($firstIndex, $chunkSize));
|
||||||
|
|
||||||
$baseNonce = fread($handle, self::NONCE_LENGTH);
|
for ($index = $firstIndex; $index < $chunkCount; $index++) {
|
||||||
|
$chunk = (string) fread($handle, $storedChunkSize);
|
||||||
|
$plaintext = $this->decryptChunk($chunk, $key, $noncePrefix, $index, $index === $chunkCount - 1);
|
||||||
|
|
||||||
|
yield $skip > 0 ? substr($plaintext, $skip) : $plaintext;
|
||||||
|
$skip = 0;
|
||||||
|
}
|
||||||
|
} 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) {
|
if (strlen($baseNonce) !== self::NONCE_LENGTH) {
|
||||||
throw new RuntimeException('Invalid chunked file: truncated header');
|
throw new RuntimeException('Invalid chunked file: truncated header');
|
||||||
@@ -320,14 +344,12 @@ class FileEncryptionService
|
|||||||
throw new RuntimeException('Invalid chunked file: missing ciphertext at chunk '.$chunkIndex);
|
throw new RuntimeException('Invalid chunked file: missing ciphertext at chunk '.$chunkIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
$nonce = $this->deriveChunkNonce($baseNonce, $chunkIndex);
|
|
||||||
|
|
||||||
$plaintext = openssl_decrypt(
|
$plaintext = openssl_decrypt(
|
||||||
$ciphertext,
|
$ciphertext,
|
||||||
self::CIPHER,
|
self::CIPHER,
|
||||||
$binaryKey,
|
$binaryKey,
|
||||||
OPENSSL_RAW_DATA,
|
OPENSSL_RAW_DATA,
|
||||||
$nonce,
|
$this->legacyChunkNonce($baseNonce, $chunkIndex),
|
||||||
$tag,
|
$tag,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -342,4 +364,47 @@ class FileEncryptionService
|
|||||||
fclose($handle);
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+411
-54
@@ -5,80 +5,336 @@ namespace App\Services;
|
|||||||
use App\Models\Setting;
|
use App\Models\Setting;
|
||||||
use App\Models\Share;
|
use App\Models\Share;
|
||||||
use App\Models\ShareFile;
|
use App\Models\ShareFile;
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
|
use Illuminate\Contracts\Session\Session;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
use Illuminate\Http\UploadedFile;
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use League\MimeTypeDetection\FinfoMimeTypeDetector;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
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(
|
public function __construct(
|
||||||
private FileEncryptionService $encryptionService,
|
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. The share's private text is registered the
|
||||||
|
* same way, as `text.txt` with `$isText`: it is capped at ShareFile::MAX_TEXT_BYTES and does not
|
||||||
|
* count as one of the share's files.
|
||||||
*
|
*
|
||||||
* @param array<int, array{file: UploadedFile, relativePath: string|null}> $files
|
* @throws ValidationException when the file breaks an admin limit
|
||||||
* @param array{password?: string|null, expires_at?: string|null, max_downloads?: int|null} $options
|
|
||||||
*/
|
*/
|
||||||
public function createShare(array $files, array $options = []): Share
|
public function registerFile(?Share $pendingShare, string $name, int $size, ?string $relativePath, bool $isText = false): ShareFile
|
||||||
{
|
{
|
||||||
$token = $this->generateUniqueToken();
|
$maxFileSize = (int) Setting::get('max_file_size', 100 * 1024 * 1024);
|
||||||
$salt = $this->encryptionService->generateSalt();
|
$maxFilesPerShare = (int) Setting::get('max_files_per_share', 50);
|
||||||
$password = $options['password'] ?? null;
|
$maxSizePerShare = (int) Setting::get('max_size_per_share', 2 * 1024 * 1024 * 1024);
|
||||||
|
|
||||||
if ($password) {
|
if ($name === '' || mb_strlen($name) > 255 || $size < 0) {
|
||||||
$encryptionKey = $this->encryptionService->deriveKey($password, $salt);
|
$this->rejectFile(__('The file could not be added.'));
|
||||||
$encryptionKeyHex = bin2hex($encryptionKey);
|
|
||||||
$storedEncryptionKey = null;
|
|
||||||
} else {
|
|
||||||
$encryptionKeyHex = $this->encryptionService->generateRandomKey();
|
|
||||||
$storedEncryptionKey = $encryptionKeyHex;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$share = Share::query()->create([
|
if ($isText && ($size < 1 || $size > ShareFile::MAX_TEXT_BYTES)) {
|
||||||
'token' => $token,
|
$this->rejectFile(__('The text is too long (maximum 100 KB).'));
|
||||||
'password' => $password ? Hash::make($password) : null,
|
}
|
||||||
'encryption_key' => $storedEncryptionKey,
|
|
||||||
'encryption_salt' => $salt,
|
if (! $isText && $size > $maxFileSize) {
|
||||||
'expires_at' => $options['expires_at'] ?? null,
|
$this->rejectFile(__('":name" is too large (:size MB). Maximum file size is :max MB.', [
|
||||||
'max_downloads' => $options['max_downloads'] ?? null,
|
'name' => $name,
|
||||||
|
'size' => round($size / (1024 * 1024), 1),
|
||||||
|
'max' => intdiv($maxFileSize, 1024 * 1024),
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $isText && $pendingShare && $pendingShare->files()->where('is_text', false)->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,
|
'total_size' => 0,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$totalSize = 0;
|
|
||||||
|
|
||||||
foreach ($files as $fileData) {
|
|
||||||
/** @var UploadedFile $file */
|
|
||||||
$file = $fileData['file'];
|
|
||||||
$relativePath = $fileData['relativePath'] ?? null;
|
|
||||||
$storedName = Str::uuid().'.enc';
|
$storedName = Str::uuid().'.enc';
|
||||||
$storedPath = 'shares/'.$share->token.'/'.$storedName;
|
|
||||||
|
|
||||||
$tempPath = $file->getRealPath();
|
|
||||||
$destPath = Storage::disk('shares')->path($share->token.'/'.$storedName);
|
|
||||||
|
|
||||||
Storage::disk('shares')->makeDirectory($share->token);
|
Storage::disk('shares')->makeDirectory($share->token);
|
||||||
|
Storage::disk('shares')->put($share->token.'/'.$storedName, $this->encryptionService->createHeader((int) config('uploads.chunk_size')));
|
||||||
|
|
||||||
$this->encryptionService->encryptFile($tempPath, $destPath, $encryptionKeyHex);
|
$file = $share->files()->create([
|
||||||
|
'original_name' => $name,
|
||||||
ShareFile::query()->create([
|
'relative_path' => $this->sanitizeRelativePath($relativePath),
|
||||||
'share_id' => $share->id,
|
'stored_path' => 'shares/'.$share->token.'/'.$storedName,
|
||||||
'original_name' => $file->getClientOriginalName(),
|
'file_size' => $size,
|
||||||
'relative_path' => $relativePath,
|
'is_text' => $isText,
|
||||||
'stored_path' => $storedPath,
|
|
||||||
'file_size' => $file->getSize(),
|
|
||||||
'mime_type' => $file->getMimeType(),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$totalSize += $file->getSize();
|
$share->increment('total_size', $size);
|
||||||
|
|
||||||
|
return $file;
|
||||||
}
|
}
|
||||||
|
|
||||||
$share->update(['total_size' => $totalSize]);
|
/**
|
||||||
|
* 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, exceeds the storage quota 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');
|
||||||
|
|
||||||
return $share->fresh();
|
if ($handle === false) {
|
||||||
|
throw (new ModelNotFoundException)->setModel(ShareFile::class, [$file->id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
['chunkSize' => $chunkSize, 'noncePrefix' => $noncePrefix] = $this->encryptionService->parseHeader(
|
||||||
|
(string) fread($handle, FileEncryptionService::HEADER_LENGTH),
|
||||||
|
);
|
||||||
|
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->getTotalUsedSpace() + $plaintextLength > $this->getMaxStorageQuota()) {
|
||||||
|
throw new InvalidArgumentException('Chunk '.$index.' exceeds the storage quota');
|
||||||
|
}
|
||||||
|
|
||||||
|
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(__('Add files or a text to share.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
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->where('is_text', false)->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, and optionally a private text, 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 = [], ?string $text = null): Share
|
||||||
|
{
|
||||||
|
$share = null;
|
||||||
|
|
||||||
|
foreach ($files as $fileData) {
|
||||||
|
$file = $fileData['file'];
|
||||||
|
$shareFile = $this->registerFile($share, $file->getClientOriginalName(), $file->getSize(), $fileData['relativePath'] ?? null);
|
||||||
|
$share = $shareFile->share;
|
||||||
|
|
||||||
|
$source = fopen($file->getRealPath(), 'rb');
|
||||||
|
$this->storeContent($shareFile, $source);
|
||||||
|
fclose($source);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($text !== null && $text !== '') {
|
||||||
|
$shareFile = $this->registerFile($share, 'text.txt', strlen($text), null, isText: true);
|
||||||
|
$share = $shareFile->share;
|
||||||
|
|
||||||
|
$source = fopen('php://memory', 'r+b');
|
||||||
|
fwrite($source, $text);
|
||||||
|
rewind($source);
|
||||||
|
$this->storeContent($shareFile, $source);
|
||||||
|
fclose($source);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($share === null) {
|
||||||
|
$this->rejectFile(__('Add files or a text to share.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->completeShare($share, $options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encrypt a registered file's content chunk by chunk from a stream and store the chunks, as the
|
||||||
|
* uploader's browser would.
|
||||||
|
*
|
||||||
|
* @param resource $source
|
||||||
|
*/
|
||||||
|
private function storeContent(ShareFile $shareFile, $source): void
|
||||||
|
{
|
||||||
|
$share = $shareFile->share;
|
||||||
|
$header = $this->readHeader($shareFile);
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A share's private text, decrypted in memory with the share's key; null when it has none.
|
||||||
|
*/
|
||||||
|
public function readText(Share $share, string $key): ?string
|
||||||
|
{
|
||||||
|
$textFile = $share->textFile()->first();
|
||||||
|
|
||||||
|
if ($textFile === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode('', iterator_to_array(
|
||||||
|
$this->encryptionService->decryptedChunks($this->storedFilePath($textFile), $key),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The key this session decrypts a share with: the one unlocked with the password and kept in
|
||||||
|
* the session, or the stored one for a share without a password.
|
||||||
|
*
|
||||||
|
* @throws HttpException 403 while a password share is still locked for this session
|
||||||
|
*/
|
||||||
|
public function sessionDecryptionKey(Share $share, Session $session): string
|
||||||
|
{
|
||||||
|
if ($share->isPasswordProtected()) {
|
||||||
|
$key = $session->get('share_key_'.$share->token);
|
||||||
|
|
||||||
|
abort_if(! $key, 403, 'Password required');
|
||||||
|
|
||||||
|
return $key;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->getDecryptionKey($share);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -108,7 +364,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
|
public function getDecryptionKey(Share $share, ?string $password = null): string
|
||||||
{
|
{
|
||||||
@@ -117,6 +374,10 @@ class ShareService
|
|||||||
throw new RuntimeException('Password required for this share');
|
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));
|
return bin2hex($this->encryptionService->deriveKey($password, $share->encryption_salt));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,23 +397,73 @@ 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 and each download started in it keeps it
|
||||||
|
* open, so downloading a large share file by file never outlasts it; 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()) {
|
if (! is_int($countedAt)) {
|
||||||
$this->deleteShare($share);
|
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) {
|
||||||
|
$session->put($this->downloadSessionKey($share), now()->getTimestamp());
|
||||||
|
|
||||||
|
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 last started a download of a share.
|
||||||
|
*/
|
||||||
|
private function downloadSessionKey(Share $share): string
|
||||||
|
{
|
||||||
|
return 'share_download_'.$share->token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get total used space in bytes; files still being uploaded count with the bytes received so far.
|
||||||
*/
|
*/
|
||||||
public function getTotalUsedSpace(): int
|
public function getTotalUsedSpace(): int
|
||||||
{
|
{
|
||||||
return (int) Share::query()->sum('total_size');
|
$chunkSize = (int) config('uploads.chunk_size');
|
||||||
|
|
||||||
|
$received = ShareFile::query()
|
||||||
|
->whereHas('share', fn ($query) => $query->whereNull('completed_at'))
|
||||||
|
->sum(DB::raw("CASE WHEN uploaded_chunks * {$chunkSize} < file_size THEN uploaded_chunks * {$chunkSize} ELSE file_size END"));
|
||||||
|
|
||||||
|
return (int) Share::query()->whereNotNull('completed_at')->sum('total_size') + (int) $received;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -160,9 +471,7 @@ class ShareService
|
|||||||
*/
|
*/
|
||||||
public function isStorageFull(): bool
|
public function isStorageFull(): bool
|
||||||
{
|
{
|
||||||
$maxQuota = (int) Setting::get('max_storage_quota', 20 * 1024 * 1024 * 1024);
|
return $this->getTotalUsedSpace() >= $this->getMaxStorageQuota();
|
||||||
|
|
||||||
return $this->getTotalUsedSpace() >= $maxQuota;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -172,4 +481,52 @@ class ShareService
|
|||||||
{
|
{
|
||||||
return (int) Setting::get('max_storage_quota', 20 * 1024 * 1024 * 1024);
|
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]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -17,7 +17,7 @@
|
|||||||
"testing-best-practices",
|
"testing-best-practices",
|
||||||
"octane-development",
|
"octane-development",
|
||||||
"livewire-development",
|
"livewire-development",
|
||||||
"tailwindcss-development",
|
"livewire-material-development",
|
||||||
"livewire-material-development"
|
"material-3-design"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-4
@@ -5,7 +5,6 @@ use App\Http\Middleware\EnsureSetupComplete;
|
|||||||
use App\Http\Middleware\SecurityHeaders;
|
use App\Http\Middleware\SecurityHeaders;
|
||||||
use App\Http\Middleware\SystemPasswordGate;
|
use App\Http\Middleware\SystemPasswordGate;
|
||||||
use Illuminate\Foundation\Application;
|
use Illuminate\Foundation\Application;
|
||||||
use Illuminate\Foundation\Configuration\Exceptions;
|
|
||||||
use Illuminate\Foundation\Configuration\Middleware;
|
use Illuminate\Foundation\Configuration\Middleware;
|
||||||
|
|
||||||
return Application::configure(basePath: dirname(__DIR__))
|
return Application::configure(basePath: dirname(__DIR__))
|
||||||
@@ -17,6 +16,9 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||||||
->withMiddleware(function (Middleware $middleware): void {
|
->withMiddleware(function (Middleware $middleware): void {
|
||||||
$middleware->trustProxies(at: '*');
|
$middleware->trustProxies(at: '*');
|
||||||
|
|
||||||
|
// Ends every other session of a user whose password changed.
|
||||||
|
$middleware->authenticateSessions();
|
||||||
|
|
||||||
$middleware->web(append: [
|
$middleware->web(append: [
|
||||||
EnsureSetupComplete::class,
|
EnsureSetupComplete::class,
|
||||||
SecurityHeaders::class,
|
SecurityHeaders::class,
|
||||||
@@ -27,6 +29,5 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||||||
'admin' => EnsureAdmin::class,
|
'admin' => EnsureAdmin::class,
|
||||||
]);
|
]);
|
||||||
})
|
})
|
||||||
->withExceptions(function (Exceptions $exceptions): void {
|
->withExceptions()
|
||||||
//
|
->create();
|
||||||
})->create();
|
|
||||||
|
|||||||
+3
-8
@@ -16,14 +16,13 @@
|
|||||||
"laravel/octane": "^2.13",
|
"laravel/octane": "^2.13",
|
||||||
"laravel/tinker": "^3.0",
|
"laravel/tinker": "^3.0",
|
||||||
"livewire/livewire": "^4.0",
|
"livewire/livewire": "^4.0",
|
||||||
"nonameweb/livewire-material": "^1.0"
|
"maennchen/zipstream-php": "^3.2",
|
||||||
|
"nonameweb/livewire-material": "^2.0"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"fakerphp/faker": "^1.23",
|
"fakerphp/faker": "^1.23",
|
||||||
"laravel/boost": "^2.0",
|
"laravel/boost": "^2.0",
|
||||||
"laravel/pail": "^1.2.2",
|
|
||||||
"laravel/pint": "^1.24",
|
"laravel/pint": "^1.24",
|
||||||
"laravel/sail": "^1.41",
|
|
||||||
"mockery/mockery": "^1.6",
|
"mockery/mockery": "^1.6",
|
||||||
"nunomaduro/collision": "^8.6",
|
"nunomaduro/collision": "^8.6",
|
||||||
"pestphp/pest": "^5.1",
|
"pestphp/pest": "^5.1",
|
||||||
@@ -51,10 +50,6 @@
|
|||||||
"npm install",
|
"npm install",
|
||||||
"npm run build"
|
"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": [
|
"lint": [
|
||||||
"pint --parallel"
|
"pint --parallel"
|
||||||
],
|
],
|
||||||
@@ -88,7 +83,7 @@
|
|||||||
"screenshots": [
|
"screenshots": [
|
||||||
"Composer\\Config::disableProcessTimeout",
|
"Composer\\Config::disableProcessTimeout",
|
||||||
"npm run build",
|
"npm run build",
|
||||||
"@php -d upload_max_filesize=4G -d post_max_size=4G vendor/bin/pest tests/Screenshots"
|
"@php vendor/bin/pest tests/Screenshots"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"extra": {
|
"extra": {
|
||||||
|
|||||||
Generated
+1292
-1057
File diff suppressed because it is too large
Load Diff
+15
-111
@@ -1,126 +1,30 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
return [
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Only what differs from the framework's config/app.php; Laravel merges
|
||||||
|
| every other key from its own defaults.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
/*
|
return [
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| 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.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'name' => env('APP_NAME', 'SealShare'),
|
'name' => env('APP_NAME', 'SealShare'),
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
| Application Environment
|
| SealShare Version
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
|
||||||
| This value determines the "environment" your application is currently
|
| The release this code is, shown on the admin dashboard. Bump it together
|
||||||
| running in. This may determine how you prefer to configure various
|
| with the release's heading in CHANGELOG.md: tests/Feature/AppVersionTest
|
||||||
| services the application utilizes. Set this in your ".env" file.
|
| fails while the two differ.
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'env' => env('APP_ENV', 'production'),
|
'version' => '2.4.3',
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| 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'),
|
|
||||||
],
|
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
-117
@@ -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
@@ -1,130 +1,18 @@
|
|||||||
<?php
|
<?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 [
|
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,
|
'serializable_classes' => false,
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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
@@ -1,52 +1,19 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Filesystem Disks
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The encrypted share files. Laravel merges this disk into its own default
|
||||||
|
| disks (local, public, s3).
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
return [
|
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' => [
|
'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' => [
|
'shares' => [
|
||||||
'driver' => 'local',
|
'driver' => 'local',
|
||||||
'root' => storage_path('app/shares'),
|
'root' => storage_path('app/shares'),
|
||||||
@@ -54,34 +21,6 @@ return [
|
|||||||
'report' => false,
|
'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'),
|
|
||||||
],
|
],
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -144,9 +144,7 @@ return [
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
'features' => [
|
'features' => [
|
||||||
// Features::registration(), // Disabled - admin created via setup wizard
|
|
||||||
Features::resetPasswords(),
|
Features::resetPasswords(),
|
||||||
Features::emailVerification(),
|
|
||||||
Features::twoFactorAuthentication([
|
Features::twoFactorAuthentication([
|
||||||
'confirm' => true,
|
'confirm' => true,
|
||||||
'confirmPassword' => true,
|
'confirmPassword' => true,
|
||||||
|
|||||||
+19
-254
@@ -1,275 +1,39 @@
|
|||||||
<?php
|
<?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 [
|
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'], // No size cap: PHP's upload_max_filesize is the hard limit, the admin limit is 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' => (int) env('LIVEWIRE_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
|
| Pagination Theme
|
||||||
|---------------------------------------------------------------------------
|
|---------------------------------------------------------------------------
|
||||||
|
|
|
|
||||||
| When enabling Livewire's pagination feature by using the `WithPagination`
|
| livewire-material takes this over itself while it still reads as
|
||||||
| trait, Livewire will use Tailwind templates to render pagination views
|
| Livewire's own default ("tailwind", or the key missing), so this stays
|
||||||
| on the page. If you want Bootstrap CSS, you can specify: "bootstrap"
|
| explicit: SealShare states the choice itself rather than relying on
|
||||||
|
| the package to silently switch it.
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'pagination_theme' => 'tailwind',
|
'pagination_theme' => 'material',
|
||||||
|
|
||||||
/*
|
|
||||||
|---------------------------------------------------------------------------
|
|
||||||
| 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,
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|---------------------------------------------------------------------------
|
|---------------------------------------------------------------------------
|
||||||
| Payload Guards
|
| Payload Guards
|
||||||
|---------------------------------------------------------------------------
|
|---------------------------------------------------------------------------
|
||||||
|
|
|
|
||||||
| These settings protect against malicious or oversized payloads that could
|
| Livewire's defaults, with at most 20 components per batch request
|
||||||
| cause denial of service. The default values should feel reasonable for
|
| instead of 200.
|
||||||
| most web applications. Each can be set to null to disable the limit.
|
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -279,4 +43,5 @@ return [
|
|||||||
'max_calls' => 50, // Maximum method calls per request
|
'max_calls' => 50, // Maximum method calls per request
|
||||||
'max_components' => 20, // Maximum components per batch request
|
'max_components' => 20, // Maximum components per batch request
|
||||||
],
|
],
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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'),
|
|
||||||
],
|
|
||||||
|
|
||||||
],
|
|
||||||
|
|
||||||
];
|
|
||||||
+11
-127
@@ -1,140 +1,24 @@
|
|||||||
<?php
|
<?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 [
|
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.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'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)),
|
|
||||||
],
|
|
||||||
|
|
||||||
'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'),
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Markdown Mail Settings
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Markdown mail wears Livewire Material's theme, coloured from the light
|
|
||||||
| scheme in resources/css/material-scheme.json.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'markdown' => [
|
'markdown' => [
|
||||||
'theme' => env('MAIL_MARKDOWN_THEME', 'livewire-material::mail.theme'),
|
'theme' => env('MAIL_MARKDOWN_THEME', 'livewire-material::mail.theme'),
|
||||||
|
|
||||||
'paths' => [
|
'paths' => [
|
||||||
resource_path('views/vendor/mail'),
|
resource_path('views/vendor/mail'),
|
||||||
],
|
],
|
||||||
|
|
||||||
'extensions' => [
|
|
||||||
// \League\CommonMark\Extension\Strikethrough\StrikethroughExtension::class,
|
|
||||||
],
|
|
||||||
],
|
],
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
+11
-206
@@ -1,222 +1,27 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Laravel\Octane\Contracts\OperationTerminated;
|
/*
|
||||||
use Laravel\Octane\Events\RequestHandled;
|
|--------------------------------------------------------------------------
|
||||||
use Laravel\Octane\Events\RequestReceived;
|
| Octane
|
||||||
use Laravel\Octane\Events\RequestTerminated;
|
|--------------------------------------------------------------------------
|
||||||
use Laravel\Octane\Events\TaskReceived;
|
|
|
||||||
use Laravel\Octane\Events\TaskTerminated;
|
| Only what differs from Octane's own config; every other key (listeners,
|
||||||
use Laravel\Octane\Events\TickReceived;
|
| warm and flush lists, watch paths, ...) comes from its defaults.
|
||||||
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;
|
|
||||||
|
|
||||||
return [
|
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'),
|
'server' => env('OCTANE_SERVER', 'frankenphp'),
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------
|
| Absolute links use HTTPS whenever APP_URL does.
|
||||||
| 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.
|
|
||||||
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'https' => env('OCTANE_HTTPS', str_starts_with(env('APP_URL', ''), 'https://')),
|
'https' => env('OCTANE_HTTPS', str_starts_with(env('APP_URL', ''), 'https://')),
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------
|
| Requests may run for up to 300 seconds instead of Octane's default 30.
|
||||||
| 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.
|
|
||||||
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'max_execution_time' => env('OCTANE_MAX_EXECUTION_TIME', 300),
|
'max_execution_time' => env('OCTANE_MAX_EXECUTION_TIME', 300),
|
||||||
|
|||||||
@@ -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',
|
|
||||||
],
|
|
||||||
|
|
||||||
];
|
|
||||||
@@ -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'),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
|
|
||||||
];
|
|
||||||
+16
-204
@@ -2,216 +2,28 @@
|
|||||||
|
|
||||||
use Illuminate\Support\Str;
|
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.
|
||||||
|
|
|
||||||
|
| Sessions are encrypted unless SESSION_ENCRYPT=false: they hold the keys
|
||||||
|
| of the password shares a recipient unlocked, which must never sit
|
||||||
|
| readable in the sessions table. Every other key comes from the
|
||||||
|
| framework's defaults.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|
||||||
/*
|
'encrypt' => env('SESSION_ENCRYPT', true),
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| 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(
|
'cookie' => env(
|
||||||
'SESSION_COOKIE',
|
'SESSION_COOKIE',
|
||||||
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
|
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),
|
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|
||||||
|
];
|
||||||
@@ -27,9 +27,22 @@ class ShareFactory extends Factory
|
|||||||
'max_downloads' => null,
|
'max_downloads' => null,
|
||||||
'download_count' => 0,
|
'download_count' => 0,
|
||||||
'total_size' => 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
|
public function withPassword(string $password = 'secret'): static
|
||||||
{
|
{
|
||||||
return $this->state(fn (array $attributes) => [
|
return $this->state(fn (array $attributes) => [
|
||||||
|
|||||||
@@ -25,6 +25,34 @@ class ShareFileFactory extends Factory
|
|||||||
'stored_path' => 'shares/'.fake()->uuid().'.enc',
|
'stored_path' => 'shares/'.fake()->uuid().'.enc',
|
||||||
'file_size' => fake()->numberBetween(1024, 10485760),
|
'file_size' => fake()->numberBetween(1024, 10485760),
|
||||||
'mime_type' => 'text/plain',
|
'mime_type' => 'text/plain',
|
||||||
|
'is_text' => false,
|
||||||
|
'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,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A share's private text.
|
||||||
|
*/
|
||||||
|
public function text(): static
|
||||||
|
{
|
||||||
|
return $this->state(fn (array $attributes) => [
|
||||||
|
'original_name' => 'text.txt',
|
||||||
|
'relative_path' => null,
|
||||||
|
'file_size' => fake()->numberBetween(1, 1024),
|
||||||
|
'is_text' => true,
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.
|
* Indicate that the user is an admin.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*
|
||||||
|
* Shares and files that exist already were complete when they were created.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('shares', function (Blueprint $table) {
|
||||||
|
$table->text('wrapped_key')->nullable()->after('encryption_salt');
|
||||||
|
$table->timestamp('completed_at')->nullable()->after('total_size');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('share_files', function (Blueprint $table) {
|
||||||
|
$table->unsignedInteger('uploaded_chunks')->default(0)->after('mime_type');
|
||||||
|
$table->timestamp('completed_at')->nullable()->after('uploaded_chunks');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('shares')->update(['completed_at' => DB::raw('created_at')]);
|
||||||
|
DB::table('share_files')->update(['completed_at' => DB::raw('created_at')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('shares', function (Blueprint $table) {
|
||||||
|
$table->dropColumn(['wrapped_key', 'completed_at']);
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('share_files', function (Blueprint $table) {
|
||||||
|
$table->dropColumn(['uploaded_chunks', 'completed_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*
|
||||||
|
* When a recipient's download was last counted: a share at its download limit is deleted a while
|
||||||
|
* after that, so downloads still running can finish.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('shares', function (Blueprint $table) {
|
||||||
|
$table->timestamp('last_downloaded_at')->nullable()->after('download_count');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('shares', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('last_downloaded_at');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*
|
||||||
|
* A share's private text is stored as one of its files, encrypted like the others; this flag
|
||||||
|
* keeps it out of the file list, the ZIP and the file counts.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('share_files', function (Blueprint $table) {
|
||||||
|
$table->boolean('is_text')->default(false)->after('mime_type');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('share_files', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('is_text');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -4,7 +4,6 @@ namespace Database\Seeders;
|
|||||||
|
|
||||||
use App\Models\Setting;
|
use App\Models\Setting;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
|
|
||||||
use Illuminate\Database\Seeder;
|
use Illuminate\Database\Seeder;
|
||||||
|
|
||||||
class DatabaseSeeder extends Seeder
|
class DatabaseSeeder extends Seeder
|
||||||
@@ -14,8 +13,6 @@ class DatabaseSeeder extends Seeder
|
|||||||
*/
|
*/
|
||||||
public function run(): void
|
public function run(): void
|
||||||
{
|
{
|
||||||
// User::factory(10)->create();
|
|
||||||
|
|
||||||
User::factory()->create([
|
User::factory()->create([
|
||||||
'name' => 'Test User',
|
'name' => 'Test User',
|
||||||
'email' => 'test@example.com',
|
'email' => 'test@example.com',
|
||||||
|
|||||||
+68
-27
@@ -1,37 +1,78 @@
|
|||||||
|
# ============================================
|
||||||
|
# SealShare - Development (extends docker-compose.yml)
|
||||||
|
# ============================================
|
||||||
|
#
|
||||||
|
# The app and the scheduler extend the production services and change only what development needs.
|
||||||
|
# Select this file in .env, then use plain `docker compose` commands:
|
||||||
|
# COMPOSE_FILE=docker-compose.dev.yml
|
||||||
|
#
|
||||||
|
# The checkout is mounted at /app, so changes apply without a rebuild: Octane reloads on PHP changes,
|
||||||
|
# the Vite dev server hot-reloads CSS and JavaScript and reloads the page on Blade changes. Every other
|
||||||
|
# value comes from .env through docker-compose.yml.
|
||||||
|
#
|
||||||
|
# No ports are published: OrbStack serves https://app.sealshare.orb.local and
|
||||||
|
# https://vite.sealshare.orb.local. Elsewhere, add docker-compose.ports.yml to COMPOSE_FILE.
|
||||||
|
#
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
# Only what differs between the host and the container: the host reads .env too.
|
||||||
|
x-container-environment: &container-environment
|
||||||
|
# Compiled views stay in the container. The host shares storage/ through the mount, and
|
||||||
|
# compiled Livewire components hold absolute paths (/app/… here, the checkout's path there).
|
||||||
|
VIEW_COMPILED_PATH: /tmp/views
|
||||||
|
# The database file the host uses, not the production volume's path
|
||||||
|
DB_DATABASE: /app/database/database.sqlite
|
||||||
|
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
|
extends:
|
||||||
|
file: docker-compose.yml
|
||||||
|
service: app
|
||||||
|
# Its own name, so a development build never tags the published image
|
||||||
|
image: sealshare-dev
|
||||||
|
build:
|
||||||
|
target: dev
|
||||||
|
ports: !reset []
|
||||||
|
volumes: !override
|
||||||
|
- .:/app
|
||||||
|
environment: *container-environment
|
||||||
|
labels:
|
||||||
|
# OrbStack's port for https://app.sealshare.orb.local, instead of detecting it (it can keep a stale one)
|
||||||
|
dev.orbstack.http-port: "80"
|
||||||
|
healthcheck:
|
||||||
|
# The first start installs Composer packages
|
||||||
|
start_period: 5m
|
||||||
|
start_interval: 2s
|
||||||
|
|
||||||
|
scheduler:
|
||||||
|
extends:
|
||||||
|
file: docker-compose.yml
|
||||||
|
service: scheduler
|
||||||
|
image: sealshare-dev
|
||||||
|
build:
|
||||||
|
target: dev
|
||||||
|
volumes: !override
|
||||||
|
- .:/app
|
||||||
|
environment: *container-environment
|
||||||
|
|
||||||
|
vite:
|
||||||
|
image: sealshare-dev
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: docker/dev.Dockerfile
|
dockerfile: Dockerfile
|
||||||
ports:
|
target: dev
|
||||||
- "8000:8000"
|
entrypoint: ["sh", "-c", "npm install --no-audit --no-fund && exec node_modules/.bin/vite"]
|
||||||
- "5173:5173"
|
|
||||||
volumes:
|
volumes:
|
||||||
- .:/app
|
- .:/app
|
||||||
# Its own node_modules: npm installs the build tools' native binaries for Linux here and for
|
# Its own node_modules: npm installs the build tools' native binaries for Linux here and for
|
||||||
# the host's platform there, and a shared folder only ever holds one of them.
|
# the host's platform there, and a shared folder only ever holds one of them.
|
||||||
- /app/node_modules
|
- /app/node_modules
|
||||||
environment:
|
labels:
|
||||||
APP_KEY: ${APP_KEY:-}
|
dev.orbstack.http-port: "${VITE_PORT:-5173}"
|
||||||
APP_URL: http://localhost:8000
|
# The image's healthcheck asks the web server, which only the app service runs
|
||||||
APP_ENV: local
|
|
||||||
# Compiled views stay in the container. The host shares storage/ through the mount, and
|
|
||||||
# compiled Livewire components hold absolute paths (/app/… here, the checkout's path there).
|
|
||||||
VIEW_COMPILED_PATH: /tmp/views
|
|
||||||
APP_DEBUG: "true"
|
|
||||||
SERVER_NAME: ":8000"
|
|
||||||
DB_CONNECTION: sqlite
|
|
||||||
LOG_CHANNEL: stack
|
|
||||||
LOG_LEVEL: debug
|
|
||||||
OCTANE_MAX_EXECUTION_TIME: "300"
|
|
||||||
PHP_UPLOAD_MAX_FILESIZE: "4G"
|
|
||||||
PHP_POST_MAX_SIZE: "4G"
|
|
||||||
PHP_MAX_EXECUTION_TIME: "300"
|
|
||||||
PHP_MAX_INPUT_TIME: "300"
|
|
||||||
PHP_MEMORY_LIMIT: "512M"
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "--silent", "--fail", "http://localhost:8000/up"]
|
disable: true
|
||||||
interval: 30s
|
depends_on:
|
||||||
timeout: 5s
|
# The stylesheet imports Livewire Material from vendor/, which the app's first start installs
|
||||||
start_period: 30s
|
app:
|
||||||
retries: 3
|
condition: service_healthy
|
||||||
|
|||||||
+32
-18
@@ -4,12 +4,13 @@
|
|||||||
#
|
#
|
||||||
# Quick start:
|
# Quick start:
|
||||||
# 1. Copy this file: cp docker-compose.example.yml docker-compose.yml
|
# 1. Copy this file: cp docker-compose.example.yml docker-compose.yml
|
||||||
# 2. Edit the settings below (APP_URL and SERVER_NAME are required)
|
# 2. Edit the settings below (APP_URL and APP_KEY are required; uploads need HTTPS, see below)
|
||||||
# 3. Start: docker compose up -d
|
# 3. Start: docker compose up -d
|
||||||
# 4. Open your browser to your configured domain
|
# 4. Open your browser to your configured domain
|
||||||
#
|
#
|
||||||
# Note: APP_KEY is auto-generated on first start if not set.
|
# APP_KEY is required: the container does not start without it. Create one with
|
||||||
# Copy it from the logs into your docker-compose.yml to persist across restarts.
|
# docker run --rm --entrypoint php gitea.nonameweb.ch/nonameweb/sealshare:latest artisan key:generate --show
|
||||||
|
# and keep it: it decrypts the shares, so a new key makes the existing ones unreadable.
|
||||||
#
|
#
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
@@ -22,18 +23,25 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "80:80" # HTTP
|
- "80:80" # HTTP
|
||||||
- "443:443" # HTTPS (auto TLS via Let's Encrypt when SERVER_NAME is a real domain)
|
- "443:443" # HTTPS (a Let's Encrypt certificate with AUTO_HTTPS)
|
||||||
- "443:443/udp" # HTTP/3 (QUIC)
|
- "443:443/udp" # HTTP/3 (QUIC)
|
||||||
volumes:
|
volumes:
|
||||||
- sealshare_storage:/app/storage/app # Uploaded & encrypted files
|
- sealshare_storage:/app/storage/app # Uploaded & encrypted files
|
||||||
- sealshare_database:/app/database # SQLite database
|
- sealshare_database:/app/database/sqlite # SQLite database
|
||||||
- caddy_data:/data # TLS certificates
|
- caddy_data:/data # TLS certificates
|
||||||
- caddy_config:/config # Caddy configuration
|
- caddy_config:/config # Caddy configuration
|
||||||
environment:
|
environment:
|
||||||
# --- REQUIRED ---
|
# --- REQUIRED ---
|
||||||
APP_URL: # Your full URL, e.g. https://share.example.com
|
APP_URL: # Your full URL, e.g. https://share.example.com
|
||||||
SERVER_NAME: # Your domain for auto-TLS, e.g. share.example.com (use "localhost" for local testing)
|
APP_KEY: # Required. Create one with php artisan key:generate --show (see above)
|
||||||
# APP_KEY: # Auto-generated if not set. Copy from logs to persist across restarts.
|
DB_DATABASE: /app/database/sqlite/database.sqlite # The SQLite file in sealshare_database
|
||||||
|
|
||||||
|
# --- HTTPS ---
|
||||||
|
# Files are encrypted in the uploader's browser, which browsers only allow over HTTPS (or on
|
||||||
|
# localhost). Either let this container fetch a Let's Encrypt certificate (ports 80 and 443
|
||||||
|
# reachable from the internet), or put a reverse proxy that terminates TLS in front of port 80.
|
||||||
|
# AUTO_HTTPS: "true"
|
||||||
|
# SERVER_NAME: share.example.com # The domain to fetch the certificate for (only with AUTO_HTTPS)
|
||||||
|
|
||||||
# --- Optional: Application ---
|
# --- Optional: Application ---
|
||||||
# APP_ENV: production
|
# APP_ENV: production
|
||||||
@@ -45,7 +53,7 @@ services:
|
|||||||
# DB_CONNECTION: sqlite # Options: sqlite, mysql, pgsql
|
# DB_CONNECTION: sqlite # Options: sqlite, mysql, pgsql
|
||||||
# DB_HOST: # Required for mysql/pgsql
|
# DB_HOST: # Required for mysql/pgsql
|
||||||
# DB_PORT: # Required for mysql/pgsql
|
# DB_PORT: # Required for mysql/pgsql
|
||||||
# DB_DATABASE: # Required for mysql/pgsql
|
# DB_DATABASE: # For mysql/pgsql the database's name, in place of the SQLite file above
|
||||||
# DB_USERNAME: # Required for mysql/pgsql
|
# DB_USERNAME: # Required for mysql/pgsql
|
||||||
# DB_PASSWORD: # Required for mysql/pgsql
|
# DB_PASSWORD: # Required for mysql/pgsql
|
||||||
|
|
||||||
@@ -53,15 +61,17 @@ services:
|
|||||||
# OCTANE_HTTPS: "false" # Set to "true" when using HTTPS
|
# OCTANE_HTTPS: "false" # Set to "true" when using HTTPS
|
||||||
# OCTANE_MAX_EXECUTION_TIME: 300 # Max request execution time (seconds)
|
# OCTANE_MAX_EXECUTION_TIME: 300 # Max request execution time (seconds)
|
||||||
|
|
||||||
# --- Optional: PHP upload limits ---
|
# --- Optional: Uploads ---
|
||||||
# PHP_UPLOAD_MAX_FILESIZE: "4G" # Max single file size
|
# UPLOAD_CHUNK_SIZE_MB: "16" # Each encrypted chunk the browser sends; a reverse proxy must accept a little more
|
||||||
# PHP_POST_MAX_SIZE: "4G" # Max total request size
|
|
||||||
# PHP_MAX_EXECUTION_TIME: "300" # Upload timeout in seconds
|
# --- Optional: PHP limits ---
|
||||||
# PHP_MAX_INPUT_TIME: "300" # Input processing timeout
|
# PHP_UPLOAD_MAX_FILESIZE: "64M" # Only for the admin's logo upload: shares upload in chunks
|
||||||
# PHP_MEMORY_LIMIT: "512M" # PHP memory limit
|
# PHP_POST_MAX_SIZE: "64M"
|
||||||
# LIVEWIRE_MAX_UPLOAD_TIME: "30" # Minutes a single upload may take (raise for large files on slow links)
|
# PHP_MAX_EXECUTION_TIME: "300"
|
||||||
|
# PHP_MAX_INPUT_TIME: "300"
|
||||||
|
# PHP_MEMORY_LIMIT: "512M"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "--silent", "--fail", "http://localhost/up"]
|
test: ["CMD", "/app/docker/healthcheck.sh"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
start_period: 10s
|
start_period: 10s
|
||||||
@@ -74,12 +84,16 @@ services:
|
|||||||
image: gitea.nonameweb.ch/nonameweb/sealshare:latest
|
image: gitea.nonameweb.ch/nonameweb/sealshare:latest
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
entrypoint: ["php", "artisan", "schedule:work"]
|
entrypoint: ["php", "artisan", "schedule:work"]
|
||||||
|
# The image's healthcheck asks the web server, which only the app service runs
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
volumes:
|
volumes:
|
||||||
- sealshare_storage:/app/storage/app
|
- sealshare_storage:/app/storage/app
|
||||||
- sealshare_database:/app/database
|
- sealshare_database:/app/database/sqlite
|
||||||
environment:
|
environment:
|
||||||
# APP_KEY: # Same key as the app service above (auto-generated if not set)
|
APP_KEY: # Same key as the app service above
|
||||||
APP_URL: # Same URL as the app service above
|
APP_URL: # Same URL as the app service above
|
||||||
|
DB_DATABASE: /app/database/sqlite/database.sqlite # Same as the app service above
|
||||||
depends_on:
|
depends_on:
|
||||||
app:
|
app:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# ============================================
|
||||||
|
# SealShare - Development ports (layered on docker-compose.dev.yml)
|
||||||
|
# ============================================
|
||||||
|
#
|
||||||
|
# Publishes the app and the Vite dev server on this machine, for Docker without OrbStack's domains:
|
||||||
|
# COMPOSE_FILE=docker-compose.dev.yml:docker-compose.ports.yml
|
||||||
|
# APP_URL=http://localhost:8000
|
||||||
|
#
|
||||||
|
# Bound to 127.0.0.1: a debug build does not belong on the network.
|
||||||
|
#
|
||||||
|
# ============================================
|
||||||
|
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${APP_PORT:-8000}:80"
|
||||||
|
|
||||||
|
vite:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${VITE_PORT:-5173}:${VITE_PORT:-5173}"
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user