# AutoSugges — Issue a publishable key from the dashboard API

You are integrating AutoSugges, a hosted autocomplete and list-of-values service. Everything you need is in this message; do not guess at anything it does not state, and do not fetch documentation to fill a gap — ask instead.

## Objective
A correct, session-authenticated call that issues a publishable key scoped to one list and one set of allowed origins, with the Turnstile challenge it requires. A publishable key alone is enough for a public or shared list; a private list additionally needs a short-lived access token, which is a separate, already-self-serve flow — issue a secret key from the same dashboard applications page (shown once) and exchange it at POST /api/v1/token (see the "token" API reference topic) — not covered step-by-step here.

## Environment
- Target framework/runtime: AutoSugges dashboard (session-authenticated).
- SDK package: `@autosugges/client`.
- Runtime HTTP API version: `v1`.
- Install: No install: a session-authenticated fetch from the dashboard origin, cookies included.

## Prerequisites
- A signed-in AutoSugges dashboard session (a browser cookie) — this route is not reachable with a publishable key or an access token.
- An application already created in the workspace (POST /api/applications), and a list the workspace owns or holds a subscription to.
- A Turnstile site key rendered on the page, so the browser can produce a challenge token before this call is made.

## Values you must supply
- `applicationId` (required, SECRET — server-side only) — placeholder `APPLICATION_ID_FROM_THE_DASHBOARD`. Path segment: POST /api/applications/{applicationId}/keys. Source: The id of the application returned by POST /api/applications, or read from the dashboard.
- `listId` (required, SECRET — server-side only) — placeholder `LIST_ID_TO_SCOPE_THE_KEY_TO`. The canonical list this key will be allowed to query. Source: The workspace's own list, or a list it holds an active subscription to.
- `listOwnerTenantId` (required, SECRET — server-side only) — placeholder `OWNER_TENANT_ID_OF_THAT_LIST`. Re-asserted here rather than inferred, so a stale or guessed id fails closed instead of resolving to the wrong list. Source: The list's ownerTenantId — the caller's own tenant id for an owned list, or the publisher's tenant id for a subscribed one.
- `allowedOrigins` (required, public by design) — placeholder `["https://example.com"]`. A non-empty array. The runtime rejects any query whose Origin header is not on this list. Source: The origins your site will actually be served from, scheme and host, no path.
- `challengeToken` (required, SECRET — server-side only) — placeholder `TURNSTILE_TOKEN_FROM_THE_WIDGET`. Verified server-side before the key is minted. A missing or failed token means no key is issued and nothing is billed for the attempt. Source: The browser Turnstile widget on the dashboard page, rendered with the site key.
- The base URL below is still the literal placeholder `YOUR_RUNTIME_BASE_URL`. Ask the developer for their environment's runtime origin and substitute it; do not invent an autosugges.com hostname.

## Request contract
The publishable key travels as a query parameter (or, for selection reports, a JSON body field) — NOT as an Authorization header. The Authorization header is reserved for the optional access token of a protected list.
- `GET /v1/bootstrap?key=<publishable key>` — Resolves the list identity, the active version hash and the effective query policy for this key. Call once per session before querying. Key placement: `key` query parameter. Headers: `x-request-id`: a per-request correlation id (the SDK mints one automatically); `authorization: Bearer <access token>`: optional, and only for a list whose policy requires a token.
- `GET /v1/query?key=<publishable key>&q=<text>&locale=<optional BCP-47 tag>` — Returns the pre-ranked suggestions for one query. Key placement: `key` query parameter. Headers: `x-request-id`: a per-request correlation id; `authorization: Bearer <access token>`: optional, as above.
- `POST /v1/selection` — Reports which suggestion the user chose, so ranking can improve. Optional: skipping it degrades ranking quality and nothing else. Key placement: `key` field of the JSON body, alongside `selectionId`, `queryRequestId`, `listId`, `itemId`, `query` and `position`. Headers: `content-type: application/json`; `x-request-id`.

## Policy that arrives from bootstrap — never hardcode these
- `requestId` (string) — Correlation id for this bootstrap call.
- `list.id` (string (UUID)) — The canonical list this key resolves to. Never supplied by the client.
- `activeVersionHash` (string) — The published version currently serving. Compare it to a stored hash to decide whether a cached local copy is stale.
- `queryPolicy.minQueryChars` (number) — Minimum characters before a query is legal. Never below 2, and never hardcoded — a shorter query is rejected and not billed.
- `queryPolicy.debounceMs` (number) — How long to wait after the last keystroke before issuing a query.
- `queryPolicy.defaultResultLimit` (number) — How many suggestions a list returns by default. Informational: the server already returns its ranked set, so the client does not send this back.
- `queryPolicy.rememberLastSelection` (boolean) — Tenant policy for prefilling a previously chosen item. Treat anything other than literal `true` as off.

