# Search from the browser

> Let a front end search Meilisearch, Typesense or Algolia with a signed token that holds the reader's filter, or through an application route that guards it.

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:

```php
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()` throws `UndeclaredSearchTokensException` until one is declared, and `ProxiedSearchTokenException` under `direct: 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.

<table>
<thead>
  <tr>
    <th>
      Engine
    </th>
    
    <th>
      <code>
        direct: true
      </code>
      
       needs
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Typesense
    </td>
    
    <td>
      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 <code>
        direct: false
      </code>
      
       with them.
    </td>
  </tr>
  
  <tr>
    <td>
      Meilisearch
    </td>
    
    <td>
      1.0 or later. The filter of a tenant token is applied apart from the filter of the browser.
    </td>
  </tr>
  
  <tr>
    <td>
      Algolia
    </td>
    
    <td>
      Not verified by the package. Algolia documents that the browser cannot change the parameters of a secured API key; use <code>
        direct: false
      </code>
      
       for a guarantee that the package verifies.
    </td>
  </tr>
</tbody>
</table>

`Access::searchToken()` signs the reader's filter into a key derived from a search-only key:

```php [app/Http/Controllers/PostSearchTokenController.php]
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:)` or `SearchTokenKey::algolia(key:)`, or `MismatchedSearchTokenKeyException` is thrown.
- The filter in the token is the one `controlled()` applies, in the syntax of the engine. A reader that `controlled()` 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.prefix` is 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 /keys` with the master key and `{"actions": ["search"], "indexes": ["posts"], "expiresAt": null}`, naming the index of the model with its `scout.prefix`. Pass the `uid` and the `key` it returns. The token is limited to the index of the model.
- **Typesense:** `POST /keys` with the admin key and `{"description": "Search posts", "actions": ["documents:search"], "collections": ["posts"]}`, naming the collection of the model with its `scout.prefix`. Pass the `value`, 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 `search` ACL and the index of the model, with its `scout.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_delete` on, the filter of a token leaves out the deleted rows of a model that uses `SoftDeletes`. Declare `__soft_deleted` as an `int32` field 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 embeds `enableRules=false` and `enableABTest=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`, `collection` and `null` engines, Turbopuffer and the engines passed to `Access::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:

```php [app/Http/Controllers/SearchController.php]
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());
    }
}
```

```php [routes/web.php]
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 `TrimStrings` and `ConvertEmptyStringsToNull` middlewares rewrite `$request->json()`.
- Forward the guarded body only, never the query string or the headers of the browser: a Typesense `preset` in the query string, for instance, replaces the whole body. One exception: with `union: true`, Typesense reads the pagination of the union (`page`, `per_page`, `offset`, `limit` and `limit_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.

<table>
<thead>
  <tr>
    <th>
      Engine
    </th>
    
    <th>
      Body
    </th>
    
    <th>
      Forward to
    </th>
    
    <th>
      Key
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Typesense
    </td>
    
    <td>
      <code>
        {"searches": [...]}
      </code>
    </td>
    
    <td>
      <code>
        POST /multi_search
      </code>
    </td>
    
    <td>
      <code>
        X-TYPESENSE-API-KEY
      </code>
      
       header
    </td>
  </tr>
  
  <tr>
    <td>
      Meilisearch (1.1 or later)
    </td>
    
    <td>
      <code>
        {"queries": [...]}
      </code>
    </td>
    
    <td>
      <code>
        POST /multi-search
      </code>
    </td>
    
    <td>
      <code>
        Authorization: Bearer
      </code>
      
       header
    </td>
  </tr>
  
  <tr>
    <td>
      Algolia
    </td>
    
    <td>
      <code>
        {"requests": [...]}
      </code>
    </td>
    
    <td>
      <code>
        POST /1/indexes/*/queries
      </code>
    </td>
    
    <td>
      <code>
        X-Algolia-Application-Id
      </code>
      
       and <code>
        X-Algolia-API-Key
      </code>
      
       headers
    </td>
  </tr>
</tbody>
</table>

### 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`, `indexUid` or `indexName`), which must be the index of a `ControlledSearchable` model whose control is [discovered](/essentials/controls#discovery). Any other index throws `UnknownSearchIndexException`, an Algolia replica or a Typesense alias included. Two discovered models searched in the same index throw `AmbiguousSearchIndexException`.
- The model must search with the engine of the body, or `InvalidSearchBodyException` is thrown. The engines that have no token throw `UnguardableSearchEngineException`.
- The reader's filter is the one `controlled()` applies, added to the filter of the browser:

<table>
<thead>
  <tr>
    <th>
      Engine
    </th>
    
    <th>
      Filter of the browser
    </th>
    
    <th>
      Sent to the engine
    </th>
    
    <th>
      Forced
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Typesense
    </td>
    
    <td>
      <code>
        filter_by
      </code>
      
      , a string that ends on its own
    </td>
    
    <td>
      <code>
        (<filter_by>) && (<access filter>)
      </code>
    </td>
    
    <td>
      <code>
        filter_curated_hits: true
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Meilisearch
    </td>
    
    <td>
      <code>
        filter
      </code>
      
      , a string or a list of strings and lists of strings
    </td>
    
    <td>
      <code>
        [<access filter>, ...<filter>]
      </code>
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      Algolia
    </td>
    
    <td>
      <code>
        filters
      </code>
      
      , a string without backslash that ends on its own
    </td>
    
    <td>
      <code>
        <filters> AND <access filter>
      </code>
      
      , with parentheses around an <code>
        OR
      </code>
    </td>
    
    <td>
      <code>
        enableRules: false
      </code>
      
      , <code>
        enableABTest: false
      </code>
    </td>
  </tr>
</tbody>
</table>

- 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 throws `RefusedSearchFilterException`. A forced parameter replaces whatever the browser sends.
- `InvalidSearchBodyException`, `UnknownSearchIndexException`, `RefusedSearchParameterException` and `RefusedSearchFilterException` are HTTP exceptions: Laravel answers `422` with their message and does not report them.
- With `scout.soft_delete` on, the filter of a model that uses `SoftDeletes` also 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.

<collapsible name="accepted parameters">

**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.

</collapsible>

## 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 `foreignKeys` from 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.
