{"version":3,"sources":["../../src/client/index.ts","../../src/client/events.ts","../../src/client/auth-client.ts"],"sourcesContent":["// Browser and native client surface.\n//\n// Kept separate from the package root deliberately: the root pulls a Redis\n// client, a JOSE implementation and server middleware, none of which can be\n// bundled for a browser or a native runtime. Importing the root from a client\n// application would fail at bundle time, or worse, succeed and ship them.\n//\n// Nothing in this subpath has a dependency.\n\nexport type { AuthClient } from \"./auth-client.js\";\nexport {\n  createAuthClient,\n  hasUserContext,\n  reportUnauthorized,\n  sharedAuthClient,\n} from \"./auth-client.js\";\nexport type { AuthEvent, AuthEventListener } from \"./events.js\";\nexport type { AuthState, AuthTransport, UserIdentity } from \"./types.js\";\n","import type { UserIdentity } from \"./types.js\";\n\n/**\n * Authentication events, as a closed set.\n *\n * A tenant application needs to *react* to authentication changing, not merely\n * read the current state: a session that expires mid-use must tear down the\n * session-scoped UI, cancel in-flight work and send the person to sign in\n * again. Polling `getState()` cannot express \"this just happened\", and every\n * application that reconstructs the transition from successive states arrives\n * at a slightly different answer.\n *\n * Names are Amplify's wherever the concept exists — `signedIn`, `signedOut` —\n * so that Amplify's documentation reads as documentation for this package. The\n * differences are deliberate, and every one of them follows from the same fact:\n * the gateway, not this client, performs OAuth and owns the session cookie.\n * Amplify's client holds tokens and runs the redirect flow itself, so it can\n * observe steps that are simply not visible from here.\n *\n *   tokenRefresh          not emitted. Amplify holds tokens in the client and\n *   tokenRefresh_failure  refreshes them there. Here the gateway owns the\n *                         session cookie and performs any refresh, so a refresh\n *                         is not an event this side can observe. `sessionExpired`\n *                         reports the only consequence that is observable, and\n *                         carries `tokenRefresh_failure`'s semantics.\n *\n *   signInWithRedirect    not emitted, and deliberately absent rather than\n *   signInWithRedirect_   declared-but-silent. Verified against agentgateway\n *   failure               (http/oidc/callback.rs, http/oidc/mod.rs): on success\n *                         the gateway redirects to the originally requested URI\n *                         with no `code` or `state` in the query, so a\n *                         successful return is indistinguishable from any other\n *                         authenticated load. On failure — `?error=` from the\n *                         provider, or a CSRF, nonce or exchange failure — the\n *                         gateway answers 400 or 500 AT the callback path, so\n *                         the application is never loaded and no listener of\n *                         ours can run. An event that can never fire is worse\n *                         than a missing one: it invites a sign-in error\n *                         handler that never runs, and the impression that\n *                         sign-in cannot fail.\n *\n *   customOAuthState      not emitted. Amplify passes application state through\n *                         the `state` parameter and hands it back on return. The\n *                         gateway performs the exchange and does not surface\n *                         `state`, so there is nothing to hand back; an\n *                         application should keep pre-redirect state in session\n *                         storage instead.\n *\n *   checkFailed           has no Amplify equivalent, because Amplify's client\n *                         reads a local token and cannot fail to reach it. Here\n *                         determining the session is a network call to the\n *                         gateway, which introduces a third answer — \"unknown\" —\n *                         that must not be collapsed into \"signed out\".\n *\n * The payload shape follows Amplify too: a single `data` field, so a listener\n * written against one reads against the other.\n *\n * The set is closed for the same reason `AuthState` is: an open string channel\n * invites each application to invent its own events, which is exactly the\n * per-tenant authentication logic this package exists to remove.\n *\n * The distinction that matters, and the one applications get wrong:\n *\n *   signedOut       the person asked to leave. Expected, no warning, no return\n *                   path to preserve.\n *\n *   sessionExpired  the person did NOT ask. They were authenticated a moment\n *                   ago and are not now. The application should say so, keep\n *                   whatever it can, and offer a way back — signing someone out\n *                   silently mid-task is indistinguishable from a bug.\n *\n *   checkFailed     the client does not KNOW. A network failure or a gateway\n *                   error is not a signed-out signal, and treating it as one\n *                   signs people out because a request timed out. Applications\n *                   should generally do nothing here except perhaps retry.\n *\n * Modelled on the AWS Amplify Hub auth channel, which draws the same lines\n * (`signedIn`, `signedOut`, `tokenRefresh_failure`). The naming follows this\n * platform's conventions rather than Amplify's underscore style.\n */\nexport type AuthEvent =\n  /** Dispatched when the user is signed-in. Amplify: `signedIn`. */\n  | { readonly event: \"signedIn\"; readonly data: UserIdentity }\n  /** Dispatched after the user signs out. Amplify: `signedOut`. */\n  | { readonly event: \"signedOut\" }\n  /**\n   * An established session is no longer valid, without the person asking.\n   *\n   * Amplify's nearest equivalent is `tokenRefresh_failure`, and the name is\n   * deliberately NOT reused: that event describes a token this client never\n   * holds. The gateway owns the session cookie and performs any refresh, so the\n   * only thing observable here is that a session which worked no longer does.\n   * The semantics are Amplify's — a definitive authentication failure, never a\n   * transient one — while the name describes what actually happened.\n   *\n   * This is the event an application logs out on. It fires only on a transition\n   * FROM authenticated, so an anonymous first load is never mistaken for an\n   * expiry.\n   */\n  | { readonly event: \"sessionExpired\" }\n  /**\n   * The session could not be determined. Not a signed-out signal.\n   *\n   * Mirrors the rule Amplify states in TokenOrchestrator.handleErrors: clear the\n   * session only for definitive authentication failures, never for transient\n   * ones such as service issues or rate limits.\n   */\n  | { readonly event: \"checkFailed\"; readonly data: { readonly error: Error } };\n\nexport type AuthEventListener = (event: AuthEvent) => void;\n\n/**\n * Fans an event out to listeners without letting one break the others.\n *\n * A listener that throws must not prevent the remaining listeners from running:\n * these fire on session expiry, when the listeners that matter most are the ones\n * tearing down access to data. Errors are reported and swallowed.\n */\nexport function createEventEmitter() {\n  const listeners = new Set<AuthEventListener>();\n\n  return {\n    listen(listener: AuthEventListener): () => void {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n    emit(event: AuthEvent): void {\n      for (const listener of [...listeners]) {\n        try {\n          listener(event);\n        } catch (cause) {\n          // Reported, not rethrown. One application's faulty handler must not\n          // stop another's from revoking access.\n          // eslint-disable-next-line no-console\n          console.error(\"[zero-ops-auth] auth event listener threw\", cause);\n        }\n      }\n    },\n    get size() {\n      return listeners.size;\n    },\n  };\n}\n","import { type AuthEventListener, createEventEmitter } from \"./events.js\";\nimport type { AuthState, AuthTransport, UserIdentity } from \"./types.js\";\n\n/** Where the aggregation boundary serves the current identity. */\nconst IDENTITY_PATH = \"/api/v1/auth/me\";\n\nexport interface AuthClient {\n  /** Current state. Synchronous; \"unknown\" until the first check completes. */\n  getState(): AuthState;\n  /** Re-check the session. Safe to call concurrently. */\n  refresh(): Promise<AuthState>;\n  /** Observe state changes. Returns an unsubscribe function. */\n  subscribe(listener: (state: AuthState) => void): () => void;\n  /**\n   * Observe authentication EVENTS. Returns an unsubscribe function.\n   *\n   * Use this to react to a session ending — tear down session-scoped UI, cancel\n   * in-flight work, send the person to sign in. `subscribe` reports what the\n   * state is; this reports what just happened, which is what an application\n   * needs in order to log someone out.\n   */\n  listen(listener: AuthEventListener): () => void;\n  /**\n   * End the session locally and announce it.\n   *\n   * Emits `signedOut`, never `sessionExpired`: the person asked. Clearing the\n   * gateway's cookie is the gateway's business — this is the client-side half,\n   * so an application has one call that means \"the session is over\" regardless\n   * of which side ended it.\n   */\n  signOut(): void;\n  /**\n   * Re-check the session periodically so expiry is noticed without user action.\n   *\n   * Without this a session expires silently and the person discovers it when\n   * their next action fails, which surfaces as a broken feature rather than as\n   * being signed out. Returns a function that stops the polling.\n   */\n  startSessionWatch(intervalMs?: number): () => void;\n  /**\n   * Report an unauthorized response from an external action.\n   *\n   * Called on any 401 from an ordinary endpoint and whenever an EventSource\n   * closes (ADR-050 amendment 2026-10-21).\n   */\n  reportUnauthorized(): void;\n}\n\n/**\n * A platform-agnostic authentication client.\n *\n * Exists because the identity contract — which endpoint, what the response\n * means, which failures are \"signed out\" and which are \"something broke\" — is\n * platform behaviour, and it is about to have more than one consumer. A browser\n * application and a native one that each implement it will diverge, and the way\n * they diverge is by disagreeing on the cases below, none of which is obvious.\n *\n * WHAT AN UNSUCCESSFUL RESPONSE MEANS\n *\n * A 401 means the session is absent or invalid: the person is signed out, which\n * is an ordinary state and not an error. Anything else — a network failure, a\n * gateway error, a malformed body — means the client does not know, and saying\n * \"signed out\" would be a claim it cannot support. Clients routinely conflate\n * the two and sign people out because a request timed out.\n *\n * CONCURRENCY\n *\n * Overlapping refreshes share one in-flight request. Without that, mounting\n * several components that each check on mount produces a burst of identical\n * requests, and their responses can resolve out of order and leave the last\n * writer's stale answer in place.\n */\nexport function createAuthClient(transport: AuthTransport = {}): AuthClient {\n  const doFetch = transport.fetch ?? globalThis.fetch;\n  const base = transport.baseUrl ?? \"\";\n  const credentials = transport.credentials ?? \"include\";\n\n  let state: AuthState = { status: \"unknown\", user: null, error: null };\n  let inFlight: Promise<AuthState> | null = null;\n  let ended = false;\n  const listeners = new Set<(s: AuthState) => void>();\n  const events = createEventEmitter();\n\n  /**\n   * Applies a new state and derives the event the transition represents.\n   *\n   * Events are derived here, in one place, rather than at each call site. The\n   * transition — not the destination — carries the meaning: arriving at\n   * `unauthenticated` is an expiry if the previous state was `authenticated`,\n   * and an ordinary unauthenticated visitor otherwise. Every application that\n   * reconstructs that from successive states gets it subtly wrong, usually by\n   * signing people out on first load.\n   */\n  function set(next: AuthState): AuthState {\n    const previous = state;\n    state = next;\n    for (const listener of listeners) listener(state);\n\n    if (next.status === \"authenticated\" && previous.status !== \"authenticated\") {\n      ended = false;\n      events.emit({ event: \"signedIn\", data: next.user as UserIdentity });\n    } else if (next.status === \"unauthenticated\" && previous.status === \"authenticated\") {\n      // The only transition that means a live session ended on its own.\n      ended = true;\n      events.emit({ event: \"sessionExpired\" });\n    } else if (next.status === \"error\" && next.error) {\n      events.emit({ event: \"checkFailed\", data: { error: next.error } });\n    }\n    return state;\n  }\n\n  async function check(): Promise<AuthState> {\n    if (!doFetch) {\n      return set({\n        status: \"error\",\n        user: null,\n        error: new Error(\"no fetch implementation available\"),\n      });\n    }\n\n    try {\n      const headers = transport.authHeaders ? await transport.authHeaders() : undefined;\n\n      const res = await doFetch(`${base}${IDENTITY_PATH}`, {\n        credentials,\n        headers,\n        // Do not follow the gateway's redirect to the identity provider.\n        //\n        // An unauthenticated request is answered with a 302 to the provider,\n        // which is right for a document navigation and unusable for this one:\n        // the browser follows it cross-origin, the provider sends no CORS\n        // headers, and the application sees a network error naming the identity\n        // provider instead of learning that its session ended.\n        //\n        // With redirect: \"manual\" that same 302 arrives as an opaque response —\n        // type \"opaqueredirect\", status 0 — which is a reliable, same-origin\n        // signal meaning exactly \"the gateway wants us to authenticate\".\n        // From agentgateway v1.6.0 (ADR-050), the gateway can also answer with\n        // a direct 401. Both are handled below.\n        redirect: \"manual\",\n      });\n\n      // The gateway answers either a 302, which arrives as opaqueredirect, or,\n      // from agentgateway v1.6.0 (ADR-050), a 401. Both are already handled:\n      // both mean signed out, and an application should not have to know which\n      // layer answered.\n      if (res.type === \"opaqueredirect\" || res.status === 0) {\n        return set({ status: \"unauthenticated\", user: null, error: null });\n      }\n      if (res.status === 401) {\n        return set({ status: \"unauthenticated\", user: null, error: null });\n      }\n      if (!res.ok) {\n        // Not a signed-out signal. Reporting one here would sign a person out\n        // because a gateway returned 502.\n        return set({\n          status: \"error\",\n          user: null,\n          error: new Error(`identity check failed with status ${res.status}`),\n        });\n      }\n\n      const body = (await res.json()) as { user?: UserIdentity };\n      if (!body.user?.subject) {\n        return set({\n          status: \"error\",\n          user: null,\n          error: new Error(\"identity response contained no subject\"),\n        });\n      }\n\n      return set({ status: \"authenticated\", user: body.user, error: null });\n    } catch (cause) {\n      return set({\n        status: \"error\",\n        user: null,\n        error: cause instanceof Error ? cause : new Error(\"identity check failed\"),\n      });\n    }\n  }\n\n  function refresh(): Promise<AuthState> {\n    if (inFlight) return inFlight;\n    inFlight = check().finally(() => {\n      inFlight = null;\n    });\n    return inFlight;\n  }\n\n  return {\n    getState: () => state,\n    subscribe(listener) {\n      listeners.add(listener);\n      return () => listeners.delete(listener);\n    },\n    listen: events.listen,\n    signOut() {\n      const wasAuthenticated = state.status === \"authenticated\";\n      state = { status: \"unauthenticated\", user: null, error: null };\n      for (const listener of listeners) listener(state);\n      // Deliberately not routed through set(): that would derive\n      // `sessionExpired` from the same transition. The person asked to leave,\n      // and telling the application their session expired would have it show a\n      // warning and try to recover a session nobody wants.\n      if (wasAuthenticated) {\n        ended = true;\n        events.emit({ event: \"signedOut\" });\n      }\n    },\n    startSessionWatch(intervalMs = 60_000) {\n      // Only meaningful while signed in, but the check is cheap and the state\n      // may change under it, so it simply re-checks and lets set() decide\n      // whether anything happened.\n      const id = setInterval(() => {\n        void refresh();\n      }, intervalMs);\n      return () => clearInterval(id);\n    },\n    reportUnauthorized() {\n      if (ended || inFlight) return;\n      void refresh();\n    },\n    refresh,\n  };\n}\n\nlet sharedClient: AuthClient | undefined;\nlet sharedTransport: AuthTransport | undefined;\n\n/**\n * A module-scoped shared AuthClient instance.\n *\n * The first call creates the instance with `createAuthClient(transport ?? {})`\n * and records the transport. A later call with transport that isn't undefined\n * and isn't the same object reference throws an Error.\n *\n * Create the transport once (a module-level constant) and pass that same object\n * everywhere. An inline object is a new transport on every render, and React\n * StrictMode and hot reload render twice.\n */\nexport function sharedAuthClient(transport?: AuthTransport): AuthClient {\n  if (!sharedClient) {\n    sharedTransport = transport;\n    sharedClient = createAuthClient(transport ?? {});\n    return sharedClient;\n  }\n  if (transport !== undefined && transport !== sharedTransport) {\n    throw new Error(\n      \"sharedAuthClient: already created with a different transport. Create the transport once (a module-level constant) and pass that same object everywhere. An inline object is a new transport on every render, and React StrictMode and hot reload render twice.\",\n    );\n  }\n  return sharedClient;\n}\n\n/**\n * Report an unauthorized response to the shared AuthClient instance.\n *\n * Called on any 401 from an ordinary endpoint and whenever an EventSource\n * closes (ADR-050 amendment 2026-10-21).\n */\nexport function reportUnauthorized(): void {\n  sharedAuthClient().reportUnauthorized();\n}\n\n/**\n * Whether the client may act on behalf of a specific person yet.\n *\n * Authenticated is not sufficient: the tenant-local identifier can be absent\n * while the session is perfectly valid, and anything keyed on ownership must\n * wait for it rather than sending null. Provided here so each client does not\n * decide separately what \"ready\" means.\n */\nexport function hasUserContext(\n  state: AuthState,\n): state is { status: \"authenticated\"; user: UserIdentity & { userId: string }; error: null } {\n  return state.status === \"authenticated\" && state.user.userId !== null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsHO,SAAS,qBAAqB;AACnC,QAAM,YAAY,oBAAI,IAAuB;AAE7C,SAAO;AAAA,IACL,OAAO,UAAyC;AAC9C,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QA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