Search by

fluxfiles / laravel

thai-pc

Laravel adapter for FluxFiles file manager

v1.1.0 2026-11-15 06:29 UTC

README

Laravel adapter for FluxFiles — a standalone, embeddable file manager with multi-storage support (Local, AWS S3, Cloudflare R2, SFTP).

Requirements

  • PHP >= 8.1 (matches fluxfiles/fluxfiles; Laravel 11/12 themselves need 8.2, Laravel 13 needs 8.3)
  • Laravel 10, 11, 12, or 13

Installation

composer require fluxfiles/laravel

Publish the config file:

php artisan vendor:publish --tag=fluxfiles-config

Add to your .env:

FLUXFILES_SECRET=your-random-32-char-secret

For the default local disk, expose Laravel public storage once:

php artisan storage:link

The default local disk writes to storage/app/public/fluxfiles/uploads (override with FLUXFILES_LOCAL_ROOT) and returns URLs under /storage/fluxfiles/uploads.

Cloud storage (optional)

The s3 and r2 disks read these from .env (see config/fluxfiles.php):

# AWS S3 — or any S3-compatible (set AWS_ENDPOINT for MinIO / DO Spaces)
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=ap-southeast-1
AWS_BUCKET=
AWS_ENDPOINT=                 # empty = native AWS S3
AWS_VISIBILITY=private        # 'public' = direct object URLs
AWS_PUBLIC_URL=               # CDN / custom domain for a public disk

# Cloudflare R2
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
R2_ACCOUNT_ID=
R2_BUCKET=
R2_VISIBILITY=private
R2_PUBLIC_URL=                # r2.dev or custom domain for a public bucket

Modes

Mode Description
proxy (default) FluxFiles API runs through Laravel routes — no separate server needed
standalone FluxFiles runs on its own server; Laravel only generates tokens and embeds the iframe

Proxy mode: exclude the route prefix from CSRF or uploads/deletes return 419 — see CSRF exclusion.

