Search from the browser
A front end reaches Meilisearch, Typesense or Algolia in one of two ways: it queries the engine directly with a signed token, or it goes through a route of your application, which adds the reader's filter on the server. Declare which one, once, in the boot() method of a service provider:
use Lomkit\Access\Access;
Access::searchTokens(direct: true); // browsers query the engine with a token from Access::searchToken()
Access::searchTokens(direct: false); // browsers go through a route that calls Access::guardSearch()
- An application makes one choice: a second declaration that differs from the first throws
ConflictingSearchTokensException. The same declaration twice is accepted. Access::searchToken()throwsUndeclaredSearchTokensExceptionuntil one is declared, andProxiedSearchTokenExceptionunderdirect: false.
Direct search with a token
direct: true is safe only on the engine versions below, which keep the filter of the token apart from the filter that the browser sends. The package cannot check the version of your servers: the declaration is your statement that every engine your browsers query meets this table.
| Engine | direct: true needs |
|---|---|
| Typesense | The first release that includes typesense/typesense#3111 (expected 31.0). Older servers do not isolate the filter of the browser from the filter of a scoped key: use direct: false with them. |
| Meilisearch | 1.0 or later. The filter of a tenant token is applied apart from the filter of the browser. |
| Algolia | Not verified by the package. Algolia documents that the browser cannot change the parameters of a secured API key; use direct: false for a guarantee that the package verifies. |
Access::searchToken() signs the reader's filter into a key derived from a search-only key:
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Lomkit\Access\Access;
use Lomkit\Access\Search\Tokens\SearchTokenKey;
class PostSearchTokenController
{
public function __invoke(Request $request): JsonResponse
{
$token = Access::searchToken(
reader: $request->user(),
model: Post::class,
key: SearchTokenKey::meilisearch(uid: config('services.meilisearch.search_key_uid'), key: config('services.meilisearch.search_key')),
expiresAt: now()->addMinutes(15),
);
return response()->json($token); // {"token": "...", "index": "posts", "expires_at": "..."}
}
}
- The token is built for the engine the model searches with: a tenant token for Meilisearch, a scoped search key for Typesense, a secured API key for Algolia. Pass the key of that engine,
SearchTokenKey::meilisearch(uid:, key:),SearchTokenKey::typesense(key:)orSearchTokenKey::algolia(key:), orMismatchedSearchTokenKeyExceptionis thrown. - The filter in the token is the one
controlled()applies, in the syntax of the engine. A reader thatcontrolled()would show an empty page gets a token whose filter asks for a key that no document carries. An unrestricted reader without a boundary gets a token with no filter, over the whole index of the model. - The token keeps the keys of its reader until it expires: a permission change reaches the browser with the next token. The expiry is required, and one that is not in the future throws
PastSearchTokenExpiryException. Keep it short, from a few minutes to an hour. scout.prefixis part of the index name.index()on the token returns the prefixed name, for the front end to query.- On the engine versions of the table above, the browser can narrow its search with its own filter, never widen it.
The search-only key
Never sign with the admin key: a key equal to the one Scout uses (scout.meilisearch.key, scout.typesense.client-settings.api_key, scout.algolia.secret) throws AdminSearchTokenKeyException. Create a search-only key for each engine, and read it from your own configuration, such as config/services.php:
- Meilisearch:
POST /keyswith the master key and{"actions": ["search"], "indexes": ["posts"], "expiresAt": null}, naming the index of the model with itsscout.prefix. Pass theuidand thekeyit returns. The token is limited to the index of the model. - Typesense:
POST /keyswith the admin key and{"description": "Search posts", "actions": ["documents:search"], "collections": ["posts"]}, naming the collection of the model with itsscout.prefix. Pass thevalue, which Typesense returns only once. A scoped key cannot narrow the collections of its parent key, so limit the parent key to the collection of the model. - Algolia: in the dashboard, under API Keys, create a key with the
searchACL and the index of the model, with itsscout.prefix, or use the search-only API key. The token is limited to the index of the model.
Meilisearch and Typesense sign with their official client, meilisearch/meilisearch-php or typesense/typesense-php, which Scout already needs; without it, MissingSearchClientException names the package. Algolia keys are signed by the package.
Good to know
- With
scout.soft_deleteon, the filter of a token leaves out the deleted rows of a model that usesSoftDeletes. Declare__soft_deletedas anint32field of the Typesense collection, or every search of a token fails. - A Typesense token embeds
filter_curated_hits: true, and an Algolia token with a filter embedsenableRules=falseandenableABTest=false, which the browser cannot turn back on. - Typesense runs its natural-language model before it applies the parameters of a scoped key: do not configure a natural-language search model on a Typesense server that browsers query with tokens.
- The
database,collectionandnullengines, Turbopuffer and the engines passed toAccess::trustSearchEngine()have no browser token:UnsupportedSearchTokenEngineException. filter()on the token returns the rendered filter, for logs and tests. Its JSON form holds the token, the index and the expiry only.
Through a route of the application
With direct: false, the front end sends the body of its multi-search to a route of your application. The route authenticates the reader, passes the body to Access::guardSearch(), and forwards the body it returns to the engine, with a search-only key that stays on the server:
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Lomkit\Access\Access;
class SearchController
{
public function __invoke(Request $request): JsonResponse
{
$body = json_decode($request->getContent(), true);
$guarded = Access::guardSearch(is_array($body) ? $body : [], $request->user());
$response = Http::baseUrl(config('services.typesense.url'))
->withHeaders(['X-TYPESENSE-API-KEY' => config('services.typesense.search_key')])
->post('/multi_search', $guarded);
return response()->json($response->json(), $response->status());
}
}
Route::post('/search', SearchController::class)->middleware('auth');
Give the search client of the front end, the InstantSearch adapter of your engine, the URL of that route instead of the engine's.
- Read the raw body, as above: Laravel's
TrimStringsandConvertEmptyStringsToNullmiddlewares rewrite$request->json(). - Forward the guarded body only, never the query string or the headers of the browser: a Typesense
presetin the query string, for instance, replaces the whole body. One exception: withunion: true, Typesense reads the pagination of the union (page,per_page,offset,limitandlimit_hits) from the query string. Forward those five, as integers, and nothing else. - Return the status of the engine, so that a search the engine rejects stays a client error.
- The filter is computed at each request, so a permission change applies at the next search.
| Engine | Body | Forward to | Key |
|---|---|---|---|
| Typesense | {"searches": [...]} | POST /multi_search | X-TYPESENSE-API-KEY header |
| Meilisearch (1.1 or later) | {"queries": [...]} | POST /multi-search | Authorization: Bearer header |
| Algolia | {"requests": [...]} | POST /1/indexes/*/queries | X-Algolia-Application-Id and X-Algolia-API-Key headers |
What the guard checks
Access::guardSearch(array $body, ?Model $reader): array is pure: it calls no engine.
- The field that lists the searches tells the engine. A body with none of them, or several, throws
InvalidSearchBodyException. - Each search names its index (
collection,indexUidorindexName), which must be the index of aControlledSearchablemodel whose control is discovered. Any other index throwsUnknownSearchIndexException, an Algolia replica or a Typesense alias included. Two discovered models searched in the same index throwAmbiguousSearchIndexException. - The model must search with the engine of the body, or
InvalidSearchBodyExceptionis thrown. The engines that have no token throwUnguardableSearchEngineException. - The reader's filter is the one
controlled()applies, added to the filter of the browser:
| Engine | Filter of the browser | Sent to the engine | Forced |
|---|---|---|---|
| Typesense | filter_by, a string that ends on its own | (<filter_by>) && (<access filter>) | filter_curated_hits: true |
| Meilisearch | filter, a string or a list of strings and lists of strings | [<access filter>, ...<filter>] | |
| Algolia | filters, a string without backslash that ends on its own | <filters> AND <access filter>, with parentheses around an OR | enableRules: false, enableABTest: false |
- The guard accepts only the parameters that narrow, page, rank or format the documents the reader may see, listed below. Any other parameter, including one that differs by its case only, refuses the whole body with
RefusedSearchParameterException. A filter it cannot combine throwsRefusedSearchFilterException. A forced parameter replaces whatever the browser sends. InvalidSearchBodyException,UnknownSearchIndexException,RefusedSearchParameterExceptionandRefusedSearchFilterExceptionare HTTP exceptions: Laravel answers422with their message and does not report them.- With
scout.soft_deleteon, the filter of a model that usesSoftDeletesalso leaves out its deleted rows.
The parameters left out let the browser choose a key, stored settings (presets, curations, rules, A/B tests), documents that the engine adds to a search, a language model, or the history of another user: set them on the server instead. Typesense natural-language search (nl_query) is refused, and so are the rule contexts and curation tags that an InstantSearch QueryRuleContext widget sends. Algolia analytics parameters are accepted, so that the InstantSearch insights middleware keeps working: the browser chooses the userToken, so do not let Algolia personalization rank a guarded search by it.
Typesense. Each search: collection, q, query_by, query_by_weights, prefix, infix, max_extra_prefix, max_extra_suffix, pre_segmented_query, split_join_tokens, text_match_type, num_typos, min_len_1typo, min_len_2typo, typo_tokens_threshold, drop_tokens_threshold, drop_tokens_mode, enable_typos_for_numerical_tokens, enable_typos_for_alpha_numerical_tokens, synonym_prefix, synonym_num_typos, enable_synonyms, demote_synonym_match, synonym_sets, stopwords, filter_by, filter_curated_hits, enable_lazy_filter, max_filter_by_candidates, validate_field_names, hidden_hits, sort_by, prioritize_exact_match, prioritize_token_position, prioritize_num_matching_fields, facet_by, facet_query, facet_query_num_typos, max_facet_values, facet_strategy, facet_sample_percent, facet_sample_threshold, facet_sample_slope, facet_return_parent, group_by, group_limit, group_missing_values, group_max_candidates, page, per_page, offset, limit, limit_hits, include_fields, exclude_fields, highlight_fields, highlight_full_fields, highlight_affix_num_tokens, highlight_start_tag, highlight_end_tag, snippet_threshold, exhaustive_search, search_cutoff_ms, max_candidates, use_cache, cache_ttl, vector_query, rerank_hybrid_matches, remote_embedding_timeout_ms, remote_embedding_num_tries, voice_query. The body takes searches, union and remove_duplicates. A reference to another collection ($name(...)) in filter_by, a $ in include_fields, exclude_fields, sort_by, facet_by or group_by, and a vector_query with an id are refused.
Meilisearch. Each search: indexUid, q, offset, limit, page, hitsPerPage, attributesToRetrieve, attributesToCrop, cropLength, cropMarker, attributesToHighlight, highlightPreTag, highlightPostTag, showMatchesPosition, filter, sort, distinct, facets, matchingStrategy, attributesToSearchOn, rankingScoreThreshold, locales, hybrid, vector, retrieveVectors, media, personalize, showRankingScore, showRankingScoreDetails, showPerformanceDetails, and federationOptions with weight and queryPosition. The body takes queries and federation, with limit, offset, page, hitsPerPage, facetsByIndex, mergeFacets, distinct, showPerformanceDetails and personalize.
Algolia. Each request: query, similarQuery, filters, facetFilters, optionalFilters, numericFilters, tagFilters, sumOrFiltersScores, restrictSearchableAttributes, facets, facetingAfterDistinct, maxValuesPerFacet, sortFacetValuesBy, facetQuery, maxFacetHits, page, hitsPerPage, offset, length, aroundLatLng, aroundLatLngViaIP, aroundRadius, aroundPrecision, minimumAroundRadius, insideBoundingBox, insidePolygon, naturalLanguages, queryLanguages, ignorePlurals, removeStopWords, decompoundQuery, attributesToRetrieve, attributesToHighlight, attributesToSnippet, highlightPreTag, highlightPostTag, snippetEllipsisText, restrictHighlightAndSnippetArrays, minWordSizefor1Typo, minWordSizefor2Typos, typoTolerance, allowTyposOnNumericTokens, disableTypoToleranceOnAttributes, queryType, removeWordsIfNoResults, advancedSyntax, advancedSyntaxFeatures, optionalWords, disableExactOnAttributes, exactOnSingleWordQuery, alternativesAsExact, distinct, getRankingInfo, synonyms, replaceSynonymsInHighlight, minProximity, responseFields, percentileComputation, attributeCriteriaComputedByMinProximity, relevancyStrictness, analytics, analyticsTags, clickAnalytics, userToken, enableRules and enableABTest, as fields of the request or in its params query string, not both. A request also takes indexName, type and facet; the body takes requests and strategy. A parameter twice in params, whatever its case, is refused.
Stored settings that skip the filter
- Meilisearch search rules that pin documents (Enterprise Edition, Meilisearch Cloud) are not verified by the package: do not pin the documents of a controlled model.
- Do not declare Meilisearch
foreignKeysfrom or to the index of a controlled model: Meilisearch replaces the keys with the documents of the other index.
These apply to controlled searches, tokens and guarded searches alike.
Searching through a parent
A searchable child declared with ThroughParent is found through the keys of its parent, and its documents follow the changes of the parent.
Your own search client
Keep the access filter when you query the search engine with your own client, or feed your own index with Access::indexKeysOf() and Access::indexReaderKeys().