Compare commits

..

1 Commits

Author SHA1 Message Date
Dan Brown
c01217827c MFA: Started exploring hardware key support 2026-06-01 13:08:58 +01:00
46 changed files with 1310 additions and 152 deletions

View File

@@ -0,0 +1,133 @@
<?php
namespace BookStack\Access\Controllers;
use BookStack\Access\LoginService;
use BookStack\Access\Mfa\BackupCodeService;
use BookStack\Access\Mfa\MfaSession;
use BookStack\Access\Mfa\MfaValue;
use BookStack\Access\Mfa\MfaVerificationLimiter;
use BookStack\Activity\ActivityType;
use BookStack\Exceptions\NotFoundException;
use BookStack\Http\Controller;
use Cose\Algorithms;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
use Webauthn\AttestationStatement\NoneAttestationStatementSupport;
use Webauthn\AuthenticatorSelectionCriteria;
use Webauthn\Denormalizer\WebauthnSerializerFactory;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialOptions;
use Webauthn\PublicKeyCredentialParameters;
use Webauthn\PublicKeyCredentialRpEntity;
use Webauthn\PublicKeyCredentialUserEntity;
class MfaHardwareKeyController extends Controller
{
use HandlesPartialLogins;
protected const SETUP_SECRET_SESSION_KEY = 'mfa-setup-hardware-key-secret';
public function __construct(
protected MfaVerificationLimiter $limiter,
) {
}
/**
* Show a view that allows configuration of a hardware key.
*/
public function generate(BackupCodeService $codeService)
{
$domain = parse_url(url('/'), PHP_URL_HOST);
$rpEntity = PublicKeyCredentialRpEntity::create(
setting('app-name'),
$domain,
);
$user = $this->currentOrLastAttemptedUser();
// TODO - Ensure user ID is somewhat long and random
// See: https://webauthn-doc.spomky-labs.com/prerequisites/user-entity
// Maybe hash of (app-id from settings + user id)
// Or maybe a UUID/random_string which we connect via DB entry?
$userEntity = PublicKeyCredentialUserEntity::create(
$user->slug,
$user->id,
$user->name,
);
$publicKeyCredentialParametersList = [
PublicKeyCredentialParameters::create('public-key', Algorithms::COSE_ALGORITHM_ES256K), // More interesting algorithm
PublicKeyCredentialParameters::create('public-key', Algorithms::COSE_ALGORITHM_ES256), // ||
PublicKeyCredentialParameters::create('public-key', Algorithms::COSE_ALGORITHM_RS256), // ||
PublicKeyCredentialParameters::create('public-key', Algorithms::COSE_ALGORITHM_PS256), // \/
PublicKeyCredentialParameters::create('public-key', Algorithms::COSE_ALGORITHM_ED256), // Less interesting algorithm
];
$credentialOptions = PublicKeyCredentialCreationOptions::create(
$rpEntity,
$userEntity,
random_bytes(32),
$publicKeyCredentialParametersList,
hints: [
PublicKeyCredentialOptions::HINT_SECURITY_KEY,
],
timeout: 60000, // 1 minute
authenticatorSelection: AuthenticatorSelectionCriteria::create(
userVerification: AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED,
)
);
$attestationStatementSupportManager = AttestationStatementSupportManager::create();
$attestationStatementSupportManager->add(NoneAttestationStatementSupport::create());
$factory = new WebauthnSerializerFactory($attestationStatementSupportManager);
$serializer = $factory->create();
$jsonOptions = $serializer->serialize(
$credentialOptions,
'json',
[
AbstractObjectNormalizer::SKIP_NULL_VALUES => true,
JsonEncode::OPTIONS => JSON_THROW_ON_ERROR,
]
);
// TODO - Change
$this->setPageTitle(trans('auth.mfa_gen_hardware_key_title'));
return view('mfa.hardware-key-generate', [
'options' => $jsonOptions,
]);
}
/**
* Confirm the setup of a hardware key, storing the key value against the user.
*
* @throws Exception
*/
public function confirm()
{
return redirect('/mfa/setup');
}
/**
* Verify the MFA method submission on check.
*
* @throws NotFoundException
* @throws ValidationException
*/
public function verify(Request $request, MfaSession $mfaSession, LoginService $loginService)
{
$user = $this->currentOrLastAttemptedUser();
$this->limiter->incrementAttempts($user, $request);
if ($this->limiter->hasHitLimit($user, $request)) {
$this->clearLastAttemptedUser();
$this->limiter->throwException();
}
}
}

