> For the complete documentation index, see [llms.txt](https://sonic-ai-works.gitbook.io/sonic-networks-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sonic-ai-works.gitbook.io/sonic-networks-docs/api-reference/authentication-and-tenant-context.md).

# Authentication & tenant context

Preview authentication and tenant-context contract for signed sessions, server-authoritative identity, wallet verification boundaries, cache rules, lifecycle invalidation and normalized failures.

**Status:** `Preview / Development`

> **Under construction** — This authentication/context contract is not fully production-tested until explicitly marked **Live** or **Verified**.

Every protected SONIC request begins with a **signed, server-verified session**. Browser headers, React state, localStorage, wallet connection state and user-editable client data do not choose the current tenant, account, role or permissions.

## GET `/api/v1/auth/context`

This endpoint answers one question:

> **Who is authenticated, and what sanitized server authority was resolved for this session?**

It does **not** make a route-access decision and does **not** describe workspace subscription state.

### Canonical contract

```ts
type AuthContext = {
  authenticated: boolean;
  tenant: { id: string; slug?: string } | null;
  user: { id: string; displayName?: string; email?: string } | null;
  account: {
    id: string;
    status: "ACTIVE" | "SUSPENDED" | "DISABLED";
  } | null;
  role: "USER" | "CREATOR" | "ADMIN" | null;
  permissions: string[];
  verifiedWalletCount: number;
  authorityRevision: string;
};
```

The public response intentionally does not expose session IDs, raw provider/Firebase claims, provider credentials, refresh tokens, wallet signatures, private authorities, internal service credentials or signing material.

## Server authority

The browser calls the same-origin SONIC application gateway. The gateway forwards trusted signed-session material to the backend; authoritative identity, tenant/account, role, permissions and verified-wallet state are resolved server-side.

```
Browser
  ↓ signed session / same-origin request
SONIC application gateway
  ↓ trusted authenticated service context
SONIC API authority resolver
  ↓
tenant + account + user + role + permissions + wallet-link projection
```

If service-to-service identity headers are used internally, they are injected **only after trusted gateway authentication**. Public clients are never allowed to choose or override values such as:

```
x-user-id
x-tenant-id
x-account-id
role
permissions
entitlements
verified-wallet state
```

Any external request attempting to supply internal authority headers must be ignored or rejected according to gateway policy.

## Authentication vs access vs SaaS

Authentication determines **who is acting**.

Route/resource access is resolved separately:

```http
GET /api/v1/access/context?path=<internal-path>
```

Workspace/product capability state is resolved separately:

```http
GET /api/v1/saas/me
```

These context projections can bootstrap application UX, but every protected mutation still performs independent server authorization.

```
signed session
→ Auth Context
→ Access Context / SaaS Context for UX
→ destination mutation re-authorizes server-side
```

A cached `allowed: true`, role string, entitlement list or feature flag is never a bearer capability.

## Wallet ownership

A connected wallet is not a verified wallet. A verified wallet is not an authenticated session. An authenticated session does not authorize arbitrary wallet transactions.

Wallet ownership remains challenge-based:

```
challenge
→ explicit wallet signature
→ server verification
→ verified wallet-link record
```

`verifiedWalletCount` is informational session context. Money-moving operations still resolve the **specific verified wallet** required by policy, freeze a server-authoritative `TransactionIntent`, require an explicit signature and independently verify chain effects before settlement.

```
wallet connected
≠ wallet verified
≠ application authenticated
≠ operation authorized
≠ transaction settled
```

## Session lifecycle

```
signed session issue
→ authenticated
→ optional refresh / rotation
→ revoke / expire / logout
→ no longer authenticated
```

Session handling must preserve revocation and rotation semantics rather than treating possession of old client context as authority.

Missing or invalid sessions return `UNAUTHENTICATED`. Expired sessions return `SESSION_EXPIRED`.

## Cache and invalidation

Authentication context is private authority state and must not be publicly cached.

```http
Cache-Control: private, no-store, max-age=0
Vary: Cookie, Authorization
```

A client may deduplicate the projection briefly in memory, but it must invalidate after:

* session creation;
* refresh or rotation;
* revoke, expire or logout;
* tenant/account switch;
* account-status change;
* user identity change;
* role or permission change;
* wallet verification or unlinking.

The browser must not persist Auth Context in localStorage as authorization evidence.

## Normalized authentication failures

| Code                  | HTTP | Meaning                                                       |
| --------------------- | ---: | ------------------------------------------------------------- |
| `UNAUTHENTICATED`     |  401 | No valid signed session                                       |
| `SESSION_EXPIRED`     |  401 | Signed session expired                                        |
| `ACCOUNT_DISABLED`    |  403 | Current account is not active                                 |
| `TENANT_NOT_FOUND`    |  404 | Session tenant cannot be resolved                             |
| `TENANT_UNAVAILABLE`  |  503 | Tenant authority temporarily unavailable                      |
| `ACCESS_DENIED`       |  403 | Current session/account authority cannot be resolved or used  |
| `CONTEXT_UNAVAILABLE` |  503 | Required context dependency unavailable                       |
| `INTERNAL_ERROR`      |  500 | Unexpected context-service failure with a safe public message |

Provider, database, session-signing and internal stack details remain server-side.

## Required distinction

SONIC keeps each security state explicit:

```
Authentication
→ principal identity

Authorization
→ operation authority

Route/resource access
→ one internal path/resource decision

SaaS context
→ subscription + entitlements + feature availability

Wallet verification
→ proof of address control

Quote/policy validation
→ frozen commercial/risk policy

TransactionIntent
→ one exact server-authoritative action

Explicit signature
→ signer approval of that concrete action

Chain verification
→ network evidence

Effect verification
→ recipient + asset + atomic amount + reference + business effect

Settlement
→ economic transition

Reconciliation
→ durable SONIC state agrees with authoritative external state
```

No earlier state substitutes for a later one.

## Application implementation boundary

Recommended monorepo ownership:

```
apps/web
  public marketing + account entry

apps/dashboard
  authenticated product shell
  consumes sanitized context only

apps/api
  session verification
  authority resolution
  context endpoints
  protected mutations

packages/auth
  session parsing/verification interfaces
  internal authority types
  gateway-header policy

packages/contracts
  AuthContext
  AccessContext
  SaaSContext
  normalized envelopes/errors
```

The browser-facing apps never become the authority database. Server-side packages remain the only source of resolved tenant/account/role/permission state.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://sonic-ai-works.gitbook.io/sonic-networks-docs/api-reference/authentication-and-tenant-context.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