## What one suggestion looks like
- `itemId` (string) — Stable identifier. Use it as the React/list key.
- `value` (string) — The canonical value — what you store.
- `displayValue` (string) — The locale-resolved label — what you render. Not the same field as `value`.
- `displayOrder` (number) — The owner's configured display order.
- `position` (number) — 1-based position in the returned ranking.
- `ancestors` (array, optional) — The precomputed hierarchy chain, root first, excluding the item itself — `{ itemId, value, displayValue, hierarchyLevel? }`. Use it to auto-fill parent form fields. Absent when the item has no ancestors; never an empty array.

## Implementation steps
1. Create the application first — POST /api/applications with { name } if one does not already exist. A key always belongs to an application.
2. Render the Turnstile widget — The dashboard page renders it with the site key exposed to the browser; its callback produces the challengeToken this call needs.
3. POST the key request — POST /api/applications/{applicationId}/keys with listId, listOwnerTenantId, allowedOrigins, environment and challengeToken, cookies included.
4. Capture the key immediately — Read keyShownOnce from the 201 response and store it. A second read of the same key is not possible — the dashboard stores only its digest and a display prefix.
5. Publish before you rely on it — If publishPending is true, the list has no active version yet. Publish it — the key resolves nothing at the edge until then.

## Code — `issue-key.ts`
```ts
// Runs in the browser, on an already-signed-in dashboard page.
// The session cookie travels automatically with credentials: 'include'.
const response = await fetch(`/api/applications/${applicationId}/keys`, {
  method: 'POST',
  credentials: 'include',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({
    listId,
    listOwnerTenantId,
    allowedOrigins: ['https://example.com'],
    environment: 'production', // or 'development' / 'staging'
    challengeToken, // from the Turnstile widget's callback
  }),
});

if (!response.ok) {
  const body = await response.json();
  throw new Error(`key issuance failed: ${body.code}`);
}

const { keyShownOnce, key, publishPending } = await response.json();
// keyShownOnce is the full publishable key. It is returned exactly once —
// the dashboard never lets you read it back. Store it in your own secret
// manager or environment configuration immediately.
// publishPending is true when the list has never been published: the key
// exists but the edge has nothing to serve yet.
```

## Security requirements
- A publishable key is public by design. It is safe in client-side JavaScript, in a mobile bundle, and in a page a search engine can read. It is not a secret and does not need a proxy.
- A publishable key is not a substitute for origin control: keys are bound to an allow-list of origins, and a request from an origin the tenant has not allowed is refused with `origin_not_allowed` and is not billed. Add the deploying site’s origin in the AutoSugges dashboard before going live.
- Never place a secret key, a signing key, a service-role credential or a database URL in client code, in an environment variable prefixed for browser exposure, or in a prompt. Nothing in an AutoSugges browser or mobile integration needs one.
- An access token (`authorization: Bearer …`) is only for a list whose policy requires one. It is short-lived, and it is minted by your own server from your own AutoSugges credentials — never in the browser, never hardcoded, never committed.
- Do not log the raw query text or the response body. Log the typed error `code` and the `requestId`.
- The publishable key is public by design once issued — safe to ship in front-end code. What is not public is the request that mints it: it requires a signed-in session and a verified Turnstile challenge, precisely because minting is the sensitive operation, not holding the result.
- A secret key is the opposite: never public, server-only, and never sent from browser or mobile code. Issue one from the same dashboard applications page (shown once — the dashboard stores only a digest and a display prefix) and exchange it at POST /api/v1/token with Authorization: Bearer <secret key> for a one-hour access token, which your backend then hands to the browser as the query-time Authorization: Bearer <access token> header a private list requires. In staging/production that mint route may answer 503 token_minting_unavailable until the signing secret is provisioned there — retry later rather than treating it as a missing feature.

## Expected result
A 201 response carrying keyShownOnce (the full key, shown exactly once), a key record with its prefix and status, and publishPending naming whether the list has anything to serve yet.

## Validation — do these before reporting success
1. Check 1 — Attempt the call with no challengeToken and confirm it is rejected before any key is created.
2. Check 2 — Attempt the call while signed out (no session cookie) and confirm it is rejected rather than falling back to an unauthenticated path.
3. Check 3 — Confirm the 201 response body is only ever readable once — reloading the page never shows the raw key again, only its prefix.
4. Check 4 — Confirm the response carries publishPending: true for a list with no active version, and false once that list has been published.

