@findlane/browser 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,6 +79,8 @@ A response has `hits` (each with its `record` and any `highlights`), `total`, `f
79
79
 
80
80
  The public ID grants search access only to its index, and it is visible in browser source. By default the API returns every uploaded record field. `attributesToRetrieve` requests fewer fields for speed, but it does not make the others private. Origin checks constrain browsers; they do not authenticate other callers. Keep public catalog fields safe to expose. The dashboard can remove origins, add server-enforced restrictions, or rotate the ID.
81
81
 
82
+ For logged-in people, pass `signedKey`: a short-lived key your server signs with the server SDK's `signSearchKey`, or a function that fetches one. Its restrictions replace the index's public settings. See [Logged-in visitors](https://findlane.dev/docs/security#logged-in-visitors).
83
+
82
84
  ## Errors
83
85
 
84
86
  Failed requests throw a `FindlaneError` with the HTTP `status` and the API's message:
package/dist/index.d.ts CHANGED
@@ -386,18 +386,29 @@ export type BrowserClientOptions = {
386
386
  * banner covers analytics, or your shoppers don't need one; with `events: "afterConsent"` the IDs
387
387
  * wait for consent as events do. */
388
388
  visitorIds?: boolean;
389
+ /** A signed key (0.25.0) from your server (the server SDK's `signSearchKey`), for a person who's logged in:
390
+ * searches and did-you-mean suggestions send it, and its restrictions replace the index's public policy and
391
+ * allowed sites. Or a function that fetches one: called for the first search, again shortly before the key
392
+ * expires, and once more if the API says it has. Make a new client when the person changes. */
393
+ signedKey?: string | (() => string | Promise<string>);
389
394
  };
390
395
  export declare class SearchBrowserClient {
391
396
  private readonly url;
392
397
  private readonly origin;
393
398
  private readonly publicId;
394
399
  private readonly fetcher;
400
+ private readonly signer?;
401
+ /** The signed key a function gave, and when it expires. */
402
+ private signed;
395
403
  /** Views, clicks, add-to-carts and orders, for the index's Events page and Bought together. */
396
404
  readonly events: BrowserEvents;
397
405
  /** The shopper's recent searches, kept in this browser only. */
398
406
  readonly recentSearches: RecentSearches;
399
407
  private popular;
400
408
  constructor(options: BrowserClientOptions);
409
+ /** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
410
+ * expires, or at once when `fresh`. */
411
+ private signedKey;
401
412
  private post;
402
413
  private get;
403
414
  /** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
package/dist/index.js CHANGED
@@ -94,6 +94,16 @@ const landed = (value) => !!value && typeof value == "object" && typeof value.q
94
94
  /** The hosted Findlane API, used unless `baseUrl` says otherwise. */
95
95
  export const defaultBaseUrl = "https://api.findlane.dev";
96
96
  const day = 86_400_000;
97
+ /** When a signed key expires, in Unix seconds, from its restrictions; Infinity when it can't be read. */
98
+ function signedKeyExpiry(signedKey) {
99
+ try {
100
+ const until = atob(signedKey).slice(64).match(/(?:^|&)validUntil=(\d+)/)?.[1];
101
+ return until ? Number(until) : Infinity;
102
+ }
103
+ catch {
104
+ return Infinity;
105
+ }
106
+ }
97
107
  /** The visitor and visit IDs of a public ID, kept on the device: the visitor's in localStorage, made
98
108
  * anew 13 months after it was made (use doesn't extend it); the visit's in sessionStorage, made anew
99
109
  * after 30 minutes without events, with how the visit's search was opened from outside the site, if it was.
@@ -237,6 +247,9 @@ export class SearchBrowserClient {
237
247
  origin;
238
248
  publicId;
239
249
  fetcher;
250
+ signer;
251
+ /** The signed key a function gave, and when it expires. */
252
+ signed = null;
240
253
  /** Views, clicks, add-to-carts and orders, for the index's Events page and Bought together. */
241
254
  events;
242
255
  /** The shopper's recent searches, kept in this browser only. */
@@ -249,21 +262,43 @@ export class SearchBrowserClient {
249
262
  this.url = `${(options.baseUrl ?? defaultBaseUrl).replace(/\/$/, "")}/api/public/indexes/${options.publicId}`;
250
263
  this.origin = new URL(this.url).origin;
251
264
  this.fetcher = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
265
+ this.signer = options.signedKey;
252
266
  this.events = eventSender(options.eventsUrl ?? `${this.url}/events`, options.fetch, options.events ?? true, options.visitorIds ? deviceIds(options.publicId) : null);
253
267
  this.recentSearches = new RecentSearches(options.publicId);
254
268
  }
255
- async post(operation, request, signal) {
269
+ /** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
270
+ * expires, or at once when `fresh`. */
271
+ signedKey(fresh) {
272
+ const signer = this.signer;
273
+ if (signer === undefined)
274
+ return undefined;
275
+ if (typeof signer == "string")
276
+ return Promise.resolve(signer);
277
+ if (fresh || !this.signed || Date.now() / 1000 > this.signed.until - 30) {
278
+ const entry = { key: Promise.resolve().then(signer), until: Infinity };
279
+ entry.key.then((key) => { entry.until = signedKeyExpiry(key); }, () => { if (this.signed === entry)
280
+ this.signed = null; });
281
+ this.signed = entry;
282
+ }
283
+ return this.signed.key;
284
+ }
285
+ async post(operation, request, signal, renewed = false) {
286
+ // A signed key goes in the body, so the request needs no preflight.
287
+ const signing = operation === "search" || operation === "suggest" ? this.signedKey(renewed) : undefined;
256
288
  const response = await this.fetcher(`${this.url}/${operation}`, {
257
289
  method: "POST",
258
290
  // JSON as text/plain: browsers send it without asking the API first (a CORS preflight), which
259
291
  // saves a round trip.
260
292
  headers: { "content-type": "text/plain" },
261
- body: JSON.stringify(request),
293
+ body: JSON.stringify(signing ? { ...request, signedKey: await signing } : request),
262
294
  signal,
263
295
  });
264
296
  const data = await response.json();
265
- if (!response.ok)
297
+ if (!response.ok) {
298
+ if (signing && !renewed && response.status === 401 && data.expired && typeof this.signer == "function")
299
+ return this.post(operation, request, signal, true);
266
300
  throw new FindlaneError(response.status, data.error ?? `HTTP ${response.status}`);
301
+ }
267
302
  return data;
268
303
  }
269
304
  // Lists are read with GET, which browsers send without a preflight and may keep for 30 seconds.
@@ -1,5 +1,5 @@
1
1
  import { type ReactNode } from "react";
2
- import { SearchBrowserClient } from "../index.js";
2
+ import { SearchBrowserClient, type BrowserClientOptions } from "../index.js";
3
3
  /** Where to search: a public ID (with an optional `baseUrl`), or a client you made. Leave both out
4
4
  * inside a FindlaneProvider. */
5
5
  export type ClientOptions = {
@@ -7,8 +7,9 @@ export type ClientOptions = {
7
7
  baseUrl?: string;
8
8
  client?: SearchBrowserClient;
9
9
  };
10
- /** Sets the index once for the hooks and components inside it. */
11
- export declare function FindlaneProvider({ children, ...options }: ClientOptions & {
10
+ /** Sets the index once for the hooks and components inside it. With `signedKey` (0.25.0), a signed key from your
11
+ * server, or a function that fetches one, the searches inside it are a logged-in person's (SearchBrowserClient). */
12
+ export declare function FindlaneProvider({ children, ...options }: ClientOptions & Pick<BrowserClientOptions, "signedKey"> & {
12
13
  children: ReactNode;
13
14
  }): import("react").JSX.Element;
14
15
  export declare function useClient(options?: ClientOptions): SearchBrowserClient;
@@ -1,12 +1,20 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { createContext, useContext, useMemo } from "react";
3
+ import { createContext, useContext, useMemo, useRef } from "react";
4
4
  import { SearchBrowserClient } from "../index.js";
5
5
  const ClientContext = createContext(null);
6
- function useOwnClient({ publicId, baseUrl, client }) {
7
- return useMemo(() => client ?? (publicId ? new SearchBrowserClient({ publicId, baseUrl }) : null), [client, publicId, baseUrl]);
6
+ function useOwnClient({ publicId, baseUrl, client, signedKey }) {
7
+ // A function is read when the client needs a key, so a new one each render keeps the client (and its
8
+ // cached results); a new key string makes a new client, for the person it's for.
9
+ const signer = useRef(signedKey);
10
+ signer.current = signedKey;
11
+ const kind = typeof signedKey == "function" ? "function" : signedKey;
12
+ return useMemo(() => client ?? (publicId ? new SearchBrowserClient({ publicId, baseUrl,
13
+ ...(typeof signer.current == "function" ? { signedKey: () => signer.current() }
14
+ : signer.current ? { signedKey: signer.current } : {}) }) : null), [client, publicId, baseUrl, kind]);
8
15
  }
9
- /** Sets the index once for the hooks and components inside it. */
16
+ /** Sets the index once for the hooks and components inside it. With `signedKey` (0.25.0), a signed key from your
17
+ * server, or a function that fetches one, the searches inside it are a logged-in person's (SearchBrowserClient). */
10
18
  export function FindlaneProvider({ children, ...options }) {
11
19
  const client = useOwnClient(options);
12
20
  if (!client)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@findlane/browser",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Findlane browser SDK: fast, typo-tolerant public search from the browser with an index's public ID, plus React hooks and components.",
5
5
  "keywords": ["findlane", "search", "full-text search", "typo tolerance", "instant search", "ecommerce search", "browser", "react", "autocomplete"],
6
6
  "license": "MIT",