View File

@@ -42,7 +42,7 @@ class ExternalBaseUserProvider implements UserProvider
/**
* Retrieve a user by the given credentials.
*/
public function retrieveByCredentials(array $credentials): ?User
public function retrieveByCredentials(array $credentials): ?Authenticatable
{
return User::query()
->where('external_auth_id', $credentials['external_auth_id'])

View File

@@ -50,12 +50,8 @@ class ExternalBaseSessionGuard implements StatefulGuard
/**
* Create a new authentication guard.
*/
public function __construct(
string $name,
UserProvider $provider,
Session $session,
RegistrationService $registrationService
) {
public function __construct(string $name, UserProvider $provider, Session $session, RegistrationService $registrationService)
{
$this->name = $name;
$this->session = $session;
$this->provider = $provider;

View File

@@ -83,10 +83,6 @@ class LdapSessionGuard extends ExternalBaseSessionGuard
}
}
if (!($user instanceof User)) {
throw new LoginAttemptException('Could not find or create a user for LDAP login.');
}
// Sync LDAP groups if required
if ($this->ldapService->shouldSyncGroups()) {
$this->ldapService->syncGroups($user, $username);

View File

@@ -23,13 +23,14 @@ class MfaValue extends Model
const METHOD_TOTP = 'totp';
const METHOD_BACKUP_CODES = 'backup_codes';
const METHOD_HARDWARE_KEY = 'hardware_key';
/**
* Get all the MFA methods available.
*/
public static function allMethods(): array
{
return [self::METHOD_TOTP, self::METHOD_BACKUP_CODES];
return [self::METHOD_TOTP, self::METHOD_BACKUP_CODES, self::METHOD_HARDWARE_KEY];
}
/**

View File

@@ -131,6 +131,8 @@ class OidcJwtWithClaims implements ProvidesClaims
}
}, $this->keys);
$parsedKeys = array_filter($parsedKeys);
$contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
/** @var OidcJwtSigningKey $parsedKey */
foreach ($parsedKeys as $parsedKey) {

View File

@@ -80,7 +80,6 @@ class OidcService
$provider->setPkceCode($pkceCode);
// Try to exchange authorization code for access token
/** @var OidcAccessToken $accessToken */
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $authorizationCode,
]);

View File

@@ -11,7 +11,6 @@ use BookStack\Entities\Tools\MixedEntityListLoader;
use BookStack\Permissions\PermissionApplicator;
use BookStack\Users\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\Relation;
@@ -28,7 +27,6 @@ class ActivityQueries
*/
public function latest(int $count = 20, int $page = 0): array
{
/** @var Collection<int, Activity> $activityList */
$activityList = $this->permissions
->restrictEntityRelationQuery(Activity::query(), 'activities', 'loggable_id', 'loggable_type')
->orderBy('created_at', 'desc')
@@ -85,7 +83,6 @@ class ActivityQueries
*/
public function userActivity(User $user, int $count = 20, int $page = 0): array
{
/** @var Collection<int, Activity> $activityList */
$activityList = $this->permissions
->restrictEntityRelationQuery(Activity::query(), 'activities', 'loggable_id', 'loggable_type')
->orderBy('created_at', 'desc')

View File

@@ -3,7 +3,6 @@
namespace BookStack\Activity\Models;
use BookStack\App\Model;
use BookStack\Entities\Models\Page;
use BookStack\Permissions\Models\JointPermission;
use BookStack\Permissions\PermissionApplicator;
use BookStack\Users\Models\HasCreatorAndUpdater;
@@ -41,9 +40,6 @@ class Comment extends Model implements Loggable, OwnableInterface
/**
* Get the entity that this comment belongs to.
* It's only pages right now hence the typing below.
* Would need a deeper audit if that changes as many areas assume this is always a page.
* @return MorphTo<Page, $this>
*/
public function entity(): MorphTo
{
@@ -59,9 +55,7 @@ class Comment extends Model implements Loggable, OwnableInterface
// Ultimately, we could just align the method name to 'commentable' but that would be a potential
// breaking change and not really worthwhile in a patch due to the risk of creating extra problems.
/** @var MorphTo<Page, $this> $relation */
$relation = $this->morphTo(null, 'commentable_type', 'commentable_id');
return $relation;
return $this->morphTo(null, 'commentable_type', 'commentable_id');
}
/**

View File

@@ -73,17 +73,13 @@ class WebhookFormatter
// Load entity owner, creator, updater details
$this->addModelFormatter(
fn ($event, $model) => ($model instanceof Entity),
function ($model) {
$model->load(['ownedBy', 'createdBy', 'updatedBy']);
}
fn ($model) => $model->load(['ownedBy', 'createdBy', 'updatedBy'])
);
// Load revision detail for page update and create events
$this->addModelFormatter(
fn ($event, $model) => ($model instanceof Page && ($event === ActivityType::PAGE_CREATE || $event === ActivityType::PAGE_UPDATE)),
function ($model) {
$model->load('currentRevision');
}
fn ($model) => $model->load('currentRevision')
);
}

View File

@@ -138,8 +138,8 @@ class ApiDocsGenerator
return $validation;
}
if (is_object($validation) && $validation instanceof \Stringable) {
return $validation->__toString();
if (is_object($validation) && method_exists($validation, '__toString')) {
return strval($validation);
}
if ($validation instanceof Password) {

View File

@@ -7,7 +7,6 @@ use BookStack\Theming\ThemeService;
use BookStack\Theming\ThemeViews;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\FileViewFinder;
class ThemeServiceProvider extends ServiceProvider
{
@@ -28,11 +27,7 @@ class ThemeServiceProvider extends ServiceProvider
// Boot up the theme system
$themeService = $this->app->make(ThemeService::class);
$viewFactory = $this->app->make('view');
$viewFinder = $viewFactory->getFinder();
if (!($viewFinder instanceof FileViewFinder)) {
throw new \Exception('Only the file view finder is supported for the theme system');
}
$themeViews = new ThemeViews($viewFinder);
$themeViews = new ThemeViews($viewFactory->getFinder());
// Use a custom include so that we can insert theme views before/after includes.
// This is done, even if no theme is active, so that view caching does not create problems

View File

@@ -6,7 +6,6 @@ use BookStack\Facades\Theme;
use BookStack\Permissions\Permission;
use BookStack\Permissions\PermissionApplicator;
use BookStack\Settings\SettingService;
use BookStack\Users\Models\OwnableInterface;
use BookStack\Users\Models\User;
/**
@@ -41,7 +40,7 @@ function user(): User
* Check if the current user has a permission. If an ownable element
* is passed in the jointPermissions are checked against that particular item.
*/
function userCan(string|Permission $permission, (Model&OwnableInterface)|null $ownable = null): bool
function userCan(string|Permission $permission, ?Model $ownable = null): bool
{
if (is_null($ownable)) {
return user()->can($permission);

View File

@@ -1,7 +1,5 @@
<?php
declare(strict_types=1);
namespace BookStack\Entities\Controllers;
use BookStack\Activity\Tools\CommentTree;
@@ -12,9 +10,7 @@ use BookStack\Exceptions\PermissionsException;
use BookStack\Http\ApiController;
use BookStack\Permissions\Permission;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class PageApiController extends ApiController
{
@@ -49,7 +45,7 @@ class PageApiController extends ApiController
/**
* Get a listing of pages visible to the user.
*/
public function list(): JsonResponse
public function list()
{
$pages = $this->queries->visibleForList()
->addSelect(['created_by', 'updated_by', 'revision_count', 'editor']);
@@ -73,7 +69,7 @@ class PageApiController extends ApiController
* Any images included via base64 data URIs will be extracted and saved as gallery
* images against the page during upload.
*/
public function create(Request $request): JsonResponse
public function create(Request $request)
{
$this->validate($request, $this->rules['create']);
@@ -106,9 +102,9 @@ class PageApiController extends ApiController
* Comments for the page are provided in a tree-structure representing the hierarchy of top-level
* comments and replies, for both archived and active comments.
*/
public function read(string $id): JsonResponse
public function read(string $id)
{
$page = $this->queries->findVisibleByIdOrFail(intval($id));
$page = $this->queries->findVisibleByIdOrFail($id);
$page = $page->forJsonDisplay();
$commentTree = (new CommentTree($page));
@@ -128,11 +124,11 @@ class PageApiController extends ApiController
* Providing a 'book_id' or 'chapter_id' property will essentially move
* the page into that parent element if you have permissions to do so.
*/
public function update(Request $request, string $id): JsonResponse
public function update(Request $request, string $id)
{
$requestData = $this->validate($request, $this->rules['update']);
$page = $this->queries->findVisibleByIdOrFail(intval($id));
$page = $this->queries->findVisibleByIdOrFail($id);
$this->checkOwnablePermission(Permission::PageUpdate, $page);
$parent = null;
@@ -165,9 +161,9 @@ class PageApiController extends ApiController
* Delete a page.
* This will typically send the page to the recycle bin.
*/
public function delete(string $id): Response
public function delete(string $id)
{
$page = $this->queries->findVisibleByIdOrFail(intval($id));
$page = $this->queries->findVisibleByIdOrFail($id);
$this->checkOwnablePermission(Permission::PageDelete, $page);
$this->pageRepo->destroy($page);

View File

@@ -25,7 +25,6 @@ use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
use Exception;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Throwable;
@@ -359,8 +358,8 @@ class PageController extends Controller
*/
public function showRecentlyUpdated()
{
$visibleBelongsScope = function (Relation $relation): void {
$relation->scopes('visible');
$visibleBelongsScope = function (BelongsTo $query) {
$query->scopes('visible');
};
$pages = $this->queries->visibleForList()

View File

@@ -177,7 +177,7 @@ class PageRevisionController extends Controller
*/
public function destroyUserDraft(string $pageId)
{
$page = $this->pageQueries->findVisibleByIdOrFail(intval($pageId));
$page = $this->pageQueries->findVisibleByIdOrFail($pageId);
$this->revisionRepo->deleteDraftsForCurrentUser($page);
return response('', 200);

View File

@@ -20,10 +20,10 @@ use Illuminate\Support\Collection;
* @property ?int $image_id
* @property ?int $default_template_id
* @property ?int $sort_rule_id
* @property \Illuminate\Database\Eloquent\Collection<int, Chapter> $chapters
* @property \Illuminate\Database\Eloquent\Collection<int, Page> $pages
* @property \Illuminate\Database\Eloquent\Collection<int, Page> $directPages
* @property \Illuminate\Database\Eloquent\Collection<int, Bookshelf> $shelves
* @property \Illuminate\Database\Eloquent\Collection $chapters
* @property \Illuminate\Database\Eloquent\Collection $pages
* @property \Illuminate\Database\Eloquent\Collection $directPages
* @property \Illuminate\Database\Eloquent\Collection $shelves
* @property ?SortRule $sortRule
*/
class Book extends Entity implements HasDescriptionInterface, HasCoverInterface, HasDefaultTemplateInterface

View File

@@ -46,7 +46,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property int|null $created_by
* @property int|null $updated_by
* @property int|null $owned_by
* @property Collection<int, Tag> $tags
* @property Collection $tags
*
* @method static Entity|Builder visible()
* @method static Builder withLastView()

View File

@@ -24,8 +24,8 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
* @property int $revision_count
* @property string $editor
* @property Chapter|null $chapter
* @property Collection<int, Attachment> $attachments
* @property Collection<int, PageRevision> $revisions
* @property Collection $attachments
* @property Collection $revisions
* @property PageRevision $currentRevision
*/
class Page extends BookChild

View File

@@ -6,7 +6,6 @@ use BookStack\Activity\Models\View;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Tools\MixedEntityListLoader;
use BookStack\Permissions\PermissionApplicator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
@@ -21,7 +20,6 @@ class QueryPopular
public function run(int $count, int $page, array $filterModels): Collection
{
/** @var Builder<View> $query */
$query = $this->permissions
->restrictEntityRelationQuery(View::query(), 'views', 'viewable_id', 'viewable_type')
->select('*', 'viewable_id', 'viewable_type', DB::raw('SUM(views) as view_count'))

View File

@@ -5,7 +5,6 @@ namespace BookStack\Entities\Queries;
use BookStack\Activity\Models\View;
use BookStack\Entities\Tools\MixedEntityListLoader;
use BookStack\Permissions\PermissionApplicator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
class QueryRecentlyViewed
@@ -23,7 +22,6 @@ class QueryRecentlyViewed
return collect();
}
/** @var Builder<View> $query */
$query = $this->permissions->restrictEntityRelationQuery(
View::query(),
'views',

View File

@@ -5,7 +5,6 @@ namespace BookStack\Entities\Queries;
use BookStack\Activity\Models\Favourite;
use BookStack\Entities\Tools\MixedEntityListLoader;
use BookStack\Permissions\PermissionApplicator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
class QueryTopFavourites
@@ -23,7 +22,6 @@ class QueryTopFavourites
return collect();
}
/** @var Builder<Favourite> $query */
$query = $this->permissions
->restrictEntityRelationQuery(Favourite::query(), 'favourites', 'favouritable_id', 'favouritable_type')
->select('favourites.*')

View File

@@ -25,13 +25,9 @@ class CustomListItemRenderer implements NodeRendererInterface
*/
public function render(Node $node, ChildNodeRendererInterface $childRenderer)
{
if (!($node instanceof ListItem)) {
return null;
}
$listItem = $this->baseRenderer->render($node, $childRenderer);
if ($this->startsTaskListItem($node) && $listItem instanceof HtmlElement) {
if ($node instanceof ListItem && $this->startsTaskListItem($node) && $listItem instanceof HtmlElement) {
$listItem->setAttribute('class', 'task-list-item');
}

View File

@@ -421,41 +421,28 @@ class PageContent
*/
protected function headerNodesToLevelList(DOMNodeList $nodeList): array
{
$minLevel = 6;
$headerDetails = array_map(function (DOMNode $header) use (&$minLevel) {
if (!$header instanceof DOMElement) {
return null;
}
$tree = collect($nodeList)->map(function (DOMElement $header) {
$text = trim(str_replace("\xc2\xa0", ' ', $header->nodeValue));
$text = mb_substr($text, 0, 100);
if (empty($text)) {
return null;
}
$level = intval(str_replace('h', '', $header->nodeName));
if ($level < $minLevel) {
$minLevel = $level;
}
return [
'nodeName' => strtolower($header->nodeName),
'level' => $level,
'level' => intval(str_replace('h', '', $header->nodeName)),
'link' => '#' . $header->getAttribute('id'),
'text' => $text,
];
}, [...$nodeList]);
$filtered = array_values(array_filter($headerDetails));
})->filter(function ($header) {
return mb_strlen($header['text']) > 0;
});
// Shift headers if only smaller headers have been used
$levelChange = ($minLevel - 1);
foreach ($filtered as $index => $header) {
$filtered[$index]['level'] -= $levelChange;
}
$levelChange = ($tree->pluck('level')->min() - 1);
$tree = $tree->map(function ($header) use ($levelChange) {
$header['level'] -= ($levelChange);
return $filtered;
return $header;
});
return $tree->toArray();
}
}

View File

@@ -192,10 +192,10 @@ class PageIncludeParser
/**
* Get the parent paragraph of the given node, if existing.
*/
protected function getParentParagraph(DOMNode $parent): ?DOMElement
protected function getParentParagraph(DOMNode $parent): ?DOMNode
{
do {
if (strtolower($parent->nodeName) === 'p' && $parent instanceof DOMElement) {
if (strtolower($parent->nodeName) === 'p') {
return $parent;
}

View File

@@ -52,7 +52,7 @@ class SlugGenerator
{
$slug = Str::slug($name);
if ($slug === '') {
$slug = substr(md5(strval(rand(1, 500))), 0, 5);
$slug = substr(md5(rand(1, 500)), 0, 5);
}
return $slug;

View File

@@ -3,8 +3,6 @@
namespace BookStack\Exports;
use BookStack\Activity\ActivityType;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Queries\EntityQueries;
use BookStack\Exceptions\FileUploadException;
@@ -121,9 +119,6 @@ class ImportRepo
$parentModel = null;
if ($import->type === 'page' || $import->type === 'chapter') {
$parentModel = $parent ? $this->entityQueries->findVisibleByStringIdentifier($parent) : null;
if ($parentModel && !($parentModel instanceof Book || $parentModel instanceof Chapter)) {
throw new ZipImportException(['Selected parent is not a book or chapter']);
}
}
DB::beginTransaction();

View File

@@ -48,7 +48,7 @@ class ZipImportRunner
* Returns the top-level entity item which was imported.
* @throws ZipImportException
*/
public function run(Import $import, Book|Chapter|null $parent = null): Entity
public function run(Import $import, ?Entity $parent = null): Entity
{
$zipPath = $this->getZipPath($import);
$reader = new ZipExportReader($zipPath);

View File

@@ -7,7 +7,6 @@ use BookStack\App\Model;
use BookStack\Exceptions\NotifyException;
use BookStack\Facades\Activity;
use BookStack\Permissions\Permission;
use BookStack\Users\Models\OwnableInterface;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
@@ -81,7 +80,7 @@ abstract class Controller extends BaseController
/**
* Check the current user's permissions against an ownable item otherwise throw an exception.
*/
protected function checkOwnablePermission(string|Permission $permission, Model&OwnableInterface $ownable, string $redirectLocation = '/'): void
protected function checkOwnablePermission(string|Permission $permission, Model $ownable, string $redirectLocation = '/'): void
{
if (!userCan($permission, $ownable)) {
$this->showPermissionError($redirectLocation);

View File

@@ -101,7 +101,6 @@ class JointPermissionBuilder
/**
* Get a query for fetching a book with its children.
* @return Builder<Book>
*/
protected function bookFetchQuery(): Builder
{
@@ -118,11 +117,9 @@ class JointPermissionBuilder
/**
* Build joint permissions for the given book and role combinations.
* @param EloquentCollection<int, Book> $books
*/
protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false): void
{
/** @var EloquentCollection<int, Entity> $entities */
$entities = clone $books;
/** @var Book $book */

View File

@@ -2,8 +2,8 @@
namespace BookStack\References;
use BookStack\App\Model;
use BookStack\Permissions\Models\JointPermission;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;

View File

@@ -22,7 +22,6 @@ class ReferenceFetcher
*/
public function getReferencesToEntity(Entity $entity, bool $withContents = false): Collection
{
/** @var Collection<int, Reference> $references */
$references = $this->queryReferencesToEntity($entity)->get();
$this->mixedEntityListLoader->loadIntoRelations($references->all(), 'from', false, $withContents);
@@ -38,9 +37,6 @@ class ReferenceFetcher
return $this->queryReferencesToEntity($entity)->count();
}
/**
* @return Builder<Reference>
*/
protected function queryReferencesToEntity(Entity $entity): Builder
{
$baseQuery = Reference::query()

View File

@@ -4,7 +4,6 @@ namespace BookStack\Search;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\EntityTable;
use BookStack\Entities\Queries\EntityQueries;
use BookStack\Entities\Tools\EntityHydrator;
use BookStack\Permissions\PermissionApplicator;
@@ -91,8 +90,6 @@ class SearchRunner
/**
* Get a page of result data from the given query based on the provided page parameters.
* @param EloquentBuilder<EntityTable> $query
* @return Collection<Entity>
*/
protected function getPageOfDataFromQuery(EloquentBuilder $query, int $page, int $count): Collection
{
@@ -109,7 +106,6 @@ class SearchRunner
/**
* Create a search query for an entity.
* @param string[] $entityTypes
* @return EloquentBuilder<EntityTable>
*/
protected function buildQuery(SearchOptions $searchOpts, array $entityTypes): EloquentBuilder
{

View File

@@ -243,9 +243,9 @@ class SettingService
/**
* Convert a setting key into a user-specific key.
*/
protected function userKey(int $userId, string $key = ''): string
protected function userKey(string $userId, string $key = ''): string
{
return 'user:' . strval($userId) . ':' . $key;
return 'user:' . $userId . ':' . $key;
}
/**
@@ -267,7 +267,7 @@ class SettingService
/**
* Delete settings for a given user id.
*/
public function deleteUserSettings(int $userId): void
public function deleteUserSettings(string $userId): void
{
Setting::query()
->where('setting_key', 'like', $this->userKey($userId) . '%')

View File

@@ -38,35 +38,21 @@ class SortRule extends Model implements Loggable
$this->sequence = implode(',', $values);
}
/**
* @inheritDoc
*/
public function logDescriptor(): string
{
return "({$this->id}) {$this->name}";
}
/**
* Get the URL to where this rule can be managed.
*/
public function getUrl(): string
{
return url("/settings/sorting/rules/{$this->id}");
}
/**
* Get the books which are specifically set to use this sort rule.
* @return HasMany<Book, $this>
*/
public function books(): HasMany
{
return $this->hasMany(Book::class, 'entity_container_data.sort_rule_id', 'id');
}
/**
* Get all the available sort rules, ordered by name, with the number of books using each.
* @return Collection<SortRule>
*/
public static function allByName(): Collection
{
return static::query()

View File

@@ -102,7 +102,7 @@ class AttachmentService
/**
* Updates the ordering for a listing of attached files.
*/
public function updateFileOrderWithinPage(array $attachmentOrder, int $pageId)
public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId)
{
foreach ($attachmentOrder as $index => $attachmentId) {
Attachment::query()->where('uploaded_to', '=', $pageId)

View File

@@ -87,7 +87,7 @@ class RoleApiController extends ApiController
*/
public function read(string $id)
{
$role = $this->permissionsRepo->getRoleById(intval($id));
$role = $this->permissionsRepo->getRoleById($id);
$this->singleFormatter($role);
return response()->json($role);

View File

@@ -94,7 +94,7 @@ class RoleController extends Controller
public function edit(string $id)
{
$this->checkPermission(Permission::UserRolesManage);
$role = $this->permissionsRepo->getRoleById(intval($id));
$role = $this->permissionsRepo->getRoleById($id);
$this->setPageTitle(trans('settings.role_edit'));
@@ -129,7 +129,7 @@ class RoleController extends Controller
public function showDelete(string $id)
{
$this->checkPermission(Permission::UserRolesManage);
$role = $this->permissionsRepo->getRoleById(intval($id));
$role = $this->permissionsRepo->getRoleById($id);
$roles = $this->permissionsRepo->getAllRolesExcept($role);
$blankRole = $role->newInstance(['display_name' => trans('settings.role_delete_no_migration')]);
$roles->prepend($blankRole);
@@ -151,7 +151,7 @@ class RoleController extends Controller
try {
$migrateRoleId = intval($request->input('migrate_role_id') ?: "0");
$this->permissionsRepo->deleteRole(intval($id), $migrateRoleId);
$this->permissionsRepo->deleteRole($id, $migrateRoleId);
} catch (PermissionsException $e) {
$this->showErrorNotification($e->getMessage());

View File

@@ -110,7 +110,7 @@ class UserApiController extends ApiController
*/
public function read(string $id)
{
$user = $this->userRepo->getById(intval($id));
$user = $this->userRepo->getById($id);
$this->singleFormatter($user);
return response()->json($user);
@@ -124,8 +124,8 @@ class UserApiController extends ApiController
*/
public function update(Request $request, string $id)
{
$data = $this->validate($request, $this->rules(intval($id))['update']);
$user = $this->userRepo->getById(intval($id));
$data = $this->validate($request, $this->rules($id)['update']);
$user = $this->userRepo->getById($id);
$this->userRepo->update($user, $data, userCan(Permission::UsersManage));
$this->singleFormatter($user);
@@ -140,7 +140,7 @@ class UserApiController extends ApiController
*/
public function delete(Request $request, string $id)
{
$user = $this->userRepo->getById(intval($id));
$user = $this->userRepo->getById($id);
$newOwnerId = $request->input('migrate_ownership_id', null);
$this->userRepo->destroy($user, $newOwnerId);

View File

@@ -3,7 +3,6 @@
namespace BookStack\Util;
use Closure;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Throwable;
@@ -25,7 +24,7 @@ use Throwable;
class DatabaseTransaction
{
/**
* @param (Closure(Connection): TReturn) $callback
* @param (Closure(static): TReturn) $callback
*/
public function __construct(
protected Closure $callback

View File

@@ -40,6 +40,7 @@
"socialiteproviders/okta": "^4.2",
"socialiteproviders/twitch": "^5.3",
"ssddanbrown/htmldiff": "^2.0.0",
"web-auth/webauthn-lib": "^5.3",
"xemlock/htmlpurifier-html5": "^0.1.12"
},
"require-dev": {

1035
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,7 +7,7 @@ parameters:
- app
# The level 8 is the highest level
level: 5
level: 4
phpVersion:
min: 80200

View File

@@ -0,0 +1,74 @@
@extends('layouts.simple')
@section('body')
<div class="container very-small py-xl">
<div class="card content-wrap auto-height">
<h1 class="list-heading">{{ trans('auth.mfa_gen_hardware_key_title') }}</h1>
<p>{{ trans('auth.mfa_gen_hardware_key_desc') }}</p>
<div class="text-center mb-xs">
<button type="button" id="setup">setup_key</button>
</div>
<form action="{{ url('/mfa/hardware_key/confirm') }}" method="POST">
{{ csrf_field() }}
<div class="mt-s text-right">
<a href="{{ url('/mfa/setup') }}" class="button outline">{{ trans('common.cancel') }}</a>
<button class="button">{{ trans('auth.mfa_gen_confirm_and_enable') }}</button>
</div>
</form>
</div>
</div>
<script type="module" nonce="{{ $cspNonce }}">
// TODO - Extract to its own compontent
// TODO - Add some guidance and call this on click
// https://webauthn-doc.spomky-labs.com/prerequisites/javascript#using-native-browser-api
const setupButton = document.getElementById('setup');
const options = {!! $options !!};
const publicKeyCredentialCreationOptions = {
...options,
challenge: base64urlDecode(options.challenge),
user: {
...options.user,
id: base64urlDecode(options.user.id)
},
excludeCredentials: options.excludeCredentials?.map(cred => ({
...cred,
id: base64urlDecode(cred.id)
}))
};
setupButton.addEventListener('click', async () => {
console.log(publicKeyCredentialCreationOptions);
const credential = await navigator.credentials.create({
publicKey: publicKeyCredentialCreationOptions,
});
console.log(credential);
});
function base64urlEncode(buffer) {
const base64 = btoa(String.fromCharCode(...new Uint8Array(buffer)));
return base64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
function base64urlDecode(base64url) {
const base64 = base64url
.replace(/-/g, '+')
.replace(/_/g, '/');
const padding = '='.repeat((4 - base64.length % 4) % 4);
const binary = atob(base64 + padding);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
</script>
@stop

View File

@@ -8,7 +8,7 @@
<p class="mb-none"> {{ trans('auth.mfa_setup_desc') }}</p>
<div class="setting-list">
@foreach(['totp', 'backup_codes'] as $method)
@foreach(\BookStack\Access\Mfa\MfaValue::allMethods() as $method)
@include('mfa.parts.setup-method-row', ['method' => $method])
@endforeach
</div>

View File

@@ -319,6 +319,8 @@ Route::middleware('mfa-setup')->group(function () {
Route::post('/mfa/totp/confirm', [AccessControllers\MfaTotpController::class, 'confirm']);
Route::get('/mfa/backup_codes/generate', [AccessControllers\MfaBackupCodesController::class, 'generate']);
Route::post('/mfa/backup_codes/confirm', [AccessControllers\MfaBackupCodesController::class, 'confirm']);
Route::get('/mfa/hardware_key/generate', [AccessControllers\MfaHardwareKeyController::class, 'generate']);
Route::post('/mfa/hardware_key/confirm', [AccessControllers\MfaHardwareKeyController::class, 'confirm']);
});
Route::middleware('guest')->group(function () {
Route::get('/mfa/verify', [AccessControllers\MfaController::class, 'verify']);