## Error codes you must handle
Every failure arrives as a typed code in the response body (and, through the SDK, as an `AutosuggesError` with that `code`). Switch on the code; never match on a message string. The codes most likely on this surface are: `invalid_request`, `challenge_failed`, `invalid_list`, `subscription_required`. The complete vocabulary:
- `invalid_key` (HTTP 401, not retryable) — The publishable key is wrong, revoked or rotated. Check the key in the AutoSugges dashboard. Do not retry with the same key.
- `origin_not_allowed` (HTTP 403, not retryable) — The requesting origin is not on this key's allow-list. Add the origin in the dashboard. Not billed.
- `invalid_list` (HTTP 404, not retryable) — The key resolves to no list, or the list was deleted. Nothing to retry.
- `subscription_required` (HTTP 403, not retryable) — The list is shared and this consumer has no active subscription to it. Subscribe, or use a list you own.
- `list_not_published` (HTTP 409, not retryable) — The list exists but has never been published, so there is no artifact to serve. Publish it once from the dashboard.
- `token_expired` (HTTP 401, not retryable) — The access token is past its expiry. Mint a fresh one on your server and retry once. Never extend expiry on the client.
- `invalid_token` (HTTP 401, not retryable) — The access token failed signature or scope verification. Mint a new one; do not retry the same token.
- `quota_exceeded` (HTTP 200, not retryable) — The allowance for this billing scope is spent. `details.scope` says which allowance — `subscription` or `key`. The response carries no items at all, real or synthetic: render an upgrade path, and do not feed it into selection analytics. It clears at the next billing period.
- `query_too_short` (HTTP 200, not retryable) — The query is below the list's `minQueryChars` (`details.minQueryChars`). Do not issue the request at all until the input reaches it. Not billed.
- `query_too_long` (HTTP 400, not retryable) — The query exceeds the server maximum (`details.maxQueryChars`). Trim the input before sending; this is a malformed request, not something a user types.
- `invalid_request` (HTTP 400, not retryable) — The request is malformed — a missing parameter or an unusable value. `details` names what. Fix the call; retrying unchanged cannot help.
- `rate_limited` (HTTP 429, retryable) — Too many requests for this key, subscription or IP. Honour the `retryAfter` seconds in the body before retrying, and check that the input is actually debounced.
- `challenge_failed` (HTTP 403, not retryable) — A bot challenge was not satisfied on a session-establishing surface. Re-present the challenge. Not billed.
- `publish_validation_failed` (HTTP 422, not retryable) — A publish was rejected by validation (duplicates, an unresolved parent, a hierarchy cycle). The previously active version keeps serving. Fix the data and publish again.
- `compile_failed` (HTTP 500, retryable) — Compilation of a new version failed. The previously active version keeps serving; nothing at runtime changed. Retry the publish after fixing the reported cause.
- `artifact_unavailable` (HTTP 503, retryable) — A published artifact could not be read at this edge, usually mid-propagation. Retryable: wait the `retryAfter` seconds and retry once. Do not render a partial or stale result set alongside a fresh one.
- `resource_removed` (HTTP 404, not retryable) — The resource was deleted. Stop requesting it; there is nothing to retry.
- `invalid_domain` (HTTP 400, not retryable) — The submitted domain or slug is not valid or is reserved. Choose another.
- `domain_validation_failed` (HTTP 409, not retryable) — A custom-domain DNS or TLS validation did not complete. Re-check the DNS records shown in the dashboard, then revalidate.
- `forbidden` (HTTP 403, not retryable) — Your account is signed in but your workspace role does not permit this action. Ask an owner or admin to change your role, or use an account that has it.
- `internal_error` (HTTP 500, retryable) — An unexpected server-side failure. Report the `requestId` from the response. Retry at most once, with backoff.

## Notes
- The key text is never logged and never appears in any response after the first one — treat the 201 body as the only copy.
- Rotating or disabling a key is a separate, already-existing action reached from the same dashboard page; neither is covered by this topic.
- A secret key and the access token it mints are a different credential pair from the publishable key this topic issues — see "Mint an access token" for that flow, including its own request/response shape and error vocabulary.

## Reference
- API reference index: https://staging.docs.autosugges.com/api-reference
- Mint an access token: https://staging.docs.autosugges.com/api-reference/token
- Integration guides: https://staging.docs.autosugges.com/integrations

---
Canonical page: https://staging.docs.autosugges.com/api-reference/token