Proxy mode exposes every core route, including the paid-module routes and the public Share/Intake recipient pages, except three that only the standalone core serves: resumable tus uploads (/tus — the UI falls back to a plain single-request upload, so PHP's upload_max_filesize applies to local disks), the DB-backend metadata export/import, and the SSO login bridge.

Set mode in .env:

FLUXFILES_MODE=proxy
# or
FLUXFILES_MODE=standalone
FLUXFILES_ENDPOINT=https://your-fluxfiles-server.com

SFTP disk

Managing a remote VPS / shared host over SFTP is supported in both modes.

  • standalone mode: run the FluxFiles server (or the Docker image), give it the SFTP_* env vars (see the core README → SFTP disk), and point Laravel at it with FLUXFILES_ENDPOINT. Then mint tokens with the sftp disk:

    $token = $fluxFiles->token(auth()->user(), [
        'prefix'      => 'user_' . auth()->id() . '/',
        'disks'       => ['sftp'],   // an SFTP disk configured on the FluxFiles server
        'allow_chmod' => true,       // cPanel-style permissions (default on for SFTP)
    ]);

    To give users an interactive terminal, run your own ttyd/gotty/wetty and pass its URL as 'terminal_pty_url' => 'https://…'; the UI embeds it.

    Standalone mode also gives large SFTP uploads resumable tus chunking.

  • proxy mode: chmod (GET/POST /chmod) is proxied through Laravel routes — add an sftp entry to config('fluxfiles.disks') (same shape as the core standalone config, e.g. driver/host/port/username/private_key or password) or hand the user a BYOB sftp disk, and mint tokens with disks => ['sftp']. A host on your own private network must be listed in FLUXFILES_SSRF_ALLOW_HOSTS (comma-separated). On a BYOB disk, download and preview links carry the disk config encrypted and last at most 30 minutes. Burn-in watermark works in both modes, and so does the preview overlay watermark (watermark_enabled + watermark_type/_text/_logo_path/…): /img is the shared core endpoint, so a watermarked token gets the overlaid image.

Usage

Upgrading from an earlier 0.2.x? Implicit tokens no longer fall back to the defaults in config/fluxfiles.php (read/write/delete, empty prefix = every user sees everything). If you relied on that, register a per-user claims resolver — returning [] keeps the old behaviour deliberately. In proxy mode, a request without a Bearer token is now refused for POST/PUT/DELETE, and for reads unless a resolver is configured; the embedded UI always sends its Bearer, so only custom cookie-only fetch() calls are affected. See Session-only requests.

Per-user token policy (claims resolver)

Tokens minted by the resolver-based helpers — tokenForUser(), tokenForResolvedUser(), <x-fluxfiles>, @fluxfilesToken, the GET {route_prefix}/token refresh route and the session fallback below — take their scope from a resolver you register once. Without a resolver they all refuse (tokenForUser() throws, <x-fluxfiles> renders a "not available" message, @fluxfilesToken prints nothing, each logging the reason); they never fall back to the config defaults:

// app/FluxFiles/TenantClaims.php
use FluxFiles\Laravel\ClaimsResolver;
use Illuminate\Contracts\Auth\Authenticatable;

class TenantClaims implements ClaimsResolver
{
    public function resolve(Authenticatable $user): array
    {
        return [
            'prefix' => 'users/' . $user->getAuthIdentifier(),
            'role'   => $user->is_admin ? 'admin' : 'editor',
        ];
    }
}
// config/fluxfiles.php — a class name is resolved through the container
'claims_resolver' => \App\FluxFiles\TenantClaims::class,

// …or at runtime, e.g. in AppServiceProvider::boot() (survives config:cache)
FluxFiles::resolveClaimsUsing(fn ($user) => ['prefix' => 'users/' . $user->id]);

The resolver returns the same array token() accepts. Explicit overrides (a component's :overrides, tokenForUser([...])) are merged on top, and the two claims maps are merged key by key. Throw from the resolver to refuse a user; a non-array result is an error, never "no restrictions". token($user, $overrides) itself is unchanged — it never consults the resolver, so any claim you omit (perms, prefix, disks, …) comes from config('fluxfiles.defaults') (read/write/delete, empty prefix). That is your responsibility: always pass prefix and perms explicitly, or use the resolver. tokenWithByob() behaves the same.

Token refresh. <x-fluxfiles>'s default onTokenRefresh sends a signed refresh ticket (an X-FluxFiles-Refresh-Ticket header, never the URL) that binds the tag's :overrides to the logged-in user, so an expired token is re-minted with the same scope it was rendered with. The ticket only refines the resolver's policy: without a configured resolver the route answers 403 token_refresh_unconfigured (the UI then asks for a reload). Custom hooks without a resolver need their own endpoint calling FluxFiles::token(). Tickets last refresh_ticket_ttl seconds (default 12 h); the response is Cache-Control: no-store.

Session-only requests (proxy mode)

The proxied API authenticates on the FluxFiles Bearer token. A request that carries only the Laravel session cookie:

  • POST / PUT / DELETE → 401 token_missing. The route prefix is CSRF-exempt (see below), so a cookie-only write is exactly what a cross-site form can forge.
  • GET / HEAD → allowed only when a claims resolver is configured (the token is minted from it) and the request comes from this site or one of allowed_origins (checked via Origin / Sec-Fetch-Site; cross-site → 403 origin_denied). Without a resolver → 401 token_missing.

The language routes (lang, lang/{locale}) need neither.

Blade Component

<x-fluxfiles
    disk="local"
    mode="picker"
    width="100%"
    height="600px"
    @select="handleFileSelect"
/>

Generate Token

use FluxFiles\Laravel\FluxFilesFacade as FluxFiles;

// For the current authenticated user (needs a claims_resolver, see above;
// without one it throws instead of minting the config defaults)
$token = FluxFiles::tokenForUser();

// With custom overrides
$token = FluxFiles::token(auth()->id(), [
    'perms'      => ['read', 'write'],
    'disks'      => ['local', 's3'],
    'prefix'     => 'user-123/',
    'max_upload'  => 20,    // MB — per uploaded file
    'max_storage' => 1000,  // MB — total quota per prefix (0 = unlimited)
    'max_files'   => 0,     // max files per prefix (0 = unlimited)
    'allowed_ext' => ['jpg', 'png', 'pdf'], // lowercase, no dot; null = all safe
    'ttl'         => 7200,  // seconds — token lifetime (7200 = 2 hours)
]);

Any claim from the configuration reference can also be passed by its raw name in a 'claims' => [...] map.

Enable Import from URL

Import-from-URL is off by default. There's nothing to install or configure server-side per tenant — enabling it is a token claim. Add the import claims to the override array:

$token = FluxFiles::token(auth()->id(), [
    'perms'                => ['read', 'write'],
    'allow_url_import'     => true,                 // required — turns the feature on
    'max_import_mb'        => 20,                   // optional — cap per import (MB)
    'import_url_allowlist' => ['*.unsplash.com'],   // optional — restrict source hosts
    // 'import_path' => 'imports', 'import_rate_limit' => 10, 'import_concurrency' => 3
]);

The core then accepts POST /api/fm/import-url ({ "url": "…", "path": "…" }) for that token — SSRF-guarded and sharing the quota/dedup/variants pipeline. Server-wide defaults (when a claim is omitted) come from FLUXFILES_IMPORT_* env vars on the core service.

Per-tenant configuration

FluxFiles is stateless — the token is the per-tenant config. There's no config file or table per customer; you mint a different token, and FluxFiles enforces its claims server-side. Drive the values from the tenant's plan:

use FluxFiles\Laravel\FluxFilesFacade as FluxFiles;

$tenant = auth()->user()->tenant;        // your own model

$claims = match ($tenant->plan) {
    // Free — 5 MB/file, images only, 500 MB quota, 200 files
    'free' => [
        'disks'       => ['local'],
        'max_upload'  => 5,
        'allowed_ext' => ['jpg', 'jpeg', 'png', 'webp'],
        'max_storage' => 500,
        'max_files'   => 200,
    ],
    // Pro — 100 MB/file, any safe type, 50 GB quota, unlimited files
    'pro' => [
        'disks'       => ['s3'],
        'max_upload'  => 100,
        'allowed_ext' => null,
        'max_storage' => 51200,
        'max_files'   => 0,
        'ai_auto_tag' => true,             // AI captions/tags on upload
        'rate_read'   => 240,              // higher API rate limit
        'variants'    => ['large' => 2560], // bigger preview variant
    ],
};

$token = FluxFiles::token(auth()->id(), [
    'prefix' => "tenant_{$tenant->id}/",   // isolates each tenant's files
    'perms'  => ['read', 'write', 'delete'],
    ...$claims,
]);

Always derive prefix from the authenticated tenant server-side — never from client input. For full isolation, give each tenant their own bucket with BYOB (byob_disks). See the root README's Multi-tenant section for the full claim list, and Permissions & Deployment for the storage each tenant's _fluxfiles/ index needs.

The ai_auto_tag, rate_read / rate_write and variants overrides are enforced by core ≥ 0.2.8 — on an older core they're simply ignored (the adapter still issues a valid token, it just won't crash). Run composer update fluxfiles/fluxfiles to pick them up.

Blade Directives

<script>
FluxFiles.open({
    endpoint: '@fluxfilesEndpoint',
    token: '@fluxfilesToken',
    disk: 'local',
    mode: 'picker'
});
</script>

Facade Methods

use FluxFiles\Laravel\FluxFilesFacade as FluxFiles;

FluxFiles::token($user, $overrides);   // Generate JWT token (no resolver)
FluxFiles::tokenForUser($overrides);   // Token for auth user (resolver + overrides; throws without a resolver)
FluxFiles::tokenForUserOrNull($overrides); // Same, but null (+ log) instead of throwing
FluxFiles::tokenForResolvedUser($user, $overrides); // Same, for a given user
FluxFiles::resolveClaimsUsing($callable);            // Register the claims resolver
FluxFiles::refreshTicketForUser($overrides);         // Ticket for a custom refresh hook
FluxFiles::endpoint();                  // Get FluxFiles URL
FluxFiles::iframeSrc();                 // Get iframe source URL
FluxFiles::sdkUrl();                    // Get SDK script URL
FluxFiles::licenseInfo();               // License status summary (no HTTP call)

Keeping a subscription key current

Monthly keys are renewed by fluxfiles license refresh (core), which keeps the newest key in a server-local file that overlays FLUXFILES_LICENSE_KEY. Runtime goes through core's LicenseManager::fromEnv(), so no Laravel code is involved and it works under config:cache. Point the file outside vendor/ (the default would live there and composer install wipes it) and schedule it as the web user:

FLUXFILES_LICENSE_FILE=/var/www/app/storage/app/fluxfiles-license.json
17 4 * * * cd /var/www/app && sudo -u www-data php vendor/bin/fluxfiles license refresh

FLUXFILES_LICENSE_FILE must be an absolute path (use storage_path('app/fluxfiles-license.json') to compute it when generating the .env). FLUXFILES_LICENSE_REFRESH=false disables the automatic call.

Scheduled e-mail notices

Expiry warnings, intake digests and document-request reminders are sent by a sweep that nothing runs for you. Schedule the command (Laravel 11+, routes/console.php):

use Illuminate\Support\Facades\Schedule;

Schedule::command('fluxfiles:notify-run --discover')->hourly();

(On Laravel 10 and older, use $schedule->command('fluxfiles:notify-run --discover')->hourly(); in app/Console/Kernel.php.) A scheduler needs the usual * * * * * php artisan schedule:run cron entry.

php artisan fluxfiles:notify-run [--disk=local] [--prefix=<p>]... [--prefixes-file=<path>] [--discover] [--dry-run] [--max=50]

It needs the Intake or Share module (installed and licensed). Mail goes out the way the proxy routes send it: the app's own mailer (config/mail.php; FLUXFILES_LARAVEL_MAILER picks one), unless FLUXFILES_MAIL_TRANSPORT is set.

What one run covers. The sweep reads one tenant store per prefix (<prefix>/_fluxfiles/intakes.json and shares.json) and mails only the recipients sealed in each record. It never reads notify_* settings, so there is no env var to set. A run covers exactly the stores you point it at:

  • --prefix=<p> (repeatable) and --prefixes-file=<path> (one prefix per line) name tenants explicitly; use these for S3 / SFTP disks.
  • --discover (local disks only) walks the disk root for every _fluxfiles/intakes.json / shares.json: depth up to 6, at most 10 000 stores, _fluxfiles/trash skipped.
  • With none of these, only the empty prefix is swept, i.e. portals and links created by tokens without a prefix. If you mint per-user prefixes (users/{id}, as above), add --discover or list them, or their reminders and expiry notices never go out.

--max is shared by the whole run and the output says how many stores were swept. --dry-run reports without sending. Exit codes: 0 ok, 1 a usage/config problem (no module, a FLUXFILES_SECRET shorter than 32 bytes, unknown disk, bad option), 2 a failed sweep (a storage or unexpected error; a store that fails is named and the others still run).

License Status

FluxFiles::licenseInfo() returns the same shape as GET /api/fm/license (edition/status/enforcement/modules/limits/expires/days_left/ updates_allowed), but as a direct in-process call — it reads \FluxFiles\LicenseManager::fromEnv()->info() straight from core, so it works from a non-request context (a scheduled command, a queued job, php artisan tinker) where there's no authenticated Claims object to satisfy the HTTP route.

This package does not ship a bundled admin-notice UI for license expiry the way the WordPress plugin does. WordPress plugins all post into one shared wp-admin screen, so a FluxFiles-authored notice fits an existing convention there. A Laravel app owns its own admin surface — Nova, Filament, a hand-rolled panel, or none — and FluxFiles has no standard place to inject UI into, so this is deliberately left to the host app. Two suggested patterns:

// app/Console/Kernel.php — scheduled check, alert however this app already does
$schedule->call(function () {
    $info = FluxFiles::licenseInfo();
    if ($info['days_left'] !== null && $info['days_left'] <= 14) {
        Log::warning("FluxFiles license expiring in {$info['days_left']} days", $info);
        // …or notify a Slack channel, send an email, etc. — whatever this
        // app already uses for ops alerts.
    }
})->daily();
// Surface it inside whatever admin panel this app already has
// (Nova resource, Filament page, a hand-rolled dashboard widget):
$licenseInfo = FluxFiles::licenseInfo();

Server env and php artisan config:cache. Core and the paid modules read their server settings from the environment: FLUXFILES_LICENSE_KEY, the module engines (FLUXFILES_AIVISION_*, FLUXFILES_DLP_ENDPOINT, FLUXFILES_C2PA_MANIFEST, FLUXFILES_WEBHOOK_ALLOW_INTERNAL, …), FLUXFILES_XACCEL and the other server-side switches. Put them in .env like any other setting. The adapter captures every FLUXFILES_* value into the server_env config key, so it ends up in the config cache, and restores it at boot. A value set in the real process environment always wins. Before this, a cached config dropped anything that was only in .env: every paid module answered 402 and the server-side switches stopped working.

Configuration

After publishing, edit config/fluxfiles.php:

return [
    'secret'     => env('FLUXFILES_SECRET'),
    'mode'       => env('FLUXFILES_MODE', 'proxy'),
    'endpoint'   => env('FLUXFILES_ENDPOINT'),

    'route_prefix' => 'api/fm',
    'middleware'    => ['web', 'auth'],

    // Per-user token policy — see "Per-user token policy" above.
    'claims_resolver'    => null,
    'refresh_ticket_ttl' => 43200,   // seconds

    // CSP frame-ancestors for /public/index.html (empty = 'self' + allowed_origins).
    'frame_ancestors' => env('FLUXFILES_FRAME_ANCESTORS', ''),

    // 'json' (default — bookkeeping in each disk's _fluxfiles/) or 'db'
    // (your app's own database connection; run the package migration)
    'storage_backend' => env('FLUXFILES_STORAGE_BACKEND', 'json'),
    'db_connection'   => env('FLUXFILES_DB_CONNECTION', null),

    'disks' => [
        'local' => [...],
        's3'    => [...],
        'r2'    => [...],
    ],

    'defaults' => [
        'perms'       => ['read', 'write', 'delete'],
        'disks'       => ['local'],
        'prefix'      => '',
        'max_upload'  => 10,    // MB
        'allowed_ext' => null,  // null = allow all
        'max_storage' => 0,     // 0 = unlimited
        'ttl'         => 3600,  // seconds
    ],

    'locale'      => env('FLUXFILES_LOCALE', ''),
    // claude|anthropic, gemini|google, openai, openrouter, groq, mistral,
    // xai|grok, ollama, or compatible (any OpenAI-compatible endpoint).
    'ai_provider' => env('FLUXFILES_AI_PROVIDER', ''),
    'ai_api_key'  => env('FLUXFILES_AI_API_KEY', ''),
    'ai_model'    => env('FLUXFILES_AI_MODEL', ''),   // empty = provider default
    'ai_base_url' => env('FLUXFILES_AI_BASE_URL', ''), // self-hosted / gateway
    'ai_auto_tag' => env('FLUXFILES_AI_AUTO_TAG', false),
];

Testing the AI connection

POST {route_prefix}/ai/test (body {"disk": "local"}) sends one tiny real vision call to the configured provider and answers 200 with {ok, provider, model, latency_ms, code, hint, ...} whether it passed or failed (a failed test is a successful diagnosis; code is e.g. ai_auth, ai_model_not_found, ai_quota). It needs the same token as /ai-tag (the disk, write, a configured provider); ai_auto_tag is not required. It is a paid call, so it has its own limit of 2 per minute per user, and it is audited as ai_test. The provider's own error text (detail) is returned only to an unscoped, non-BYOB, non-owner_only token, never to a tenant. The key is never in any response. GET {route_prefix}/disk/doctor gains an additive ai block (provider, model) for tokens that can write, without any network call.

From the shell, with the same config/fluxfiles.php settings:

php artisan fluxfiles:doctor --ai            # one tiny vision call (paid)
php artisan fluxfiles:doctor --ai --cheap    # only look the model up at the provider (free)

It prints OK ai - claude/claude-sonnet-4-5 (812 ms) or FAIL ai - <code> ... with a fix: line, and a failure makes the command exit non-zero. It never prints the key; the base URL and its host are replaced by <base-url> / <host>. To route the call through your own HTTP client (or fake it in tests), bind a FluxFiles\HttpTransportInterface in the container under the key fluxfiles.ai_transport (AI calls only; the generic interface is not consulted, because core uses it for mail and OIDC too). The base URL is operator config, so there is no SSRF guard here, as in core.

(Abridged — the published file also carries the rate limits — read/write, /img, /stream, URL import (FLUXFILES_IMPORT_RATE_LIMIT, default 10/min; a token's import_rate_limit wins) and /usage + /duplicates (2/min: this proxy recomputes usage on every call) — plus storage_path, and comments for every key.)

CSRF exclusion (proxy mode only)

In proxy mode the routes run under the web middleware group (needed for the session-based auth bridge), which includes Laravel's CSRF protection. The FluxFiles SDK authenticates every call with an Authorization: Bearer <jwt> header — not a Laravel CSRF token — so the mutating routes (upload, delete, move, rename, …) return 419 Page Expired until you exclude the FluxFiles route prefix from CSRF. Use the value of config('fluxfiles.route_prefix') (default api/fm) with a /* wildcard.

The file/location differs by Laravel version:

Laravel 11 / 12 — there is no VerifyCsrfToken.php; configure it in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'api/fm/*',   // = config('fluxfiles.route_prefix') . '/*'
    ]);
})

