Files
SealShare/tests/Browser/ShareFlowTest.php
T
Andreas Reinhold / reiniandClaude Opus 5 40e35bab0e Encrypt uploads in the browser and send them in chunks
A 6 GB upload kept a customer waiting long after its progress bar
reached 100%. The server wrote every upload three times: PHP's
temporary file, Livewire's copy of it ("Processing files...") and the
encrypted file ("Create Share Link"), each a full rewrite of a slow
disk. The unencrypted copy also stayed behind in livewire-tmp.

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

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

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 20:49:17 +02:00

218 lines
9.7 KiB
PHP

<?php
use App\Models\Share;
use App\Models\User;
use App\Services\ShareService;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
/**
* The share flow (upload, share created, share download) and today's rework of it, plus the
* settings/admin buttons and sections reworked alongside it — all changed since the last browser
* run (148ff38) without one. tests/Browser/SealShareTest.php, FrameTest.php and
* SettingsAndAdminTest.php already cover the flow's existing behaviour; this file adds what that
* rework introduced and does not re-assert what those already do (the copy-to-clipboard toast, the
* dragover burst, the QR code's fill and PNG export).
*/
beforeEach(function () {
config(['session.driver' => 'file']);
Storage::fake('shares');
});
test('tab reaches Browse Files with its focus ring, and Enter or Space opens the file picker', function () {
$page = ready(visit('/upload'));
// A spy, not a real dialog: Playwright would otherwise have to field a native file chooser.
$page->script("window.eval(\"window.__fileInputClicks = 0; HTMLInputElement.prototype.click = function () { if (this.type === 'file') { window.__fileInputClicks++ } }\")");
// "body" alone is not a CSS-explicit selector to this plugin's guesser (no special chars) and
// falls back to a text search, which never matches and times out; "html > body" is explicit and
// focuses nothing new (the body takes no tabindex), so the Tab lands where a fresh page load
// would send it: the first tabbable element.
$page->keys('html > body', 'Tab');
$page->assertScript("document.activeElement.matches('[data-md-button]') && document.activeElement.textContent.trim() === 'Browse Files'");
$ring = $page->script('getComputedStyle(document.activeElement).outlineStyle');
expect($ring)->toBe('solid');
$page->keys(':focus', 'Enter');
$page->assertScript('window.__fileInputClicks === 1');
$page->keys(':focus', 'Space');
$page->assertScript('window.__fileInputClicks === 2')
->assertNoJavaScriptErrors();
});
test('the selected files list avoids horizontal overflow once files are chosen', function () {
$path = sys_get_temp_dir().'/a-genuinely-quite-long-holiday-photos-archive-from-portugal-'.uniqid().'.zip';
file_put_contents($path, 'archive');
$page = ready(visit('/upload')->resize(393, 852));
$page->attach('[data-test="file-input"]', $path)
->waitForText('Uploaded');
$rows = $page->script("(() => {
const rows = [...document.querySelectorAll('[data-test=selected-file]')];
return { count: rows.length, allFit: rows.every((row) => row.getBoundingClientRect().right <= window.innerWidth + 0.5) };
})()");
expect($rows['count'])->toBe(1);
expect($rows['allFit'])->toBeTrue();
$page->assertScript('document.documentElement.scrollWidth <= window.innerWidth')
->assertNoJavaScriptErrors();
unlink($path);
});
test('without a secure context the upload page says HTTPS is needed and takes no files', function () {
$page = ready(visit('/upload'));
$page->script("window.eval(\"Alpine.\$data(document.querySelector('[data-test=drop-zone]')).secure = false\")");
$page->assertScript("getComputedStyle(document.querySelector('[data-test=insecure-context]')).display !== 'none'")
->assertSee('Uploads need a secure connection (HTTPS).')
->assertScript("document.querySelector('[data-test=file-input]').disabled === true")
->assertScript("document.querySelector('[data-test=drop-zone]').getAttribute('aria-disabled') === 'true'")
->assertNoJavaScriptErrors();
});
test('the drop zone hides its burst again once the drag leaves', function () {
$page = ready(visit('/upload'));
$burst = "getComputedStyle(document.querySelector('[data-test=drop-zone-burst]')).opacity";
$page->assertScript("{$burst} === '0'");
$page->script("window.eval(\"document.querySelector('[data-test=drop-zone]').dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true }))\")");
$page->assertScript("{$burst} === '1'");
$page->script("window.eval(\"document.querySelector('[data-test=drop-zone]').dispatchEvent(new DragEvent('dragleave', { bubbles: true, cancelable: true }))\")");
$page->assertScript("{$burst} === '0'")
->assertNoJavaScriptErrors();
});
test('the QR dialog holds its code inside the box, and Escape returns focus to the button that opened it', function () {
$share = Share::factory()->create();
$page = ready(visit(route('share.created', $share, false)));
$page->click('[data-test="show-qr-code"]');
$page->wait(1);
$page->assertScript("document.querySelector('[data-test=\"qr-code-dialog\"]').open");
$inside = $page->script("(() => {
const dialog = document.querySelector('[data-test=\"qr-code-dialog\"]').getBoundingClientRect();
const qr = document.querySelector('[data-qr-code] svg').getBoundingClientRect();
return qr.left >= dialog.left - 1 && qr.right <= dialog.right + 1
&& qr.top >= dialog.top - 1 && qr.bottom <= dialog.bottom + 1;
})()");
expect($inside)->toBeTrue();
$page->keys(':focus', 'Escape');
$page->wait(1);
$page->assertScript("! document.querySelector('[data-test=\"qr-code-dialog\"]').open")
->assertScript("document.activeElement === document.querySelector('[data-test=\"show-qr-code\"]')")
->assertNoJavaScriptErrors();
});
test('the download page fits a phone before and after unlocking a password-protected share', function () {
$share = app(ShareService::class)->createShare(
[['file' => UploadedFile::fake()->create('a-genuinely-quite-long-holiday-photos-archive-from-portugal.zip', 120), 'relativePath' => null]],
['password' => 'let-me-in'],
);
$page = ready(visit(route('share.download', $share, false))->resize(393, 852));
$metrics = $page->script("(() => {
const button = document.querySelector('button[type=submit]');
const form = button.closest('[data-md-form]').getBoundingClientRect();
const rect = button.getBoundingClientRect();
return { formWidth: form.width, formRight: form.right, buttonWidth: rect.width, buttonRight: rect.right };
})()");
expect($metrics['buttonWidth'])->toBeLessThan($metrics['formWidth']);
expect($metrics['buttonRight'])->toEqualWithDelta($metrics['formRight'], 1);
$page->assertScript('document.documentElement.scrollWidth <= window.innerWidth');
$page->type('input[type="password"]', 'let-me-in')->press('Unlock');
$page->wait(1);
$page->assertScript("document.querySelector('h2').tagName === 'H2' && document.querySelector('h2').textContent.trim() === 'Shared Files'");
$rows = $page->script("(() => {
const rows = [...document.querySelectorAll('[data-md-list-item]')];
return {
count: rows.length,
allFit: rows.every((row) => row.getBoundingClientRect().right <= window.innerWidth + 0.5),
};
})()");
expect($rows['count'])->toBeGreaterThan(0);
expect($rows['allFit'])->toBeTrue();
$page->assertScript('document.documentElement.scrollWidth <= window.innerWidth')
->assertNoJavaScriptErrors();
});
test('the settings Save button is end-aligned at less than the form\'s width', function (string $url, string $button) {
$this->actingAs($url === '/admin/settings' ? User::factory()->admin()->create() : User::factory()->create());
$page = ready(visit($url)->resize(1280, 800));
$metrics = $page->script("(() => {
const button = document.querySelector('{$button}');
const form = button.closest('[data-md-form]').getBoundingClientRect();
const rect = button.getBoundingClientRect();
return { formWidth: form.width, formRight: form.right, buttonWidth: rect.width, buttonRight: rect.right };
})()");
expect($metrics['buttonWidth'])->toBeLessThan($metrics['formWidth']);
expect($metrics['buttonRight'])->toEqualWithDelta($metrics['formRight'], 1);
})->with([
['/settings/profile', '[data-test="update-profile-button"]'],
['/admin/settings', '[data-test="save-settings"]'],
]);
test('the admin dashboard heads its shares table with an h2 and drops the card', function () {
$admin = User::factory()->admin()->create();
Share::factory()->count(2)->create();
$this->actingAs($admin);
$page = ready(visit('/admin/dashboard'));
$result = $page->script("(() => {
const heading = [...document.querySelectorAll('h2')].find((h) => h.textContent.trim() === 'All Shares');
const table = document.querySelector('table');
return {
headingIsH2: heading?.tagName === 'H2',
headingBeforeTable: !!heading && !!table
&& !!(heading.compareDocumentPosition(table) & Node.DOCUMENT_POSITION_FOLLOWING),
noCard: document.querySelectorAll('[data-md-card]').length === 0,
};
})()");
expect($result['headingIsH2'])->toBeTrue();
expect($result['headingBeforeTable'])->toBeTrue();
expect($result['noCard'])->toBeTrue();
});
test('the admin settings page has six headed sections and no card', function () {
$this->actingAs(User::factory()->admin()->create());
$page = ready(visit('/admin/settings'));
$result = $page->script("(() => {
return {
// Every dialog's own title is an h2 too (components/modal.blade.php), whether open or
// not: exclude those to count only the page's own section headings.
h2Count: document.querySelectorAll('h2:not([data-md-modal-title])').length,
noCard: document.querySelectorAll('[data-md-card]').length === 0,
};
})()");
expect($result['h2Count'])->toBe(6);
expect($result['noCard'])->toBeTrue();
});