npm package: @golojan/auth
Description: Enterprise-grade SSO-enabled authentication SDK for OAuth2/OpenID authorization code with PKCE.
Latest version: 2.0.9

# @golojan/auth

Enterprise SSO authentication SDK for OAuth2/OpenID Connect using Authorization Code + PKCE.

## Install

```ts
// npm
npm i @golojan/auth
```

## Quick Start (Browser/Node)

```ts
import { createAuthClient } from '@golojan/auth';

const auth = createAuthClient({
  clientId: '<client-id>',
  clientSecret: '<client-secret>',
  redirectUri: 'https://app.example.com/api/callback',
  scope: 'openid profile email',
});
```

## Core Flow

```ts
// 1) Redirect user to SSO login
await auth.login();

// 2) On callback URL, exchange code
await auth.handleCallback(window.location.href);

// 3) Call userinfo
const me = await auth.userinfo();
```

## Next.js App Router (Recommended)

Use the reusable helpers from `@golojan/auth/next`.

### 1) Runtime auth client

```ts
// app/lib/auth.ts
import { createAuthClient } from '@golojan/auth';

const CLIENT_ID = process.env.NEXT_PUBLIC_OPENID_CLIENT_ID!;
const CLIENT_SECRET = process.env.OPENID_CLIENT_SECRET; // optional
const DEFAULT_ORIGIN = process.env.NEXT_PUBLIC_APP_ORIGIN ?? 'http://localhost:3000';

export const createRuntimeAuthClient = (origin = DEFAULT_ORIGIN) =>
  createAuthClient({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
    redirectUri: `${origin}/api/callback`,
    scope: 'openid profile email',
  });
```

### 2) Protect routes with `proxy.ts`

```ts
// proxy.ts
import { createAuthProxy, defaultAuthProxyMatcher } from '@golojan/auth/next';

const PUBLIC_ROUTES = ['/', '/api/callback'] as const;

export default createAuthProxy({
  callbackPath: '/api/callback',
  publicRoutes: [...PUBLIC_ROUTES],
});

export const config = {
  matcher: defaultAuthProxyMatcher,
};
```

### 3) Handle callback and code exchange

```ts
// app/api/callback/route.ts
import { createAuthCallbackHandler } from '@golojan/auth/next';
import { createRuntimeAuthClient } from '@/app/lib/auth';

export const GET = createAuthCallbackHandler({
  createAuthClient: createRuntimeAuthClient,
  callbackPath: '/api/callback',
  // optional: sync access token to client memory store
  accessTokenSyncCookieName: 'golojan_console_access_token_sync',
});
```

## Important Parameters

- `redirectUri`: OAuth client config value (your app callback URL, e.g. `https://app.example.com/api/callback`).
- `redirectTo`: SSO URL query param pointing to your callback URL.
- `returnTo`: SSO URL query param for the final in-app destination after callback/code exchange.
- `state`: signed/encoded context, includes `returnTo`.

`createAuthProxy` sets `redirectTo`, `returnTo`, and `state` automatically.
It also writes a short-lived returnTo cookie so callback redirect can recover even if upstream state is rewritten.
For mixed deployments, login URL generation includes legacy aliases (`redirectUri`, `redirect_uri`, `return_to`) in addition to canonical keys.

## API Surface (Core SDK)

- `loadDiscovery(): Promise<DiscoveryDoc>`
- `createLoginUrl(options?): Promise<string>`
- `login(options?): Promise<string>`
- `handleCallback(url): Promise<TokenSet>`
- `exchangeAuthorizationCode(args): Promise<TokenSet>`
- `exchangeAuthorizationCodeDetailed(args): Promise<{ tokenSet, setCookieHeaders }>`
- `getTokens(): TokenSet | null`
- `setTokens(tokens): void`
- `clearTokens(): void`
- `clearPendingAuth(): void`
- `clearClientState(): void`
- `userinfo(accessToken?): Promise<T>`
- `refresh(request?): Promise<TokenSet>`
- `logoutUrl(options?): Promise<string>`
- `logout(options?): Promise<string>`

## API Surface (`@golojan/auth/next`)

- `createAuthProxy(options?): (request: NextRequest) => NextResponse`
- `authProxy` (default proxy instance)
- `createAuthCallbackHandler(options): (request: Request) => Promise<NextResponse>`
- `defaultAuthProxyMatcher`

## Platform Defaults

- `AUTH_API_BASE_URL`: `https://api.golojan.com/v1`
- `AUTH_SWAGGER_JSON_URL`: `https://api.golojan.com/v1/auth/docs-json`
- `AUTH_DEFAULT_ISSUER`: `https://api.golojan.com/v1/auth`
- `AUTH_DEFAULT_AUTHORIZATION_ENDPOINT`: `https://accounts.golojan.com/auth/login`

## Storage Defaults

- Pending auth: `SessionPendingAuthStorage` (default, TTL-aware)
- Tokens: `MemoryTokenStorage` (default)
- Optional persistence: `createLocalTokenStorage()`

## Security Notes

- Uses PKCE (`S256`) + state validation.
- Uses top-level redirects for multi-domain SSO compatibility.
- Callback enforces same-origin `returnTo` normalization.
- Do not store secrets/tokens in logs or analytics.