Laravel 9 / 10 — add it to the $except array in app/Http/Middleware/VerifyCsrfToken.php:

protected $except = [
    'api/fm/*',   // = config('fluxfiles.route_prefix') . '/*'
];

Standalone mode is unaffected — the core runs as its own server with its own Origin-based CSRF check, and Laravel only mints tokens / embeds the iframe.

Excluding the prefix is safe because the routes never act on the session cookie alone for a write: a request without a Bearer token is refused for POST/PUT/DELETE (see Session-only requests).

Permissions & Deployment

By default FluxFiles keeps all of its state on disk (no database — unless you set storage_backend to db, which moves the bookkeeping below into your app's database connection). Two locations must be writable by the user PHP-FPM runs as (usually www-data):

Path Holds Created when
<local disk root>/_fluxfiles/ search index, folder index, file locks, audit log, trash manifest, metadata sidecars first write to that disk (upload / mkdir / …)
config('fluxfiles.storage_path') (default storage/fluxfiles/) proxy-mode rate-limiter counter (rate_limit.json; in db mode the counter lives in the fluxfiles_rate_limits table instead) first request

_fluxfiles/

Lives inside the disk root you configure (e.g. a root of storage/app/fluxfiles → storage/app/fluxfiles/_fluxfiles/), and again under each tenant prefix (<root>/<prefix>/_fluxfiles/). PHP creates it on the first write, so the safest rule is: let PHP create it — don't pre-create it as root or your deploy user.

It holds FluxFiles' bookkeeping, and none of it should ever be downloadable:

Path Why it is sensitive
audit.jsonl, audit/archive/ who did what: user ids, IP addresses, user agents, per operation
index.json, dirs.json every file and folder of every tenant on the disk
trash.json, trash/ the manifest and the trashed files themselves (still downloadable)
meta/ metadata sidecars: titles, alt text, tags
fixity.json, usage.json, optimize.json checksums, usage and optimisation stats

With storage_backend = db most of the above moves into your database, but trash/ (the bytes) stays on the disk. The rate limiter moves too, into a fluxfiles_rate_limits table (named like the other adapter tables, honours your connection's table prefix, and never touches a table of your own called rate_limits; published by vendor:publish --tag=fluxfiles-migrations, so re-publish and php artisan migrate after upgrading). Until that table exists the adapter logs a warning (at most once a minute) and keeps using rate_limit.json.

# Make the uploads tree writable by the web server user (adjust www-data to your
# PHP-FPM user: `ps aux | grep php-fpm | grep -v root`)
sudo chown -R www-data:www-data /path/to/public/uploads
sudo chmod -R u+rwX,g+rwX /path/to/public/uploads

Symptom → fix. A 500 with fopen(.../_fluxfiles/index.lock): Permission denied (or, on core ≥ 0.2.7, a clean storage_not_writable error naming the path) means the web server user can't write _fluxfiles/. Almost always the directory was pre-created by a different user — chown it back to the PHP-FPM user (or delete it and let PHP recreate it):

sudo chown -R www-data:www-data /path/to/public/uploads/_fluxfiles

Keep _fluxfiles/ off the web

Prefer a disk root outside the web root. Note that the package default, storage_path('app/public/fluxfiles/uploads'), is only "outside public/" until you run php artisan storage:link: that makes public/storage a symlink to storage/app/public, so the default root is web-served at /storage/fluxfiles/uploads/ (which is also why previews work out of the box). Pick one of:

  1. Truly private (recommended for anything sensitive). Root storage_path('app/fluxfiles') (not under app/public) and FLUXFILES_LOCAL_PRIVATE=true. Files are then served through the gated, token-checked /api/fm/stream route, never as static URLs.
  2. Public files, private bookkeeping. Keep the root under public/ or storage/app/public (so url previews work) and deny _fluxfiles at the web server, as below.

nginx — in the server block that serves the app, before any static location (a regex location earlier in the file wins over a later static one):

location ~* /_fluxfiles/ { deny all; }

Apache — public/.htaccess (needs AllowOverride on), above the Laravel rewrite rules:

RewriteEngine On
RewriteRule (^|/)_fluxfiles(/|$) - [F,NC]

or, in a vhost config where .htaccess is off:

<LocationMatch "(^|/)_fluxfiles(/|$)">
    Require all denied
</LocationMatch>

Core also drops its own _fluxfiles/.htaccess + index.html on local disks. That only helps Apache with AllowOverride enabled; it does nothing on nginx, so do not rely on it.

Verify it. php artisan fluxfiles:doctor flags every local disk root that sits inside the web root and probes /_fluxfiles/index.json over HTTP (--no-probe to skip the probe; non-zero exit on a problem; --ai adds a live AI connection test, see "Testing the AI connection"). The same static checks appear as warnings in GET {route_prefix}/disk/doctor. It also lists keys missing from a stale published config/fluxfiles.php.

On S3 / R2 disks there is nothing to chmod — _fluxfiles/ lives in the bucket as regular objects, governed by your IAM policy (s3:PutObject etc.). Run the Bucket Doctor to verify those grants.

rate_limit.json

In proxy mode (with the default json storage backend) the rate limiter keeps its counter in a JSON file at config('fluxfiles.storage_path') — by default storage/fluxfiles/rate_limit.json (override with FLUXFILES_STORAGE_PATH). PHP creates the directory 0755 and the file 0600 automatically on the first request.

  • The directory must be writable by the user PHP-FPM runs as (usually www-data). Laravel's storage/ already requires this, so the standard deploy perms cover it:

    sudo chown -R www-data:www-data storage bootstrap/cache
    sudo chmod -R 775 storage bootstrap/cache
  • Let PHP create rate_limit.json itself. It's chmod-ed to 0600 (owner only), so it must be owned by the PHP-FPM user. If a deploy script or root pre-creates it as another user, PHP-FPM can't read it and every request fails with 500 "Rate limiter unavailable". Fix:

    sudo chown www-data:www-data storage/fluxfiles/rate_limit.json   # or just delete it; PHP recreates it
  • No web-server rule needed. Unlike the standalone core, this file lives under Laravel's storage/ (outside the public/ web root), so it is never served. Keep the 0600 mode — don't loosen it.

  • Read-only / immutable deploys (e.g. containers): point the path at a writable volume —

    FLUXFILES_STORAGE_PATH=/var/lib/fluxfiles
    sudo install -d -o www-data -g www-data -m 775 /var/lib/fluxfiles

Standalone mode (running the core server directly) puts the file at packages/core/storage/rate_limit.json instead — there it is under the web root, so block it at the web server (see the core's docs/guides/DEPLOYMENT.md, which denies the whole storage/ runtime directory).

Using an existing upload directory

If your app already has a directory tree like public/uploads/user_1/, public/uploads/user_2/ (populated before FluxFiles was installed), you can point FluxFiles at it — existing files show up immediately, and a one-shot Artisan command makes them searchable.

Security. A root inside public/ also exposes FluxFiles' _fluxfiles/ bookkeeping (audit log, file index, trash) unless you deny it. Only use this layout if your files already live there, and add the deny rule from Keep _fluxfiles/ off the web at the same time: location ~* /_fluxfiles/ { deny all; } (nginx) or the .htaccess rule (Apache). Starting fresh? Use a root outside public/ instead.

1. Point the local disk at your existing path

If your files already live in public/uploads, in config/fluxfiles.php:

'disks' => [
    'local' => [
        'driver' => 'local',
        'root'   => public_path('uploads'),     // where your files already live
        'url'    => '/uploads',                 // URL prefix for preview links
    ],
],

2. Scope each user to their own sub-folder via the prefix claim

Always derive the prefix server-side from the authenticated user — never trust client input:

use FluxFiles\Laravel\FluxFilesFacade as FluxFiles;

$token = FluxFiles::token(auth()->user(), [
    'prefix' => 'user_' . auth()->id() . '/',
    'disks'  => ['local'],
    'perms'  => ['read', 'write', 'delete'],
]);

With prefix = 'user_1/', all API paths are transparently scoped to public/uploads/user_1/. User 1 cannot see or touch user_2/.

3. Filesystem permissions

Make public/uploads writable by the PHP process (upload / mkdir / delete):

chown -R www-data:www-data public/uploads
chmod -R u+rwX public/uploads

This also covers the _fluxfiles/ index directory FluxFiles writes inside the root — see Permissions & Deployment for the common _fluxfiles/index.lock permission-denied symptom and fix.

4. Seed metadata + folder index for pre-existing content

Listing existing files works out of the box. Preview links load only when the disk url matches a path your web server actually serves. Search relies on the FluxFiles metadata index (_fluxfiles/index.json) and the directory index (_fluxfiles/dirs.json), which are only written when content is created through the API. To make pre-existing files and folders searchable, run the included Artisan command once:

# Dry run first — report what would be indexed, no writes
php artisan fluxfiles:seed --disk=local --dry-run

# Apply
php artisan fluxfiles:seed --disk=local

# Generate thumbnails for existing images
php artisan fluxfiles:seed --disk=local --variants

# Add hashes for duplicate detection too
php artisan fluxfiles:seed --disk=local --hash --variants

# Only a sub-tree
php artisan fluxfiles:seed --disk=local --path=user_1

# Force re-index (overwrite any existing metadata)
php artisan fluxfiles:seed --disk=local --overwrite

What it does:

  • Walks the disk recursively (skipping _fluxfiles/, _variants/, and *.meta.json).
  • For each file: creates a metadata record with title derived from the filename so search can find it. Metadata writes are skipped for files that already have metadata unless --overwrite is passed, but --hash and --variants can still fill in missing hashes/thumbnails.
  • For each folder: tracks it in _fluxfiles/dirs.json so folder search (/api/fm/search-folders) can return it.

After seeding, both file and folder search work for the existing tree.

5. Notes & gotchas

  • FluxFiles creates _fluxfiles/ (metadata index, audit log, trash) and _variants/ (image thumbnails) inside the disk root — e.g. public/uploads/_fluxfiles/ with the example above, and again under each tenant prefix. They are hidden from the UI — do not delete them, and do deny _fluxfiles/ at the web server (see Keep _fluxfiles/ off the web). If you use FTP/rsync/backup tools, add both to your ignore list.
  • url = '/uploads' must match how your web server serves public/. Preview links are built as {url}/{key} — e.g. file key user_1/avatar.jpg → /uploads/user_1/avatar.jpg.
  • Files uploaded before seeding won't have an uploaded_by metadata field. If you later enable owner_only, legacy files fall through gracefully (all users can act on them) until the next time someone edits them through the UI.
  • For S3/R2 disks with an existing bucket, the same seed command works — pass --disk=s3 (or --disk=r2). Listing is slower because it pages the bucket remotely.

Upgrading from < 0.2.51

Security change. Before laravel-v0.2.51, the FluxFilesAuth middleware and GET {route_prefix}/token minted a token from config('fluxfiles.defaults') (read/write/delete, prefix '') for any logged-in session user, i.e. full access to the whole disk. Since 0.2.51 a token comes only from a claims_resolver or from the component's signed refresh ticket, and cookie-only writes return 401 token_missing. See advisory GHSA-m73q-w9rc-jcxh. Upgrade, and review the files your users could reach in the meantime.

Without a claims_resolver the picker fails when its token expires (403 token_refresh_failed) and session-only requests are refused. Add one:

// app/FluxFiles/UserClaims.php
namespace App\FluxFiles;

use FluxFiles\Laravel\ClaimsResolver;
use Illuminate\Contracts\Auth\Authenticatable;

class UserClaims implements ClaimsResolver
{
    public function resolve(Authenticatable $user): array
    {
        return [
            'prefix' => 'user_' . $user->getAuthIdentifier() . '/',   // one folder per user
            'perms'  => ['read', 'write', 'delete'],
            'disks'  => ['local'],
        ];
    }
}
// config/fluxfiles.php
'claims_resolver' => \App\FluxFiles\UserClaims::class,

If you published config/fluxfiles.php from an older version it silently lacks newer keys (claims_resolver, storage_backend, allowed_origins, frame_ancestors, server_env, …). php artisan fluxfiles:doctor lists them. Also check that _fluxfiles/ is not web-served (details).

Features

  • Blade component <x-fluxfiles> with auto token generation
  • Blade directives @fluxfilesToken and @fluxfilesEndpoint
  • Facade FluxFiles::token() for programmatic token generation
  • Proxy mode — serve the FluxFiles API (incl. paid-module routes, /img, /stream and the Share/Intake recipient pages) through Laravel routes
  • Standalone mode — connect to a separate FluxFiles server
  • Optional DB backend — storage_backend = db keeps the bookkeeping in your app's database
  • Auto-discovery — ServiceProvider and Facade register automatically
  • 16 languages — en, vi, zh, ja, ko, fr, de, es, ar, pt, it, ru, th, hi, tr, nl

License

MIT — see LICENSE for details.

Links