npm package: @starasia/sso
Description: Reusable authentication helpers, storage utilities, and protected route components that wrap the Starasia single sign-on (SSO) flow. The codebase is published as a consumable package that can be embedded into other React applications.
Latest version: 0.0.42

# Starasia SSO Package

Reusable authentication helpers, storage utilities, and protected route components that wrap the Starasia single sign-on (SSO) flow. The codebase is published as a consumable package that can be embedded into other React applications.

## Highlights

- React context provider that keeps authentication and authorization tokens in sync with secure storage
- Fetch helpers and default client built on `fetch` for exchanging, validating, and refreshing tokens
- Headless protected-route component that automatically handles SSO callbacks and redirects
- Storage helpers for persisting auth, OTP, and organization data using `@hudoro/storage`
- Library build powered by Vite (ES and UMD bundles) plus generated TypeScript declarations
- Runtime configuration helpers (`configureSSOApp`, `configureAuthClient`) for adapting API endpoints dan kredensial SSO di aplikasi host

## Instalasi

```bash
pnpm install
pnpm build        # emits dist/starasia-sso.* bundles + dist/types
```

Atau tambahkan dependensi ke aplikasi lain (menggunakan registri privat atau `npm link`):

```bash
pnpm add @starasia/sso
```

## Penggunaan Dasar

### 1. Setup Cepat (`setupSSO`)

Gunakan helper `setupSSO` untuk menginisialisasi seluruh paket secara modular:

```ts
import { setupSSO } from '@starasia/sso';

const { components, hooks, storage, config } = setupSSO({
  app: {
    key: window.__APP_KEY__,
    name: window.__APP_NAME__,
    api: { baseUrl: window.__API_BASE_URL__ },
    sso: {
      clientId: window.__SSO_CLIENT_ID__,
      redirectUri: window.__SSO_REDIRECT_URI__
    },
    storage: {
      otp: 'app-otp',
      access: 'app-access',
      auth: 'app-auth',
      organization: 'app-organization'
    }
  }
  // authClient: { exchangeAuthToken: ... } // opsional
});

const { AuthProvider, ProtectedRoute } = components;
const { useAuth, useValidate } = hooks;
const { globalLogout } = storage;

console.log('SSO siap dengan client:', config.sso.clientId);
```

Anda bisa mengekspor instance ini dari modul bootstrap, atau panggil sekali di `main.tsx` sebelum render aplikasi.
```

`setupSSO` otomatis memvalidasi konfigurasi dan mengembalikan peta komponen, hooks, storage helpers, dan client aktif. Bila Anda ingin melewati validasi (misal saat testing), set `validateConfig: false`.

### 2. Manual: Konfigurasi Runtime & Client HTTP

Helper individual tetap tersedia:

```ts
import {
  configureSSOApp,
  configureAuthClient,
  getSSOClientConfig,
  getSSOStorageConfig
} from '@starasia/sso';

configureSSOApp({
  api: { baseUrl: 'https://api.example.com' },
  sso: { clientId: 'client', redirectUri: 'https://sso.example.com' },
  storage: { otp: 'otp', access: 'access', auth: 'auth', organization: 'org' }
});

configureAuthClient({
  logout: (payload) => myHttp.post('/logout', payload)
});

console.log(getSSOClientConfig(), getSSOStorageConfig());
```

### 3. Bungkus Aplikasi dengan Provider

Gunakan langsung `AuthProvider`, atau `SSOContainer` jika Anda juga ingin React Query siap pakai.

```tsx
import { setupSSO } from '@starasia/sso';

const { components } = setupSSO({
  app: window.__SSO_CONFIG__ // misal disuntik dari server
});

const { AuthProvider } = components;

export function Bootstrap() {
  return (
    <AuthProvider>
      <RouterProvider router={router} />
    </AuthProvider>
  );
}
```

### 4. Lindungi Rute Menggunakan ProtectedRoute

```tsx
import { ProtectedRoute } from '@starasia/sso';

const router = createBrowserRouter([
  {
    path: '/',
    element: (
      <ProtectedRoute redirectPath="/login">
        <Dashboard />
      </ProtectedRoute>
    )
  }
]);
```

`ProtectedRoute` otomatis menghapus `authToken` dari query string, men-trigger `useAuthCallback`, menjalankan validasi akses, serta memanggil `globalLogout` bila validasi gagal. Anda bisa mengganti `loadingFallback` atau `unauthenticatedFallback` jika diperlukan.

### 5. Gunakan Hooks dan Utilitas Storage

```tsx
import { useAuth, useValidate, useLogout } from '@starasia/sso';

export function Profile() {
  const auth = useAuth();
  const validate = useValidate();
  const logout = useLogout();

  if (validate.isLoading) {
    return <span>Checking token…</span>;
  }

  return (
    <>
      <pre>{JSON.stringify(auth, null, 2)}</pre>
      <button onClick={() => logout.mutate()}>Logout</button>
    </>
  );
}
```

```ts
import {
  saveMainTokenToStorage,
  getMainTokenFromStorage,
  globalLogout
} from '@starasia/sso';

saveMainTokenToStorage({
  accessToken: 'access-token',
  refreshToken: 'refresh-token',
  idToken: 'id-token'
});

console.log(getMainTokenFromStorage());
globalLogout(); // redirect ke redirectUri + clientId dari konfigurasi runtime
```

## Scripts

- `pnpm dev` – run Vite dev server for local playground consumption
- `pnpm build:types` – emit only the `.d.ts` files into `dist/types`
- `pnpm build` – generate declaration files and bundle the package in both ES and UMD formats
- `pnpm preview` – preview the bundled playground output
- `pnpm lint` – run ESLint across the repo

## Konfigurasi Lingkungan & Runtime

Semua nilai dinamis kini dikonfigurasi manual melalui helper. Tidak ada lagi `import.meta.env` di dalam paket.

```ts
import { configureSSOApp } from '@starasia/sso';

configureSSOApp({
  key: 'base64-app-key',
  name: 'Starasia Portal',
  api: { baseUrl: 'https://api.example.com' },
  sso: {
    clientId: 'client-id',
    redirectUri: 'https://sso.example.com/callback'
  },
  storage: {
    otp: 'storage-otp-key',
    access: 'storage-access-key',
    auth: 'storage-auth-key',
    organization: 'storage-organization-key'
  }
});
```

Helper `configureSSOApp` dapat dipanggil satu kali pada bootstrap aplikasi host. Nilai bawaan adalah string kosong, jadi isi semua properti yang diperlukan. Untuk pengujian atau reset, gunakan `resetSSOAppConfig()`. Bila Anda hanya perlu mengubah HTTP client, gunakan `configureAuthClient`.

## Project Layout

```
src/
├── core/          # Config, HTTP helper, and API service definitions
├── lib/sso/       # Package surface area (provider, hooks, components)
├── utils/         # Secure storage helpers
└── index.ts       # Package entry point that re-exports public APIs
```

## License

Private internal package. Redistribution is restricted.