Compare commits

..

4 Commits

Author SHA1 Message Date
Dan Brown
cf648906e9 SSR: Hardened URL validator against a range of workarounds
Added a more comprehensive range of tests to cover.
Thanks to naruhodoowl (https://github.com/kilhsrito-crypto) for
reporting.
2026-04-30 10:18:50 +01:00
Dan Brown
fddeb9030b Attachments: Added page access check to attachment delete
Thanks to github.com/404-pkj for reporting.
2026-04-29 18:31:11 +01:00
Dan Brown
99a704698d Deps: Updated PHP package versions 2026-04-29 18:12:24 +01:00
Dan Brown
fc220dea39 Search: Fixed exact saerch term negation causing no results
Closes #6121
2026-04-29 18:07:32 +01:00
56 changed files with 1063 additions and 1231 deletions

View File

@@ -17,7 +17,7 @@ jobs:
if: ${{ github.ref != 'refs/heads/l10n_development' }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
- name: Install NPM deps
run: npm ci

1
.gitignore vendored
View File

@@ -2,7 +2,6 @@
/node_modules
/.vscode
/composer
/composer.phar
/coverage
Homestead.yaml
.env

View File

@@ -5,7 +5,6 @@ namespace BookStack\Access;
use BookStack\Access\Notifications\ConfirmEmailNotification;
use BookStack\Exceptions\ConfirmationEmailException;
use BookStack\Users\Models\User;
use Exception;
class EmailConfirmationService extends UserTokenService
{
@@ -17,7 +16,6 @@ class EmailConfirmationService extends UserTokenService
* Also removes any existing old ones.
*
* @throws ConfirmationEmailException
* @throws Exception
*/
public function sendConfirmation(User $user): void
{

View File

@@ -71,7 +71,7 @@ class LoginService
}
$lastLoginDetails = $this->getLastLoginAttemptDetails();
$this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember']);
$this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
}
/**

View File

@@ -48,16 +48,17 @@ class MfaValue extends Model
}
/**
* Get the decrypted MFA value for the given user and method.
* Easily get the decrypted MFA value for the given user and method.
*/
public static function getValueForUser(User $user, string $method): ?string
{
/** @var MfaValue $mfaVal */
$mfaVal = static::query()
->where('user_id', '=', $user->id)
->where('method', '=', $method)
->first();
return $mfaVal?->getValue();
return $mfaVal ? $mfaVal->getValue() : null;
}
/**

View File

@@ -9,7 +9,10 @@ use phpseclib3\Math\BigInteger;
class OidcJwtSigningKey
{
protected PublicKey $key;
/**
* @var PublicKey
*/
protected $key;
/**
* Can be created either from a JWK parameter array or local file path to load a certificate from.
@@ -17,13 +20,15 @@ class OidcJwtSigningKey
* 'file:///var/www/cert.pem'
* ['kty' => 'RSA', 'alg' => 'RS256', 'n' => 'abc123...'].
*
* @param array|string $jwkOrKeyPath
*
* @throws OidcInvalidKeyException
*/
public function __construct(array|string $jwkOrKeyPath)
public function __construct($jwkOrKeyPath)
{
if (is_array($jwkOrKeyPath)) {
$this->loadFromJwkArray($jwkOrKeyPath);
} elseif (str_starts_with($jwkOrKeyPath, 'file://')) {
} elseif (is_string($jwkOrKeyPath) && strpos($jwkOrKeyPath, 'file://') === 0) {
$this->loadFromPath($jwkOrKeyPath);
} else {
throw new OidcInvalidKeyException('Unexpected type of key value provided');
@@ -33,7 +38,7 @@ class OidcJwtSigningKey
/**
* @throws OidcInvalidKeyException
*/
protected function loadFromPath(string $path): void
protected function loadFromPath(string $path)
{
try {
$key = PublicKeyLoader::load(
@@ -53,7 +58,7 @@ class OidcJwtSigningKey
/**
* @throws OidcInvalidKeyException
*/
protected function loadFromJwkArray(array $jwk): void
protected function loadFromJwkArray(array $jwk)
{
// 'alg' is optional for a JWK, but we will still attempt to validate if
// it exists otherwise presume it will be compatible.
@@ -77,7 +82,7 @@ class OidcJwtSigningKey
throw new OidcInvalidKeyException('A "n" parameter on the provided key is expected');
}
$n = strtr($jwk['n'], '-_', '+/');
$n = strtr($jwk['n'] ?? '', '-_', '+/');
try {
$key = PublicKeyLoader::load([

View File

@@ -102,12 +102,12 @@ class OidcJwtWithClaims implements ProvidesClaims
protected function validateTokenStructure(): void
{
foreach (['header', 'payload'] as $prop) {
if (empty($this->$prop)) {
if (empty($this->$prop) || !is_array($this->$prop)) {
throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
}
}
if (empty($this->signature)) {
if (empty($this->signature) || !is_string($this->signature)) {
throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
}
}

View File

@@ -39,7 +39,7 @@ class OidcUserDetails
): void {
$this->externalId = $claims->getClaim($idClaim) ?? $this->externalId;
$this->email = $claims->getClaim('email') ?? $this->email;
$this->name = static::getUserDisplayName($displayNameClaims, $claims) ?: $this->name;
$this->name = static::getUserDisplayName($displayNameClaims, $claims) ?? $this->name;
$this->groups = static::getUserGroups($groupsClaim, $claims) ?? $this->groups;
$this->picture = static::getPicture($claims) ?: $this->picture;
}

View File

@@ -266,7 +266,7 @@ class Saml2Service
/**
* Extract the details of a user from a SAML response.
*
* @return array{external_id: string, name: string, email: string|null, saml_id: string}
* @return array{external_id: string, name: string, email: string, saml_id: string}
*/
protected function getUserDetails(string $samlID, $samlAttributes): array
{
@@ -357,7 +357,7 @@ class Saml2Service
]);
}
if (empty($userDetails['email'])) {
if ($userDetails['email'] === null) {
throw new SamlException(trans('errors.saml_no_email_address'));
}

View File

@@ -117,14 +117,14 @@ class SocialAuthService
}
// When a user is logged in and the social account exists and is already linked to the current user.
if ($isLoggedIn && $socialAccount->user->id === $currentUser->id) {
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
return redirect('/my-account/auth#social_accounts');
}
// When a user is logged in, A social account exists but the users do not match.
if ($isLoggedIn && $socialAccount->user->id != $currentUser->id) {
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
return redirect('/my-account/auth#social_accounts');

View File

@@ -15,14 +15,14 @@ use BookStack\Users\Models\User;
class NotificationManager
{
/**
* @var array<string, class-string<NotificationHandler>[]>
* @var class-string<NotificationHandler>[]
*/
protected array $handlersByActivity = [];
protected array $handlers = [];
public function handle(Activity $activity, string|Loggable $detail, User $user): void
{
$activityType = $activity->type;
$handlersToRun = $this->handlersByActivity[$activityType] ?? [];
$handlersToRun = $this->handlers[$activityType] ?? [];
foreach ($handlersToRun as $handlerClass) {
/** @var NotificationHandler $handler */
$handler = new $handlerClass();
@@ -35,12 +35,12 @@ class NotificationManager
*/
public function registerHandler(string $activityType, string $handlerClass): void
{
if (!isset($this->handlersByActivity[$activityType])) {
$this->handlersByActivity[$activityType] = [];
if (!isset($this->handlers[$activityType])) {
$this->handlers[$activityType] = [];
}
if (!in_array($handlerClass, $this->handlersByActivity[$activityType])) {
$this->handlersByActivity[$activityType][] = $handlerClass;
if (!in_array($handlerClass, $this->handlers[$activityType])) {
$this->handlers[$activityType][] = $handlerClass;
}
}

View File

@@ -17,14 +17,7 @@ use ReflectionMethod;
class ApiDocsGenerator
{
/**
* @var array<string, ReflectionClass>
*/
protected array $reflectionClasses = [];
/**
* @var array<string, ApiController>
*/
protected array $controllerClasses = [];
/**
@@ -114,6 +107,7 @@ class ApiDocsGenerator
*/
protected function getBodyParamsFromClass(string $className, string $methodName): ?array
{
/** @var ApiController $class */
$class = $this->controllerClasses[$className] ?? null;
if ($class === null) {
$class = app()->make($className);
@@ -159,7 +153,7 @@ class ApiDocsGenerator
$matches = [];
preg_match_all('/^\s*?\*\s?($|((?![\/@\s]).*?))$/m', $comment, $matches);
$text = implode(' ', $matches[1]);
$text = implode(' ', $matches[1] ?? []);
return str_replace(' ', "\n", $text);
}

View File

@@ -74,21 +74,18 @@ class ApiEntityListFormatter
/**
* Include parent book/chapter info in the formatted data.
* These functions are careful to not load the relation themselves, since they should
* have already been loaded in a more efficient manner, with permissions applied, by the time
* the parent fields are handled here.
*/
public function withParents(): self
{
$this->withField('book', function (Entity $entity) {
if ($entity instanceof BookChild && $entity->relationLoaded('book') && $entity->getRelationValue('book')) {
if ($entity instanceof BookChild && $entity->book) {
return $entity->book->only(['id', 'name', 'slug']);
}
return null;
});
$this->withField('chapter', function (Entity $entity) {
if ($entity instanceof Page && $entity->relationLoaded('chapter') && $entity->getRelationValue('chapter')) {
if ($entity instanceof Page && $entity->chapter) {
return $entity->chapter->only(['id', 'name', 'slug']);
}
return null;

View File

@@ -17,14 +17,29 @@ class ApiTokenGuard implements Guard
use GuardHelpers;
/**
* The last auth exception thrown in this request.
* The request instance.
*/
protected ApiAuthException|null $lastAuthException = null;
protected $request;
public function __construct(
protected Request $request,
protected LoginService $loginService
) {
/**
* @var LoginService
*/
protected $loginService;
/**
* The last auth exception thrown in this request.
*
* @var ApiAuthException
*/
protected $lastAuthException;
/**
* ApiTokenGuard constructor.
*/
public function __construct(Request $request, LoginService $loginService)
{
$this->request = $request;
$this->loginService = $loginService;
}
/**
@@ -52,7 +67,7 @@ class ApiTokenGuard implements Guard
}
/**
* Determine if the current user is authenticated. If not, throw an exception.
* Determine if current user is authenticated. If not, throw an exception.
*
* @throws ApiAuthException
*
@@ -106,7 +121,7 @@ class ApiTokenGuard implements Guard
throw new ApiAuthException(trans('errors.api_no_authorization_found'));
}
if (!str_contains($authToken, ':') || !str_starts_with($authToken, 'Token ')) {
if (strpos($authToken, ':') === false || strpos($authToken, 'Token ') !== 0) {
throw new ApiAuthException(trans('errors.api_bad_authorization_format'));
}
}
@@ -140,7 +155,7 @@ class ApiTokenGuard implements Guard
/**
* {@inheritdoc}
*/
public function validate(array $credentials = []): bool
public function validate(array $credentials = [])
{
if (empty($credentials['id']) || empty($credentials['secret'])) {
return false;
@@ -160,7 +175,7 @@ class ApiTokenGuard implements Guard
/**
* "Log out" the currently authenticated user.
*/
public function logout(): void
public function logout()
{
$this->user = null;
}

View File

@@ -32,7 +32,7 @@ class AssignSortRuleCommand extends Command
*/
public function handle(BookSorter $sorter): int
{
$sortRuleId = intval($this->argument('sort-rule'));
$sortRuleId = intval($this->argument('sort-rule')) ?? 0;
if ($sortRuleId === 0) {
return $this->listSortRules();
}

View File

@@ -32,7 +32,6 @@ class CopyShelfPermissionsCommand extends Command
{
$shelfSlug = $this->option('slug');
$cascadeAll = $this->option('all');
$noInteraction = boolval($this->option('no-interaction'));
$shelves = null;
if (!$cascadeAll && !$shelfSlug) {
@@ -42,16 +41,14 @@ class CopyShelfPermissionsCommand extends Command
}
if ($cascadeAll) {
if (!$noInteraction) {
$continue = $this->confirm(
'Permission settings for all shelves will be cascaded. ' .
'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. ' .
'Are you sure you want to proceed?',
);
$continue = $this->confirm(
'Permission settings for all shelves will be cascaded. ' .
'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. ' .
'Are you sure you want to proceed?'
);
if (!$continue) {
return 0;
}
if (!$continue && !$this->hasOption('no-interaction')) {
return 0;
}
$shelves = $queries->start()->get(['id']);

View File

@@ -213,23 +213,15 @@ class InstallModuleCommand extends Command
$redirectLocation = $resp->getHeaderLine('Location');
if ($redirectLocation) {
$redirectUrl = parse_url($redirectLocation);
$redirectOriginMatches = ($originalUrl['host'] ?? '') === ($redirectUrl['host'] ?? '')
if (
($originalUrl['host'] ?? '') === ($redirectUrl['host'] ?? '')
&& ($originalUrl['scheme'] ?? '') === ($redirectUrl['scheme'] ?? '')
&& ($originalUrl['port'] ?? '') === ($redirectUrl['port'] ?? '');
if (!$redirectOriginMatches) {
$redirectOrigin = ($redirectUrl['scheme'] ?? '') . '://' . ($redirectUrl['host'] ?? '') . (isset($redirectUrl['port']) ? ':' . $redirectUrl['port'] : '');
$this->info("The download URL is redirecting to a different site: {$redirectOrigin}");
$shouldContinue = $this->confirm("Do you trust downloading the module from this site?");
if (!$shouldContinue) {
$this->error("Stopping module installation");
return null;
}
&& ($originalUrl['port'] ?? '') === ($redirectUrl['port'] ?? '')
) {
$currentLocation = $redirectLocation;
$redirectCount++;
continue;
}
$currentLocation = $redirectLocation;
$redirectCount++;
continue;
}
}

View File

@@ -17,7 +17,7 @@ use Illuminate\Support\Collection;
*
* @property string $description
* @property string $description_html
* @property ?int $image_id
* @property int $image_id
* @property ?int $default_template_id
* @property ?int $sort_rule_id
* @property \Illuminate\Database\Eloquent\Collection $chapters

View File

@@ -479,7 +479,6 @@ abstract class Entity extends Model implements
'chapter' => new Chapter(),
'book' => new Book(),
'bookshelf' => new Bookshelf(),
default => throw new \InvalidArgumentException("Invalid entity type: {$type}"),
};
}
}

View File

@@ -23,7 +23,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
* @property bool $draft
* @property int $revision_count
* @property string $editor
* @property Chapter|null $chapter
* @property Chapter $chapter
* @property Collection $attachments
* @property Collection $revisions
* @property PageRevision $currentRevision

View File

@@ -60,7 +60,7 @@ class PageRepo
$page->book_id = $parent->id;
}
$defaultTemplate = $page->chapter?->defaultTemplate()->get() ?? $page->book->defaultTemplate()->get();
$defaultTemplate = $page->chapter?->defaultTemplate()->get() ?? $page->book?->defaultTemplate()->get();
if ($defaultTemplate) {
$page->forceFill([
'html' => $defaultTemplate->html,

View File

@@ -359,7 +359,7 @@ class PageContent
{
$contentHash = md5($html);
$contentId = $this->page->id;
$contentTime = $this->page->updated_at->timestamp ?? time();
$contentTime = $this->page->updated_at?->timestamp ?? time();
$appVersion = AppVersion::get();
$filterConfig = config('app.content_filtering') ?? '';
return "page-content-cache::{$filterConfig}::{$appVersion}::{$contentId}::{$contentTime}::{$contentHash}";

View File

@@ -47,7 +47,7 @@ class PermissionsUpdater
{
if (isset($data['role_permissions'])) {
$entity->permissions()->where('role_id', '!=', 0)->delete();
$rolePermissionData = $this->formatPermissionsFromApiRequestToEntityPermissions($data['role_permissions'], false);
$rolePermissionData = $this->formatPermissionsFromApiRequestToEntityPermissions($data['role_permissions'] ?? [], false);
$entity->permissions()->createMany($rolePermissionData);
}

View File

@@ -208,7 +208,7 @@ class ExportFormatter
preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
// Replace image src with base64 encoded image strings
if (count($imageTagsOutput[0]) > 0) {
if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
foreach ($imageTagsOutput[0] as $index => $imgMatch) {
$oldImgTagString = $imgMatch;
$srcString = $imageTagsOutput[2][$index];
@@ -225,7 +225,7 @@ class ExportFormatter
preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput);
// Update relative links to be absolute, with instance url
if (count($linksOutput[0]) > 0) {
if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
foreach ($linksOutput[0] as $index => $linkMatch) {
$oldLinkString = $linkMatch;
$srcString = $linksOutput[2][$index];

View File

@@ -82,8 +82,10 @@ class ZipImportRunner
$entity = $this->importBook($exportModel, $reader);
} else if ($exportModel instanceof ZipExportChapter) {
$entity = $this->importChapter($exportModel, $parent, $reader);
} else {
} else if ($exportModel instanceof ZipExportPage) {
$entity = $this->importPage($exportModel, $parent, $reader);
} else {
throw new ZipImportException(['No importable data found in import data.']);
}
$this->references->replaceReferences();
@@ -130,7 +132,7 @@ class ZipImportRunner
'name' => $exportBook->name,
'description_html' => $exportBook->description_html ?? '',
'image' => $exportBook->cover ? $this->zipFileToUploadedFile($exportBook->cover, $reader) : null,
'tags' => $this->exportTagsToInputArray($exportBook->tags),
'tags' => $this->exportTagsToInputArray($exportBook->tags ?? []),
]);
if ($book->coverInfo()->getImage()) {
@@ -149,7 +151,7 @@ class ZipImportRunner
foreach ($children as $child) {
if ($child instanceof ZipExportChapter) {
$this->importChapter($child, $book, $reader);
} else {
} else if ($child instanceof ZipExportPage) {
$this->importPage($child, $book, $reader);
}
}
@@ -164,7 +166,7 @@ class ZipImportRunner
$chapter = $this->chapterRepo->create([
'name' => $exportChapter->name,
'description_html' => $exportChapter->description_html ?? '',
'tags' => $this->exportTagsToInputArray($exportChapter->tags),
'tags' => $this->exportTagsToInputArray($exportChapter->tags ?? []),
], $parent);
$exportPages = $exportChapter->pages;
@@ -197,7 +199,7 @@ class ZipImportRunner
'name' => $exportPage->name,
'markdown' => $exportPage->markdown ?? '',
'html' => $exportPage->html ?? '',
'tags' => $this->exportTagsToInputArray($exportPage->tags),
'tags' => $this->exportTagsToInputArray($exportPage->tags ?? []),
]);
$this->references->addPage($page, $exportPage);
@@ -300,7 +302,7 @@ class ZipImportRunner
array_push($chapters, ...$exportModel->chapters);
} else if ($exportModel instanceof ZipExportChapter) {
$chapters[] = $exportModel;
} else {
} else if ($exportModel instanceof ZipExportPage) {
$pages[] = $exportModel;
}

View File

@@ -68,6 +68,10 @@ class ZipReferenceParser
$matches = [];
preg_match_all($referenceRegex, $content, $matches);
if (count($matches) < 3) {
return $content;
}
for ($i = 0; $i < count($matches[0]); $i++) {
$referenceText = $matches[0][$i];
$type = strtolower($matches[1][$i]);

View File

@@ -62,7 +62,7 @@ abstract class Controller extends BaseController
*/
protected function checkPermission(string|Permission $permission): void
{
if (!user()->can($permission)) {
if (!user() || !user()->can($permission)) {
$this->showPermissionError();
}
}

View File

@@ -61,7 +61,8 @@ class JointPermissionBuilder
return;
}
if ($entity instanceof BookChild) {
/** @var BookChild $entity */
if ($entity->book) {
$entities[] = $entity->book;
}

View File

@@ -121,11 +121,13 @@ class SearchOptions
foreach ($patterns as $termType => $pattern) {
$matches = [];
preg_match_all($pattern, $searchString, $matches);
foreach ($matches[1] as $index => $value) {
$negated = str_starts_with($matches[0][$index], '-');
$terms[$termType][] = $constructors[$termType]($value, $negated);
if (count($matches) > 0) {
foreach ($matches[1] as $index => $value) {
$negated = str_starts_with($matches[0][$index], '-');
$terms[$termType][] = $constructors[$termType]($value, $negated);
}
$searchString = preg_replace($pattern, '', $searchString);
}
$searchString = preg_replace($pattern, '', $searchString);
}
// Unescape exacts and backslash escapes
@@ -259,7 +261,7 @@ class SearchOptions
$userFilters = ['updated_by', 'created_by', 'owned_by'];
$unsupportedFilters = ['is_template', 'sort_by'];
foreach ($this->filters->all() as $filter) {
if (in_array($filter->getKey(), $userFilters, true) && $filter->value && $filter->value !== 'me') {
if (in_array($filter->getKey(), $userFilters, true) && $filter->value !== null && $filter->value !== 'me') {
$options[] = $filter;
} else if (in_array($filter->getKey(), $unsupportedFilters, true)) {
$options[] = $filter;

View File

@@ -120,8 +120,14 @@ class SearchRunner
$filter = function (EloquentBuilder $query) use ($exact) {
$inputTerm = str_replace('\\', '\\\\', $exact->value);
$query->where('name', 'like', '%' . $inputTerm . '%')
->orWhere('description', 'like', '%' . $inputTerm . '%')
->orWhere('text', 'like', '%' . $inputTerm . '%');
->orWhere(function (EloquentBuilder $query) use ($inputTerm) {
$query->whereNotNull('description')
->where('description', 'like', '%' . $inputTerm . '%');
})
->orWhere(function (EloquentBuilder $query) use ($inputTerm) {
$query->whereNotNull('text')
->where('text', 'like', '%' . $inputTerm . '%');
});
};
$exact->negated ? $entityQuery->whereNot($filter) : $entityQuery->where($filter);

View File

@@ -125,8 +125,9 @@ class BookSorter
*/
protected function applySortUpdates(BookSortMapItem $sortMapItem, array $modelMap): void
{
/** @var BookChild $model */
$model = $modelMap[$sortMapItem->type . ':' . $sortMapItem->id] ?? null;
if (!($model instanceof BookChild)) {
if (!$model) {
return;
}

View File

@@ -51,14 +51,7 @@ class ThemeModuleManager
}
$folderPath = $this->modulesFolderPath . DIRECTORY_SEPARATOR . $folderName;
try {
$zip->extractTo($folderPath);
} catch (ThemeModuleException $exception) {
if (is_dir($folderPath)) {
$this->deleteDirectoryRecursively($folderPath);
}
throw new ThemeModuleException("Failed to load extract files from module ZIP with error: {$exception->getMessage()}");
}
$zip->extractTo($folderPath);
$module = $this->loadFromFolder($folderName);
if (!$module) {

View File

@@ -2,7 +2,6 @@
namespace BookStack\Theming;
use BookStack\Util\FilePathNormalizer;
use ZipArchive;
readonly class ThemeModuleZip
@@ -16,46 +15,7 @@ readonly class ThemeModuleZip
{
$zip = new ZipArchive();
$zip->open($this->path);
$prefix = $this->getZipContentPrefix($zip);
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
$entryIsDir = str_ends_with($name, "/");
if ($entryIsDir) {
continue;
}
$stream = $zip->getStreamIndex($i);
if ($prefix) {
if (!str_starts_with($name, $prefix) || $name === $prefix) {
continue;
}
$name = str_replace($prefix, '', $name);
}
try {
$targetPath = $destinationPath . DIRECTORY_SEPARATOR . FilePathNormalizer::normalize($name);
} catch (\Exception $exception) {
throw new ThemeModuleException("Bad file path found in module ZIP file: {$name}");
}
$targetPathDir = dirname($targetPath);
if (!is_dir($targetPathDir)) {
$dirCreated = mkdir($targetPathDir, 0777, true);
if (!$dirCreated) {
throw new ThemeModuleException("Failed to create directory {$targetPathDir} when extracting module files");
}
}
$targetFile = fopen($targetPath, 'w');
$written = stream_copy_to_stream($stream, $targetFile);
if (!$written) {
throw new ThemeModuleException("Failed to write to {$targetPath} when extracting module files");
}
fclose($targetFile);
}
$zip->extractTo($destinationPath);
$zip->close();
}
@@ -71,8 +31,7 @@ readonly class ThemeModuleZip
throw new ThemeModuleException("Unable to open zip file at {$this->path}");
}
$prefix = $this->getZipContentPrefix($zip);
$moduleJsonText = $zip->getFromName("{$prefix}bookstack-module.json");
$moduleJsonText = $zip->getFromName('bookstack-module.json');
$zip->close();
if ($moduleJsonText === false) {
@@ -136,20 +95,4 @@ readonly class ThemeModuleZip
return $totalSize;
}
protected function getZipContentPrefix(ZipArchive $zip): string
{
$index = $zip->locateName('bookstack-module.json', ZipArchive::FL_NODIR);
if ($index === false) {
return '';
}
$location = $zip->getNameIndex($index);
$pathParts = explode('/', $location);
if (count($pathParts) !== 2) {
return '';
}
return $pathParts[0] . '/';
}
}

View File

@@ -195,6 +195,7 @@ class AttachmentController extends Controller
$this->validate($request, [
'order' => ['required', 'array'],
]);
$page = $this->pageQueries->findVisibleByIdOrFail($pageId);
$this->checkOwnablePermission(Permission::PageUpdate, $page);
@@ -221,8 +222,6 @@ class AttachmentController extends Controller
throw new NotFoundException(trans('errors.attachment_not_found'));
}
$this->checkOwnablePermission(Permission::PageView, $page);
if ($attachment->external) {
return redirect($attachment->path);
}
@@ -247,6 +246,13 @@ class AttachmentController extends Controller
{
/** @var Attachment $attachment */
$attachment = Attachment::query()->findOrFail($attachmentId);
try {
$this->pageQueries->findVisibleByIdOrFail($attachment->uploaded_to);
} catch (NotFoundException $exception) {
throw new NotFoundException(trans('errors.attachment_not_found'));
}
$this->checkOwnablePermission(Permission::AttachmentDelete, $attachment);
$this->attachmentService->deleteFile($attachment);

View File

@@ -91,7 +91,7 @@ class ImageRepo
$parentFilter = function (Builder $query) use ($filterType, $contextPage) {
if ($filterType === 'page') {
$query->where('uploaded_to', '=', $contextPage->id);
} else {
} else if ($filterType === 'book') {
$validPageIds = $contextPage->book->pages()
->scopes('visible')
->pluck('id')

View File

@@ -148,7 +148,7 @@ class UserAvatars
$responseCount++;
$isRedirect = ($response->getStatusCode() === 301 || $response->getStatusCode() === 302);
$url = $response->getHeader('Location')[0] ?? '';
} while ($responseCount < 3 && $isRedirect && str_starts_with($url, 'http'));
} while ($responseCount < 3 && $isRedirect && is_string($url) && str_starts_with($url, 'http'));
if ($responseCount === 3) {
throw new HttpFetchException("Failed to fetch image, max redirect limit of 3 tries reached. Last fetched URL: {$url}");

View File

@@ -222,7 +222,8 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
public function getAvatar(int $size = 50): string
{
$default = url('/user_avatar.png');
if ($this->image_id === 0) {
$imageId = $this->image_id;
if ($imageId === 0 || $imageId === '0' || $imageId === null) {
return $default;
}

View File

@@ -8,6 +8,10 @@ use BookStack\Exceptions\HttpFetchException;
* Validate the host we're connecting to when making a server-side-request.
* Will use the given hosts config if given during construction otherwise
* will look to the app configured config.
*
* The config format is a space-seperated list of URL prefixes which should contain the
* protocol and host. It can optionally define a path prefix as part of the URL.
* Wildcards, via a '*', can be used within these elements to match anything but a '/'.
*/
class SsrUrlValidator
{
@@ -48,15 +52,34 @@ class SsrUrlValidator
{
$pattern = rtrim(trim($pattern), '/');
$url = trim($url);
$urlParts = parse_url($url);
if (empty($pattern) || empty($url)) {
if (empty($pattern) || empty($url) || $urlParts === false) {
return false;
}
$quoted = preg_quote($pattern, '/');
$regexPattern = str_replace('\*', '.*', $quoted);
// Prevent potential tricks using percent encoded slashes
if (str_contains(strtolower($urlParts['host'] ?? ''), '%2f')) {
return false;
}
return preg_match('/^' . $regexPattern . '($|\/.*$|#.*$)/i', $url);
// Disregard query and fragment
$url = explode('?', $url, 2)[0];
$url = explode('#', $url, 2)[0];
// Disregard userinfo if existing
if (!empty($urlParts['user']) || !empty($urlParts['pass'])) {
[$start, $postUserinfo] = explode('@', $url, 2);
$preUserinfo = explode('//', $start, 2)[0];
$url = ($preUserinfo ? $preUserinfo . '//' : '') . $postUserinfo;
}
// Prepare pattern
$quoted = preg_quote($pattern, '/');
$regexPattern = str_replace('\*', '[^\/]*', $quoted);
// Check against our URL
return preg_match('/^' . $regexPattern . '($|\/.*$)/i', $url);
}
/**

254
composer.lock generated
View File

@@ -62,16 +62,16 @@
},
{
"name": "aws/aws-sdk-php",
"version": "3.376.3",
"version": "3.379.8",
"source": {
"type": "git",
"url": "https://github.com/aws/aws-sdk-php.git",
"reference": "2081f8db174df4bb8842aed3b7b513590ee9d219"
"reference": "856ddf3d241c29132fe1eb946e112351ab043542"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/2081f8db174df4bb8842aed3b7b513590ee9d219",
"reference": "2081f8db174df4bb8842aed3b7b513590ee9d219",
"url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/856ddf3d241c29132fe1eb946e112351ab043542",
"reference": "856ddf3d241c29132fe1eb946e112351ab043542",
"shasum": ""
},
"require": {
@@ -153,9 +153,9 @@
"support": {
"forum": "https://github.com/aws/aws-sdk-php/discussions",
"issues": "https://github.com/aws/aws-sdk-php/issues",
"source": "https://github.com/aws/aws-sdk-php/tree/3.376.3"
"source": "https://github.com/aws/aws-sdk-php/tree/3.379.8"
},
"time": "2026-04-03T18:07:33+00:00"
"time": "2026-04-27T19:13:21+00:00"
},
{
"name": "bacon/bacon-qr-code",
@@ -985,12 +985,12 @@
"version": "v7.0.5",
"source": {
"type": "git",
"url": "https://github.com/firebase/php-jwt.git",
"url": "https://github.com/googleapis/php-jwt.git",
"reference": "47ad26bab5e7c70ae8a6f08ed25ff83631121380"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/firebase/php-jwt/zipball/47ad26bab5e7c70ae8a6f08ed25ff83631121380",
"url": "https://api.github.com/repos/googleapis/php-jwt/zipball/47ad26bab5e7c70ae8a6f08ed25ff83631121380",
"reference": "47ad26bab5e7c70ae8a6f08ed25ff83631121380",
"shasum": ""
},
@@ -1039,8 +1039,8 @@
"php"
],
"support": {
"issues": "https://github.com/firebase/php-jwt/issues",
"source": "https://github.com/firebase/php-jwt/tree/v7.0.5"
"issues": "https://github.com/googleapis/php-jwt/issues",
"source": "https://github.com/googleapis/php-jwt/tree/v7.0.5"
},
"time": "2026-04-01T20:38:03+00:00"
},
@@ -1802,16 +1802,16 @@
},
{
"name": "laravel/framework",
"version": "v12.56.0",
"version": "v12.58.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/framework.git",
"reference": "dac16d424b59debb2273910dde88eb7050a2a709"
"reference": "6172ae1f44ba5d89e111057ee4a4e7c27f5a610d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/framework/zipball/dac16d424b59debb2273910dde88eb7050a2a709",
"reference": "dac16d424b59debb2273910dde88eb7050a2a709",
"url": "https://api.github.com/repos/laravel/framework/zipball/6172ae1f44ba5d89e111057ee4a4e7c27f5a610d",
"reference": "6172ae1f44ba5d89e111057ee4a4e7c27f5a610d",
"shasum": ""
},
"require": {
@@ -1852,8 +1852,8 @@
"symfony/mailer": "^7.2.0",
"symfony/mime": "^7.2.0",
"symfony/polyfill-php83": "^1.33",
"symfony/polyfill-php84": "^1.33",
"symfony/polyfill-php85": "^1.33",
"symfony/polyfill-php84": "^1.34",
"symfony/polyfill-php85": "^1.34",
"symfony/process": "^7.2.0",
"symfony/routing": "^7.2.0",
"symfony/uid": "^7.2.0",
@@ -2020,20 +2020,20 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2026-03-26T14:51:54+00:00"
"time": "2026-04-26T16:42:04+00:00"
},
{
"name": "laravel/prompts",
"version": "v0.3.16",
"version": "v0.3.17",
"source": {
"type": "git",
"url": "https://github.com/laravel/prompts.git",
"reference": "11e7d5f93803a2190b00e145142cb00a33d17ad2"
"reference": "6a82ac19a28b916ae0885828795dbd4c59d9a818"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/prompts/zipball/11e7d5f93803a2190b00e145142cb00a33d17ad2",
"reference": "11e7d5f93803a2190b00e145142cb00a33d17ad2",
"url": "https://api.github.com/repos/laravel/prompts/zipball/6a82ac19a28b916ae0885828795dbd4c59d9a818",
"reference": "6a82ac19a28b916ae0885828795dbd4c59d9a818",
"shasum": ""
},
"require": {
@@ -2077,22 +2077,22 @@
"description": "Add beautiful and user-friendly forms to your command-line applications.",
"support": {
"issues": "https://github.com/laravel/prompts/issues",
"source": "https://github.com/laravel/prompts/tree/v0.3.16"
"source": "https://github.com/laravel/prompts/tree/v0.3.17"
},
"time": "2026-03-23T14:35:33+00:00"
"time": "2026-04-20T16:07:33+00:00"
},
{
"name": "laravel/serializable-closure",
"version": "v2.0.10",
"version": "v2.0.13",
"source": {
"type": "git",
"url": "https://github.com/laravel/serializable-closure.git",
"reference": "870fc81d2f879903dfc5b60bf8a0f94a1609e669"
"reference": "b566ee0dd251f3c4078bed003a7ce015f5ea6dce"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/serializable-closure/zipball/870fc81d2f879903dfc5b60bf8a0f94a1609e669",
"reference": "870fc81d2f879903dfc5b60bf8a0f94a1609e669",
"url": "https://api.github.com/repos/laravel/serializable-closure/zipball/b566ee0dd251f3c4078bed003a7ce015f5ea6dce",
"reference": "b566ee0dd251f3c4078bed003a7ce015f5ea6dce",
"shasum": ""
},
"require": {
@@ -2140,20 +2140,20 @@
"issues": "https://github.com/laravel/serializable-closure/issues",
"source": "https://github.com/laravel/serializable-closure"
},
"time": "2026-02-20T19:59:49+00:00"
"time": "2026-04-16T14:03:50+00:00"
},
{
"name": "laravel/socialite",
"version": "v5.26.1",
"version": "v5.27.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/socialite.git",
"reference": "db6ec2ee967b7f06412c3a0cf1daaf072f4752a4"
"reference": "40e0757a75637c7b2dff05d3286b0d8fc25e5c0e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/socialite/zipball/db6ec2ee967b7f06412c3a0cf1daaf072f4752a4",
"reference": "db6ec2ee967b7f06412c3a0cf1daaf072f4752a4",
"url": "https://api.github.com/repos/laravel/socialite/zipball/40e0757a75637c7b2dff05d3286b0d8fc25e5c0e",
"reference": "40e0757a75637c7b2dff05d3286b0d8fc25e5c0e",
"shasum": ""
},
"require": {
@@ -2212,7 +2212,7 @@
"issues": "https://github.com/laravel/socialite/issues",
"source": "https://github.com/laravel/socialite"
},
"time": "2026-03-29T14:50:53+00:00"
"time": "2026-04-24T14:05:47+00:00"
},
{
"name": "laravel/tinker",
@@ -3362,16 +3362,16 @@
},
{
"name": "nesbot/carbon",
"version": "3.11.3",
"version": "3.11.4",
"source": {
"type": "git",
"url": "https://github.com/CarbonPHP/carbon.git",
"reference": "6a7e652845bb018c668220c2a545aded8594fbbf"
"reference": "e890471a3494740f7d9326d72ce6a8c559ffee60"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/6a7e652845bb018c668220c2a545aded8594fbbf",
"reference": "6a7e652845bb018c668220c2a545aded8594fbbf",
"url": "https://api.github.com/repos/CarbonPHP/carbon/zipball/e890471a3494740f7d9326d72ce6a8c559ffee60",
"reference": "e890471a3494740f7d9326d72ce6a8c559ffee60",
"shasum": ""
},
"require": {
@@ -3463,7 +3463,7 @@
"type": "tidelift"
}
],
"time": "2026-03-11T17:23:39+00:00"
"time": "2026-04-07T09:57:54+00:00"
},
{
"name": "nette/schema",
@@ -4028,16 +4028,16 @@
},
{
"name": "phpseclib/phpseclib",
"version": "3.0.50",
"version": "3.0.52",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "aa6ad8321ed103dc3624fb600a25b66ebf78ec7b"
"reference": "2adaefc83df2ec548558307690f376dd7d4f4fce"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/aa6ad8321ed103dc3624fb600a25b66ebf78ec7b",
"reference": "aa6ad8321ed103dc3624fb600a25b66ebf78ec7b",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/2adaefc83df2ec548558307690f376dd7d4f4fce",
"reference": "2adaefc83df2ec548558307690f376dd7d4f4fce",
"shasum": ""
},
"require": {
@@ -4118,7 +4118,7 @@
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.50"
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.52"
},
"funding": [
{
@@ -4134,7 +4134,7 @@
"type": "tidelift"
}
],
"time": "2026-03-19T02:57:58+00:00"
"time": "2026-04-27T07:02:15+00:00"
},
{
"name": "pragmarx/google2fa",
@@ -6499,16 +6499,16 @@
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638"
"reference": "141046a8f9477948ff284fa65be2095baafb94f2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638",
"reference": "a3cc8b044a6ea513310cbd48ef7333b384945638",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/141046a8f9477948ff284fa65be2095baafb94f2",
"reference": "141046a8f9477948ff284fa65be2095baafb94f2",
"shasum": ""
},
"require": {
@@ -6558,7 +6558,7 @@
"portable"
],
"support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.37.0"
},
"funding": [
{
@@ -6578,20 +6578,20 @@
"type": "tidelift"
}
],
"time": "2024-09-09T11:45:10+00:00"
"time": "2026-04-10T16:19:22+00:00"
},
{
"name": "symfony/polyfill-intl-grapheme",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-intl-grapheme.git",
"reference": "380872130d3a5dd3ace2f4010d95125fde5d5c70"
"reference": "4864388bfbd3001ce88e234fab652acd91fdc57e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/380872130d3a5dd3ace2f4010d95125fde5d5c70",
"reference": "380872130d3a5dd3ace2f4010d95125fde5d5c70",
"url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/4864388bfbd3001ce88e234fab652acd91fdc57e",
"reference": "4864388bfbd3001ce88e234fab652acd91fdc57e",
"shasum": ""
},
"require": {
@@ -6640,7 +6640,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.37.0"
},
"funding": [
{
@@ -6660,11 +6660,11 @@
"type": "tidelift"
}
],
"time": "2025-06-27T09:58:17+00:00"
"time": "2026-04-26T13:13:48+00:00"
},
{
"name": "symfony/polyfill-intl-idn",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-intl-idn.git",
@@ -6727,7 +6727,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.37.0"
},
"funding": [
{
@@ -6751,7 +6751,7 @@
},
{
"name": "symfony/polyfill-intl-normalizer",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-intl-normalizer.git",
@@ -6812,7 +6812,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.37.0"
},
"funding": [
{
@@ -6836,16 +6836,16 @@
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493"
"reference": "6a21eb99c6973357967f6ce3708cd55a6bec6315"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6d857f4d76bd4b343eac26d6b539585d2bc56493",
"reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6a21eb99c6973357967f6ce3708cd55a6bec6315",
"reference": "6a21eb99c6973357967f6ce3708cd55a6bec6315",
"shasum": ""
},
"require": {
@@ -6897,7 +6897,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.37.0"
},
"funding": [
{
@@ -6917,20 +6917,20 @@
"type": "tidelift"
}
],
"time": "2024-12-23T08:48:59+00:00"
"time": "2026-04-10T17:25:58+00:00"
},
{
"name": "symfony/polyfill-php80",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php80.git",
"reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608"
"reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/0cc9dd0f17f61d8131e7df6b84bd344899fe2608",
"reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608",
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
"reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
"shasum": ""
},
"require": {
@@ -6981,7 +6981,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php80/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0"
},
"funding": [
{
@@ -7001,20 +7001,20 @@
"type": "tidelift"
}
],
"time": "2025-01-02T08:10:11+00:00"
"time": "2026-04-10T16:19:22+00:00"
},
{
"name": "symfony/polyfill-php83",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php83.git",
"reference": "17f6f9a6b1735c0f163024d959f700cfbc5155e5"
"reference": "3600c2cb22399e25bb226e4a135ce91eeb2a6149"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/17f6f9a6b1735c0f163024d959f700cfbc5155e5",
"reference": "17f6f9a6b1735c0f163024d959f700cfbc5155e5",
"url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/3600c2cb22399e25bb226e4a135ce91eeb2a6149",
"reference": "3600c2cb22399e25bb226e4a135ce91eeb2a6149",
"shasum": ""
},
"require": {
@@ -7061,7 +7061,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php83/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-php83/tree/v1.37.0"
},
"funding": [
{
@@ -7081,20 +7081,20 @@
"type": "tidelift"
}
],
"time": "2025-07-08T02:45:35+00:00"
"time": "2026-04-10T17:25:58+00:00"
},
{
"name": "symfony/polyfill-php84",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php84.git",
"reference": "d8ced4d875142b6a7426000426b8abc631d6b191"
"reference": "88486db2c389b290bf87ff1de7ebc1e13e42bb06"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php84/zipball/d8ced4d875142b6a7426000426b8abc631d6b191",
"reference": "d8ced4d875142b6a7426000426b8abc631d6b191",
"url": "https://api.github.com/repos/symfony/polyfill-php84/zipball/88486db2c389b290bf87ff1de7ebc1e13e42bb06",
"reference": "88486db2c389b290bf87ff1de7ebc1e13e42bb06",
"shasum": ""
},
"require": {
@@ -7141,7 +7141,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php84/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-php84/tree/v1.37.0"
},
"funding": [
{
@@ -7161,20 +7161,20 @@
"type": "tidelift"
}
],
"time": "2025-06-24T13:30:11+00:00"
"time": "2026-04-10T18:47:49+00:00"
},
{
"name": "symfony/polyfill-php85",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php85.git",
"reference": "d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91"
"reference": "fcfa4973a9917cef23f2e38774da74a2b7d115ee"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91",
"reference": "d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91",
"url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/fcfa4973a9917cef23f2e38774da74a2b7d115ee",
"reference": "fcfa4973a9917cef23f2e38774da74a2b7d115ee",
"shasum": ""
},
"require": {
@@ -7221,7 +7221,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php85/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-php85/tree/v1.37.0"
},
"funding": [
{
@@ -7241,20 +7241,20 @@
"type": "tidelift"
}
],
"time": "2025-06-23T16:12:55+00:00"
"time": "2026-04-26T13:10:57+00:00"
},
{
"name": "symfony/polyfill-uuid",
"version": "v1.33.0",
"version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-uuid.git",
"reference": "21533be36c24be3f4b1669c4725c7d1d2bab4ae2"
"reference": "26dfec253c4cf3e51b541b52ddf7e42cb0908e94"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-uuid/zipball/21533be36c24be3f4b1669c4725c7d1d2bab4ae2",
"reference": "21533be36c24be3f4b1669c4725c7d1d2bab4ae2",
"url": "https://api.github.com/repos/symfony/polyfill-uuid/zipball/26dfec253c4cf3e51b541b52ddf7e42cb0908e94",
"reference": "26dfec253c4cf3e51b541b52ddf7e42cb0908e94",
"shasum": ""
},
"require": {
@@ -7304,7 +7304,7 @@
"uuid"
],
"support": {
"source": "https://github.com/symfony/polyfill-uuid/tree/v1.33.0"
"source": "https://github.com/symfony/polyfill-uuid/tree/v1.37.0"
},
"funding": [
{
@@ -7324,7 +7324,7 @@
"type": "tidelift"
}
],
"time": "2024-09-09T11:45:10+00:00"
"time": "2026-04-10T16:19:22+00:00"
},
{
"name": "symfony/process",
@@ -8285,23 +8285,23 @@
},
{
"name": "voku/portable-ascii",
"version": "2.0.3",
"version": "2.1.1",
"source": {
"type": "git",
"url": "https://github.com/voku/portable-ascii.git",
"reference": "b1d923f88091c6bf09699efcd7c8a1b1bfd7351d"
"reference": "8e1051fe39379367aecf014f41744ce7539a856f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/voku/portable-ascii/zipball/b1d923f88091c6bf09699efcd7c8a1b1bfd7351d",
"reference": "b1d923f88091c6bf09699efcd7c8a1b1bfd7351d",
"url": "https://api.github.com/repos/voku/portable-ascii/zipball/8e1051fe39379367aecf014f41744ce7539a856f",
"reference": "8e1051fe39379367aecf014f41744ce7539a856f",
"shasum": ""
},
"require": {
"php": ">=7.0.0"
"php": ">=7.1.0"
},
"require-dev": {
"phpunit/phpunit": "~6.0 || ~7.0 || ~9.0"
"phpunit/phpunit": "~8.5 || ~9.6 || ~10.5 || ~11.5"
},
"suggest": {
"ext-intl": "Use Intl for transliterator_transliterate() support"
@@ -8331,7 +8331,7 @@
],
"support": {
"issues": "https://github.com/voku/portable-ascii/issues",
"source": "https://github.com/voku/portable-ascii/tree/2.0.3"
"source": "https://github.com/voku/portable-ascii/tree/2.1.1"
},
"funding": [
{
@@ -8355,7 +8355,7 @@
"type": "tidelift"
}
],
"time": "2024-11-21T01:49:47+00:00"
"time": "2026-04-26T05:33:54+00:00"
},
{
"name": "xemlock/htmlpurifier-html5",
@@ -8723,16 +8723,16 @@
},
{
"name": "larastan/larastan",
"version": "v3.9.3",
"version": "v3.9.6",
"source": {
"type": "git",
"url": "https://github.com/larastan/larastan.git",
"reference": "64a52bcc5347c89fdf131cb59f96ebfbc8d1ad65"
"reference": "9ad17e83e96b63536cb6ac39c3d40d29ff9cf636"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/larastan/larastan/zipball/64a52bcc5347c89fdf131cb59f96ebfbc8d1ad65",
"reference": "64a52bcc5347c89fdf131cb59f96ebfbc8d1ad65",
"url": "https://api.github.com/repos/larastan/larastan/zipball/9ad17e83e96b63536cb6ac39c3d40d29ff9cf636",
"reference": "9ad17e83e96b63536cb6ac39c3d40d29ff9cf636",
"shasum": ""
},
"require": {
@@ -8746,7 +8746,7 @@
"illuminate/pipeline": "^11.44.2 || ^12.4.1 || ^13",
"illuminate/support": "^11.44.2 || ^12.4.1 || ^13",
"php": "^8.2",
"phpstan/phpstan": "^2.1.32"
"phpstan/phpstan": "^2.1.44"
},
"require-dev": {
"doctrine/coding-standard": "^13",
@@ -8801,7 +8801,7 @@
],
"support": {
"issues": "https://github.com/larastan/larastan/issues",
"source": "https://github.com/larastan/larastan/tree/v3.9.3"
"source": "https://github.com/larastan/larastan/tree/v3.9.6"
},
"funding": [
{
@@ -8809,7 +8809,7 @@
"type": "github"
}
],
"time": "2026-02-20T12:07:12+00:00"
"time": "2026-04-16T10:02:43+00:00"
},
{
"name": "mockery/mockery",
@@ -8956,23 +8956,23 @@
},
{
"name": "nunomaduro/collision",
"version": "v8.9.2",
"version": "v8.9.4",
"source": {
"type": "git",
"url": "https://github.com/nunomaduro/collision.git",
"reference": "6eb16883e74fd725ac64dbe81544c961ab448ba5"
"reference": "716af8f95a470e9094cfca09ed897b023be191a5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nunomaduro/collision/zipball/6eb16883e74fd725ac64dbe81544c961ab448ba5",
"reference": "6eb16883e74fd725ac64dbe81544c961ab448ba5",
"url": "https://api.github.com/repos/nunomaduro/collision/zipball/716af8f95a470e9094cfca09ed897b023be191a5",
"reference": "716af8f95a470e9094cfca09ed897b023be191a5",
"shasum": ""
},
"require": {
"filp/whoops": "^2.18.4",
"nunomaduro/termwind": "^2.4.0",
"php": "^8.2.0",
"symfony/console": "^7.4.8 || ^8.0.4"
"symfony/console": "^7.4.8 || ^8.0.8"
},
"conflict": {
"laravel/framework": "<11.48.0 || >=14.0.0",
@@ -8980,12 +8980,12 @@
},
"require-dev": {
"brianium/paratest": "^7.8.5",
"larastan/larastan": "^3.9.3",
"laravel/framework": "^11.48.0 || ^12.56.0 || ^13.2.0",
"laravel/pint": "^1.29.0",
"orchestra/testbench-core": "^9.12.0 || ^10.12.1 || ^11.0.0",
"larastan/larastan": "^3.9.6",
"laravel/framework": "^11.48.0 || ^12.56.0 || ^13.5.0",
"laravel/pint": "^1.29.1",
"orchestra/testbench-core": "^9.12.0 || ^10.12.1 || ^11.2.1",
"pestphp/pest": "^3.8.5 || ^4.4.3 || ^5.0.0",
"sebastian/environment": "^7.2.1 || ^8.0.4 || ^9.0.0"
"sebastian/environment": "^7.2.1 || ^8.0.4 || ^9.3.0"
},
"type": "library",
"extra": {
@@ -9048,7 +9048,7 @@
"type": "patreon"
}
],
"time": "2026-03-31T21:51:27+00:00"
"time": "2026-04-21T14:04:20+00:00"
},
{
"name": "phar-io/manifest",
@@ -9170,11 +9170,11 @@
},
{
"name": "phpstan/phpstan",
"version": "2.1.46",
"version": "2.1.54",
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/a193923fc2d6325ef4e741cf3af8c3e8f54dbf25",
"reference": "a193923fc2d6325ef4e741cf3af8c3e8f54dbf25",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/8be50c3992107dc837b17da4d140fbbdf9a5c5bd",
"reference": "8be50c3992107dc837b17da4d140fbbdf9a5c5bd",
"shasum": ""
},
"require": {
@@ -9219,7 +9219,7 @@
"type": "github"
}
],
"time": "2026-04-01T09:25:14+00:00"
"time": "2026-04-29T13:31:09+00:00"
},
{
"name": "phpunit/php-code-coverage",
@@ -10983,5 +10983,5 @@
"platform-overrides": {
"php": "8.2.0"
},
"plugin-api-version": "2.6.0"
"plugin-api-version": "2.9.0"
}

View File

@@ -66,7 +66,6 @@ Here are some general best practices when it comes to creating modules:
### Distribution Format
Modules are expected to be distributed as a compressed ZIP file, where the ZIP contents follow that of a module folder.
Contents may optionally be placed within a nested folder inside the ZIP.
BookStack provides a `php artisan bookstack:install-module` command which allows modules to be installed from these ZIP files, either from a local path or from a web URL.
Currently, there's a hardcoded total filesize limit of 50MB for module contents installed via this method.

View File

@@ -5,15 +5,7 @@
import type {Config} from 'jest';
import {pathsToModuleNameMapper} from "ts-jest";
import fs from "node:fs";
const { compilerOptions } = JSON.parse(fs.readFileSync('./tsconfig.json', 'utf8'));
const compilerPaths = compilerOptions.paths as Record<string, string[]>;
const cleanedPaths: Record<string, string[]> = {};
Object.keys(compilerPaths).forEach((key) => {
const paths = compilerPaths[key];
cleanedPaths[key] = paths.map(p => p.replace('./', ''));
});
import { compilerOptions } from './tsconfig.json';
const config: Config = {
// All imported modules in your tests should be mocked automatically
@@ -106,7 +98,7 @@ const config: Config = {
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
'lexical/shared/invariant': 'resources/js/wysiwyg/lexical/core/shared/__mocks__/invariant',
...pathsToModuleNameMapper(cleanedPaths),
...pathsToModuleNameMapper(compilerOptions.paths),
},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
@@ -119,7 +111,7 @@ const config: Config = {
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: 'ts-jest',
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,

View File

@@ -173,7 +173,6 @@ return [
'books_sort_desc' => 'Move chapters and pages within a book to reorganise its contents. Other books can be added which allows easy moving of chapters and pages between books. Optionally an auto sort rule can be set to automatically sort this book\'s contents upon changes.',
'books_sort_auto_sort' => 'Auto Sort Option',
'books_sort_auto_sort_active' => 'Auto Sort Active: :sortName',
'books_sort_auto_sort_creation_hint' => 'Auto sort option rules can be created in the "Lists & Sorting" settings area by a user with the relevant permissions.',
'books_sort_named' => 'Sort Book :bookName',
'books_sort_name' => 'Sort by Name',
'books_sort_created' => 'Sort by Created Date',

1279
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -20,23 +20,22 @@
"devDependencies": {
"@eslint/js": "^10.0.1",
"@lezer/generator": "^1.8.0",
"@types/jest": "^30.0.0",
"@types/markdown-it": "^14.1.2",
"@types/sortablejs": "^1.15.9",
"chokidar-cli": "^3.0",
"esbuild": "^0.28.0",
"eslint": "^10.2.0",
"esbuild": "^0.27.3",
"eslint": "^10.0.2",
"globals": "^17.4.0",
"jest": "^30.3.0",
"jest-environment-jsdom": "^30.3.0",
"jest": "^30.2.0",
"jest-environment-jsdom": "^30.2.0",
"npm-run-all": "^4.1.5",
"sass": "^1.99.0",
"ts-jest": "^29.4.9",
"sass": "^1.97.3",
"ts-jest": "^29.4.6",
"ts-node": "^10.9.2",
"typescript": "6.0.*"
"typescript": "5.9.*"
},
"dependencies": {
"@codemirror/commands": "^6.10.3",
"@codemirror/commands": "^6.10.2",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.11",
"@codemirror/lang-javascript": "^6.2.5",
@@ -44,14 +43,15 @@
"@codemirror/lang-markdown": "^6.5.0",
"@codemirror/lang-php": "^6.0.2",
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/language": "^6.12.3",
"@codemirror/language": "^6.12.2",
"@codemirror/legacy-modes": "^6.5.2",
"@codemirror/state": "^6.6.0",
"@codemirror/state": "^6.5.4",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.41.0",
"@codemirror/view": "^6.39.16",
"@lezer/highlight": "^1.2.3",
"@ssddanbrown/codemirror-lang-smarty": "^1.0.0",
"@ssddanbrown/codemirror-lang-twig": "^1.0.0",
"@types/jest": "^30.0.0",
"codemirror": "^6.0.2",
"idb-keyval": "^6.2.2",
"markdown-it": "^14.1.1",

View File

@@ -7,11 +7,11 @@ parameters:
- app
# The level 8 is the highest level
level: 4
level: 3
phpVersion:
min: 80200
max: 80500
max: 80400
bootstrapFiles:
- bootstrap/phpstan.php

View File

@@ -20,12 +20,7 @@
<h1 class="list-heading">{{ trans('entities.books_sort') }}</h1>
<div class="flex-container-row gap-m wrap mb-m">
<div class="flex min-width-s">
<p class="text-muted mb-none">{{ trans('entities.books_sort_desc') }}</p>
@if(!userCan(\BookStack\Permissions\Permission::SettingsManage))
<p class="text-muted mb-none mt-s small">{{ trans('entities.books_sort_auto_sort_creation_hint') }}</p>
@endif
</div>
<p class="text-muted flex min-width-s mb-none">{{ trans('entities.books_sort_desc') }}</p>
<div class="min-width-s">
@php
$autoSortVal = intval(old('auto-sort') ?? $book->sort_rule_id ?? 0);
@@ -46,11 +41,6 @@
</option>
@endforeach
</select>
@if(userCan(\BookStack\Permissions\Permission::SettingsManage))
<p class="small">
<a href="{{ url('/settings/sorting/rules/new') }}" class="text-button" target="_blank">{{ trans('settings.sort_rule_create') }}</a>
</p>
@endif
</div>
</div>

View File

@@ -38,9 +38,9 @@
<div>
<label for="setting-sorting-book-default"
class="setting-list-label">{{ trans('settings.sorting_book_default') }}</label>
<p class="small mb-s">{{ trans('settings.sorting_book_default_desc') }}</p>
<p class="small">{{ trans('settings.sorting_book_default_desc') }}</p>
</div>
<div class="pt-s">
<div>
<select id="setting-sorting-book-default" name="setting-sorting-book-default"
@if($errors->has('setting-sorting-book-default')) class="neg" @endif>
<option value="0" @if(intval(setting('sorting-book-default', '0')) === 0) selected @endif>
@@ -54,9 +54,6 @@
</option>
@endforeach
</select>
<p class="small">
<a href="{{ url('/settings/sorting/rules/new') }}" class="text-button" target="_blank">{{ trans('settings.sort_rule_create') }}</a>
</p>
</div>
</div>

View File

@@ -106,7 +106,6 @@ class SearchApiTest extends TestCase
$this->permissions->setEntityPermissions($page, ['view'], [$editor->roles()->first()]);
$resp = $this->getJson($this->baseEndpoint . '?query=superextrauniquevalue');
$resp->assertOk();
$resp->assertJsonPath('data.0.id', $page->id);
$resp->assertJsonPath('data.0.book.name', $book->name);
$resp->assertJsonMissingPath('data.0.chapter');

View File

@@ -2,7 +2,6 @@
namespace Tests\Commands;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Bookshelf;
use Tests\TestCase;
@@ -62,21 +61,4 @@ class CopyShelfPermissionsCommandTest extends TestCase
'view' => true, 'update' => true, 'create' => false, 'delete' => false,
]);
}
public function test_copy_shelf_permissions_command_using_slug_without_interaction()
{
$shelf = $this->entities->shelfHasBooks();
$editorRole = $this->users->editor()->roles()->first();
/** @var Book $child */
$child = $shelf->books()->first();
$child->shelves()->where('id', '!=', $shelf->id)->delete();
$this->assertFalse($child->hasPermissions());
$this->permissions->setEntityPermissions($shelf, ['view', 'update'], [$editorRole]);
$this->artisan('bookstack:copy-shelf-permissions --all --no-interaction');
$child->refresh();
$this->assertTrue($child->hasPermissions(), 'Child book should now be restricted');
}
}

View File

@@ -96,44 +96,18 @@ class InstallModuleCommandTest extends TestCase
});
}
public function test_remote_module_install_prompts_on_following_redirects_to_different_origin()
public function test_remote_module_install_does_not_follow_redirects_to_different_origin()
{
$this->usingThemeFolder(function () {
$zip = $this->getModuleZipPath();
$http = $this->mockHttpClient([
new Response(302, ['Location' => 'http://example.com/a-test-module.zip']),
new Response(301, ['Location' => 'https://a.example.com:8080/a-test-module.zip']),
new Response(200, ['Content-Length' => filesize($zip)], file_get_contents($zip))
]);
$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
->expectsConfirmation('Are you sure you trust this source?', 'yes')
->expectsOutput('The download URL is redirecting to a different site: http://example.com')
->expectsConfirmation('Do you trust downloading the module from this site?', 'yes')
->expectsOutput('The download URL is redirecting to a different site: https://a.example.com:8080')
->expectsConfirmation('Do you trust downloading the module from this site?', 'yes')
->assertExitCode(0);
$this->assertEquals(3, $http->requestCount());
$this->assertEquals('https', $http->requestAt(0)->getUri()->getScheme());
$this->assertEquals('http', $http->requestAt(1)->getUri()->getScheme());
$this->assertEquals('a.example.com', $http->requestAt(2)->getUri()->getHost());
});
}
public function test_remote_module_install_redirect_origin_prompt_rejection()
{
$this->usingThemeFolder(function () {
$http = $this->mockHttpClient([
new Response(302, ['Location' => 'http://example.com/a-test-module.zip']),
new Response(301, ['Location' => 'https://a.example.com:8080/a-test-module.zip']),
]);
$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
->expectsConfirmation('Are you sure you trust this source?', 'yes')
->expectsOutput('The download URL is redirecting to a different site: http://example.com')
->expectsConfirmation('Do you trust downloading the module from this site?', 'no')
->assertExitCode(1);
$this->assertEquals(1, $http->requestCount());
@@ -141,26 +115,6 @@ class InstallModuleCommandTest extends TestCase
});
}
public function test_remote_module_install_has_redirect_limit()
{
$this->usingThemeFolder(function () {
$http = $this->mockHttpClient([
new Response(302, ['Location' => 'https://example.com/a-test-module.zip']),
new Response(302, ['Location' => 'https://example.com/b-test-module.zip']),
new Response(302, ['Location' => 'https://example.com/c-test-module.zip']),
new Response(302, ['Location' => 'https://example.com/d-test-module.zip']),
]);
$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
->expectsConfirmation('Are you sure you trust this source?', 'yes')
->expectsOutput('ERROR: Failed to download module from https://example.com/test-module.zip')
->assertExitCode(1);
$this->assertEquals(4, $http->requestCount());
$this->assertEquals('/c-test-module.zip', $http->requestAt(3)->getUri()->getPath());
});
}
public function test_remote_module_install_download_failures_are_announced_to_user()
{
$this->usingThemeFolder(function () {
@@ -221,52 +175,6 @@ class InstallModuleCommandTest extends TestCase
->assertExitCode(1);
}
public function test_module_zip_when_files_in_nested_directory()
{
$this->usingThemeFolder(function ($themeFolder) {
$zip = new ZipArchive();
$zipFile = tempnam(sys_get_temp_dir(), 'bs-test-module');
$zip->open($zipFile, ZipArchive::CREATE);
$zip->addEmptyDir('mod');
$zip->addFromString('mod/bookstack-module.json', json_encode($metadata ?? [
'name' => 'Test Module',
'description' => 'A test module for BookStack',
'version' => '1.0.0',
]));
$zip->addFromString('mod/functions.php', '<?php $a = "cat";');
$zip->addEmptyDir('mod/a');
$zip->addFromString('mod/a/cat.txt', 'Meow');
$zip->close();
$this->artisan('bookstack:install-module', ['location' => $zipFile])
->expectsConfirmation('Are you sure you want to install this module?', 'yes')
->assertExitCode(0);
$modulePath = glob(theme_path('modules/*'), GLOB_ONLYDIR)[0];
$this->assertFileExists($modulePath . '/a/cat.txt');
$contents = file_get_contents($modulePath . '/a/cat.txt');
$this->assertEquals('Meow', $contents);
});
}
public function test_module_install_negates_zip_slip()
{
$this->usingThemeFolder(function () {
$zip = $this->getModuleZipPath(null, [
'../parent.txt' => str_repeat('dog', 10)
]);
$expectedInstallPath = theme_path('modules/test-module');
$this->artisan('bookstack:install-module', ['location' => $zip])
->expectsConfirmation('Are you sure you want to install this module?', 'yes')
->expectsOutput("ERROR: Failed to install module with error: Failed to load extract files from module ZIP with error: Bad file path found in module ZIP file: ../parent.txt")
->assertExitCode(1);
$this->assertDirectoryDoesNotExist($expectedInstallPath);
});
}
public function test_local_module_install_without_active_theme_can_setup_theme_folder()
{
$zip = $this->getModuleZipPath();

View File

@@ -136,17 +136,21 @@ class EntitySearchTest extends TestCase
$page->tags()->saveMany([new Tag(['name' => 'DonkCount', 'value' => '500'])]);
$page->created_by = $this->users->admin()->id;
$page->save();
$otherPage = $this->entities->newPage(['name' => 'A different page in negation tests', 'html' => '<p>A different page in negation tests</p>']);
$editor = $this->users->editor();
$this->actingAs($editor);
$exactSearch = $this->get('/search?term=' . urlencode('negation -"tortoise"'));
$exactSearch->assertStatus(200)->assertDontSeeText($page->name);
$exactSearch->assertSeeText($otherPage->name);
$tagSearchA = $this->get('/search?term=' . urlencode('negation [DonkCount=500]'));
$tagSearchA->assertStatus(200)->assertSeeText($page->name);
$tagSearchA->assertDontSeeText($otherPage->name);
$tagSearchB = $this->get('/search?term=' . urlencode('negation -[DonkCount=500]'));
$tagSearchB->assertStatus(200)->assertDontSeeText($page->name);
$tagSearchB->assertSeeText($otherPage->name);
$filterSearchA = $this->get('/search?term=' . urlencode('negation -{created_by:me}'));
$filterSearchA->assertStatus(200)->assertSeeText($page->name);

View File

@@ -271,21 +271,6 @@ class BookSortTest extends TestCase
$this->withHtml($resp)->assertElementExists('select[name="auto-sort"] option[value="' . $sort->id . '"]');
}
public function test_auto_sort_rule_create_hint_shown_on_sort_page()
{
$book = $this->entities->book();
$hintText = 'Auto sort option rules can be created in the "Lists & Sorting" settings area by a user with the relevant permissions.';
// Admin users see link for creating new rule
$resp = $this->asAdmin()->get($book->getUrl('/sort'));
$this->withHtml($resp)->assertLinkExists(url('/settings/sorting/rules/new'), 'Create Sort Rule');
$resp->assertDontSee($hintText);
// Non-admin users see help text
$resp = $this->asEditor()->get($book->getUrl('/sort'));
$resp->assertSee($hintText);
}
public function test_auto_sort_option_submit_saves_to_book()
{
$sort = SortRule::factory()->create();

View File

@@ -1,62 +0,0 @@
<?php
namespace Tests\Unit;
use BookStack\Exceptions\HttpFetchException;
use BookStack\Util\SsrUrlValidator;
use Tests\TestCase;
class SsrUrlValidatorTest extends TestCase
{
public function test_allowed()
{
$testMap = [
// Single values
['config' => '', 'url' => '', 'result' => false],
['config' => '', 'url' => 'https://example.com', 'result' => false],
['config' => ' ', 'url' => 'https://example.com', 'result' => false],
['config' => '*', 'url' => '', 'result' => false],
['config' => '*', 'url' => 'https://example.com', 'result' => true],
['config' => 'https://*', 'url' => 'https://example.com', 'result' => true],
['config' => 'http://*', 'url' => 'https://example.com', 'result' => false],
['config' => 'https://*example.com', 'url' => 'https://example.com', 'result' => true],
['config' => 'https://*ample.com', 'url' => 'https://example.com', 'result' => true],
['config' => 'https://*.example.com', 'url' => 'https://example.com', 'result' => false],
['config' => 'https://*.example.com', 'url' => 'https://test.example.com', 'result' => true],
['config' => '*//example.com', 'url' => 'https://example.com', 'result' => true],
['config' => '*//example.com', 'url' => 'http://example.com', 'result' => true],
['config' => '*//example.co', 'url' => 'http://example.co.uk', 'result' => false],
['config' => '*//example.co/bookstack', 'url' => 'https://example.co/bookstack/a/path', 'result' => true],
['config' => '*//example.co*', 'url' => 'https://example.co.uk/bookstack/a/path', 'result' => true],
['config' => 'https://example.com', 'url' => 'https://example.com/a/b/c?test=cat', 'result' => true],
['config' => 'https://example.com', 'url' => 'https://example.co.uk', 'result' => false],
// Escapes
['config' => 'https://(.*?).com', 'url' => 'https://example.com', 'result' => false],
['config' => 'https://example.com', 'url' => 'https://example.co.uk#https://example.com', 'result' => false],
// Multi values
['config' => '*//example.org *//example.com', 'url' => 'https://example.com', 'result' => true],
['config' => '*//example.org *//example.com', 'url' => 'https://example.com/a/b/c?test=cat#hello', 'result' => true],
['config' => '*.example.org *.example.com', 'url' => 'https://example.co.uk', 'result' => false],
['config' => ' *.example.org *.example.com ', 'url' => 'https://example.co.uk', 'result' => false],
['config' => '* *.example.com', 'url' => 'https://example.co.uk', 'result' => true],
['config' => '*//example.org *//example.com *//example.co.uk', 'url' => 'https://example.co.uk', 'result' => true],
['config' => '*//example.org *//example.com *//example.co.uk', 'url' => 'https://example.net', 'result' => false],
];
foreach ($testMap as $test) {
$result = (new SsrUrlValidator($test['config']))->allowed($test['url']);
$this->assertEquals($test['result'], $result, "Failed asserting url '{$test['url']}' with config '{$test['config']}' results " . ($test['result'] ? 'true' : 'false'));
}
}
public function test_enssure_allowed()
{
$result = (new SsrUrlValidator('https://example.com'))->ensureAllowed('https://example.com');
$this->assertNull($result);
$this->expectException(HttpFetchException::class);
(new SsrUrlValidator('https://example.com'))->ensureAllowed('https://test.example.com');
}
}

View File

@@ -5,6 +5,7 @@ namespace Tests\Uploads;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Repos\PageRepo;
use BookStack\Entities\Tools\TrashCan;
use BookStack\Permissions\Permission;
use BookStack\Uploads\Attachment;
use Tests\TestCase;
@@ -206,6 +207,21 @@ class AttachmentTest extends TestCase
$this->files->deleteAllAttachmentFiles();
}
public function test_attachment_deletion_requires_page_access()
{
$page = $this->entities->page();
$attachment = Attachment::factory()->create(['uploaded_to' => $page->id]);
$editor = $this->users->editor();
$this->permissions->disableEntityInheritedPermissions($page);
$this->permissions->grantUserRolePermissions($editor, [Permission::AttachmentDeleteAll]);
$resp = $this->actingAs($editor)->delete($attachment->getUrl());
$resp->assertNotFound();
$this->assertDatabaseHas('attachments', ['id' => $attachment->id]);
}
public function test_attachment_access_without_permission_shows_404()
{
$admin = $this->users->admin();

View File

@@ -0,0 +1,142 @@
<?php
namespace Tests\Util;
use BookStack\Exceptions\HttpFetchException;
use BookStack\Util\SsrUrlValidator;
use Tests\TestCase;
class SsrUrlValidatorTest extends TestCase
{
public function test_is_uses_app_config_by_default()
{
config()->set([
'app.ssr_hosts' => 'https://donkey.example.com',
]);
$validator = new SsrUrlValidator();
$this->assertTrue($validator->allowed('https://donkey.example.com'));
$this->assertFalse($validator->allowed('https://monkey.example.com'));
}
public function test_config_string_can_be_passed_in_constructor()
{
config()->set([
'app.ssr_hosts' => 'https://donkey.example.com',
]);
$validator = new SsrUrlValidator('https://monkey.example.com');
$this->assertFalse($validator->allowed('https://donkey.example.com'));
$this->assertTrue($validator->allowed('https://monkey.example.com'));
}
public function test_config_string_can_include_multiple_space_seperated_values()
{
$validator = new SsrUrlValidator('https://monkey.example.com https://cat.example.com');
$this->assertFalse($validator->allowed('https://donkey.example.com'));
$this->assertTrue($validator->allowed('https://monkey.example.com'));
$this->assertTrue($validator->allowed('https://cat.example.com'));
}
public function test_ensure_allowed_throws_if_not_allowed()
{
$validator = new SsrUrlValidator('https://monkey.example.com');
$this->assertNull($validator->ensureAllowed('https://monkey.example.com'));
$this->assertThrows(function () use ($validator) {
$validator->ensureAllowed('https://donkey.example.com');
}, HttpFetchException::class, 'The URL does not match the configured allowed SSR hosts');
}
public function test_basic_url_matching()
{
$tests = [
// Single values
['config' => '', 'url' => '', 'result' => false],
['config' => '', 'url' => 'https://example.com', 'result' => false],
['config' => ' ', 'url' => 'https://example.com', 'result' => false],
['config' => '*', 'url' => '', 'result' => false],
['config' => '*', 'url' => 'https://example.com', 'result' => true],
['config' => 'https://*', 'url' => 'https://example.com', 'result' => true],
['config' => 'http://*', 'url' => 'https://example.com', 'result' => false],
['config' => 'https://*example.com', 'url' => 'https://example.com', 'result' => true],
['config' => 'https://*ample.com', 'url' => 'https://example.com', 'result' => true],
['config' => 'https://*.example.com', 'url' => 'https://example.com', 'result' => false],
['config' => 'https://*.example.com', 'url' => 'https://test.example.com', 'result' => true],
['config' => '*//example.com', 'url' => 'https://example.com', 'result' => true],
['config' => '*//example.com', 'url' => 'http://example.com', 'result' => true],
['config' => '*//example.co', 'url' => 'http://example.co.uk', 'result' => false],
['config' => '*//example.co/bookstack', 'url' => 'https://example.co/bookstack/a/path', 'result' => true],
['config' => '*//example.co*', 'url' => 'https://example.co.uk/bookstack/a/path', 'result' => true],
['config' => 'https://example.com', 'url' => 'https://example.com/a/b/c?test=cat', 'result' => true],
['config' => 'https://example.com', 'url' => 'https://example.co.uk', 'result' => false],
// Escapes
['config' => 'https://(.*?).com', 'url' => 'https://example.com', 'result' => false],
['config' => 'https://example.com', 'url' => 'https://example.co.uk#https://example.com', 'result' => false],
// Multi values
['config' => '*//example.org *//example.com', 'url' => 'https://example.com', 'result' => true],
['config' => '*//example.org *//example.com', 'url' => 'https://example.com/a/b/c?test=cat#hello', 'result' => true],
['config' => '*.example.org *.example.com', 'url' => 'https://example.co.uk', 'result' => false],
['config' => ' *.example.org *.example.com ', 'url' => 'https://example.co.uk', 'result' => false],
['config' => '* *.example.com', 'url' => 'https://example.co.uk', 'result' => true],
['config' => '*//example.org *//example.com *//example.co.uk', 'url' => 'https://example.co.uk', 'result' => true],
['config' => '*//example.org *//example.com *//example.co.uk', 'url' => 'https://example.net', 'result' => false],
// Further tests
['config' => 'https://monkey.example.com', 'url' => 'https://monkey.example.com/a/b', 'result' => true,],
['config' => 'https://monkey.example.com', 'url' => 'https://monkey.example.com/a/b?a=b#ab', 'result' => true,],
['config' => 'https://monkey.example.com', 'url' => 'https://monkey.example.com:8080/a', 'result' => false,],
['config' => '*', 'url' => 'https://a.example.com', 'result' => true,],
['config' => 'https://monkey.example.com', 'url' => 'http://monkey.example.com/a/b?a=b#ab', 'result' => false,],
['config' => 'https://monkey.example.com', 'url' => 'https://beans.monkey.example.com/a/b?a=b#ab', 'result' => false,],
['config' => 'https://*monkey.example.com', 'url' => 'https://amonkey.example.com/a/b?a=b#ab', 'result' => true,],
['config' => 'https://*monkey.example.com', 'url' => 'https://donkey.example.com/a/b/monkey.example.com/b?a=b#ab', 'result' => false,],
['config' => 'https://monkey.example.com', 'url' => 'https://example.com/monkey.example.com/b?a=monkey.example.com#monkey.example.com', 'result' => false,],
['config' => 'https://*.example.com', 'url' => 'https://a.b.example.com/a/b', 'result' => true,],
['config' => 'https://*.example.com', 'url' => 'https://a.b.example.a.com/a/b', 'result' => false,],
['config' => 'https://*.example.com', 'url' => 'https://a.com/a/b?val=a.example.com', 'result' => false,],
['config' => 'https://*.example.com', 'url' => 'https://a.com/a/b#example.com', 'result' => false,],
['config' => 'https://a.*.example.com', 'url' => 'https://a.b.c.example.com/c/d', 'result' => true,],
['config' => 'https://example.com/webhooks/', 'url' => 'https://example.com/webhooks/beans', 'result' => true,],
['config' => 'https://example.com/webhooks/', 'url' => 'https://example.com/a/webhooks/', 'result' => false,],
['config' => 'https://example.com:8080', 'url' => 'https://example.com/a/b', 'result' => false,],
['config' => 'https://example.com:8080', 'url' => 'https://example.com:8080/a/b', 'result' => true,],
['config' => 'https://example.com/*', 'url' => 'https://example.com:8080/a/b', 'result' => false,],
];
foreach ($tests as $testCase) {
$validator = new SsrUrlValidator($testCase['config']);
$result = $validator->allowed($testCase['url']);
$this->assertEquals($testCase['result'], $result, "Failed asserting expected result for config {$testCase['config']} and test value {$testCase['url']}");
}
}
public function test_wildcard_does_not_match_userinfo_data_but_still_allows_it()
{
$validator = new SsrUrlValidator('https://*monkey.example.com');
$this->assertFalse($validator->allowed('https://monkey.example.com@a.example.com'));
$validator = new SsrUrlValidator('https://monkey.example.com*');
$this->assertFalse($validator->allowed('https://monkey.example.com@a.example.com'));
$this->assertFalse($validator->allowed('https://monkey.example.com:monkey.example.com@a.example.com'));
$validator = new SsrUrlValidator('https://monkey.example.com');
$this->assertTrue($validator->allowed('https://a:b@monkey.example.com'));
}
public function test_percent_encoded_slashes_in_host_are_rejected()
{
$validator = new SsrUrlValidator('*');
$this->assertFalse($validator->allowed('https://cat.example.com%2Fa/b'));
$this->assertFalse($validator->allowed('https://cat.example.com%2fa/b'));
$this->assertFalse($validator->allowed('https://cat%2f.example.com/a/b'));
$this->assertFalse($validator->allowed('https://cat.exa%2Fmple.com'));
}
}

View File

@@ -2,16 +2,15 @@
"include": ["resources/js/**/*"],
"exclude": ["resources/js/wysiwyg/lexical/yjs/*"],
"compilerOptions": {
"target": "es2023",
"module": "esnext",
"moduleResolution": "bundler",
"target": "es2022",
"module": "commonjs",
"rootDir": "./resources/js/",
"types": ["jest", "node"],
"baseUrl": "./",
"paths": {
"@icons/*": ["./resources/icons/*"],
"lexical": ["./resources/js/wysiwyg/lexical/core/index.ts"],
"lexical/*": ["./resources/js/wysiwyg/lexical/core/*"],
"@lexical/*": ["./resources/js/wysiwyg/lexical/*"]
"@icons/*": ["resources/icons/*"],
"lexical": ["resources/js/wysiwyg/lexical/core/index.ts"],
"lexical/*": ["resources/js/wysiwyg/lexical/core/*"],
"@lexical/*": ["resources/js/wysiwyg/lexical/*"]
},
"resolveJsonModule": true,
"allowJs": true,