@kivacore/signin 0.0.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,1193 @@
1
1
  # @kivacore/signin
2
2
 
3
- Placeholder. Install the latest version.
3
+ Authentication provider for Docyrus apps. Provides "Sign in with Docyrus" experience with automatic environment detection — standalone apps use OAuth2 Authorization Code + PKCE via page redirect, while iframe-embedded apps receive tokens via `window.postMessage` from the host.
4
+
5
+ Supports **React**, **Vue**, **React Native**, **Electron**, and **Next.js SSR** via separate entrypoints.
6
+
7
+ ## Features
8
+
9
+ - **Auto Environment Detection**: Detects standalone vs iframe mode automatically
10
+ - **OAuth2 PKCE**: Full Authorization Code flow with PKCE (S256) for standalone apps
11
+ - **Iframe Auth**: Receives tokens via `postMessage` from `*.docyrus.app` hosts
12
+ - **Host Message Hooks**: Subscribe to `navigation` and `notification` messages pushed by the host into the embedded app
13
+ - **App → Host Actions**: Send to Docy, Send to Chat, Send to Email, and Send to Calendar — hand `text`/`adaptiveCard`/email/event payloads to host surfaces, with a `Promise` that resolves on the host's delivery acknowledgement
14
+ - **Microsoft Graph Bridge**: Make **proxy-only** Microsoft Graph calls through the host's logged-in MSAL session (the access token never crosses the frame boundary)
15
+ - **Route Sync**: Mirror the embedded app's route to the host so the host can reflect it in its address bar
16
+ - **Token Auto-Refresh**: Proactive token refresh before expiry in both modes (opt out with `autoRefresh: false` when an external system owns the token lifecycle)
17
+ - **Token Bootstrap**: Start a session from existing access/refresh tokens (e.g. device flow handoff)
18
+ - **React Hooks**: `useDocyrusAuth()` and `useDocyrusClient()` for easy integration
19
+ - **Vue Composables**: `useDocyrusAuth()` and `useDocyrusClient()` for Vue 3
20
+ - **Authorization Helpers**: `hasRole()` and `hasPermission()` for role-based access control
21
+ - **Electron Support**: `ElectronTokenStorage` for IPC-based token storage + `getAuthorizationUrl()` for external browser login
22
+ - **Ready-to-Use API Client**: Exposes a configured `RestApiClient` from `@kivacore/api-client`
23
+ - **SignInButton**: Unstyled, customizable sign-in button component (React + Vue)
24
+ - **SSR Support**: Sync access token to cookie for server-side rendering (Next.js) with `max-age` and `Secure` flag
25
+ - **Next.js SSR Helpers**: `createServerClient()`, `getSession()`, `authMiddleware()` for server components, actions, and middleware
26
+ - **TypeScript**: Full type definitions included
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ npm install @kivacore/signin
32
+ ```
33
+
34
+ ```bash
35
+ pnpm add @kivacore/signin
36
+ ```
37
+
38
+ ### Peer Dependencies
39
+
40
+ - `@kivacore/api-client` >= 0.0.4
41
+ - `react` >= 19.2.0 (optional — required for React/Next.js entrypoint)
42
+ - `vue` >= 3.5.0 (optional — required for Vue entrypoint)
43
+
44
+ ## Entrypoints
45
+
46
+ | Import Path | Description | Framework |
47
+ |-------------|-------------|-----------|
48
+ | `@kivacore/signin` | React provider, hooks, components | React, Next.js |
49
+ | `@kivacore/signin/nextjs` | Server-side helpers (middleware, server client, session) | Next.js |
50
+ | `@kivacore/signin/vue` | Vue provider, composables, components | Vue 3 |
51
+ | `@kivacore/signin/electron` | Electron token storage | Electron |
52
+ | `@kivacore/signin/react-native` | React Native OAuth2 auth (in-app browser) | React Native / Expo |
53
+ | `@kivacore/signin/core` | Pure TypeScript core (no framework dependency) | Any |
54
+
55
+ ## Quick Start (React)
56
+
57
+ ```tsx
58
+ import { DocyrusAuthProvider, useDocyrusAuth, useDocyrusClient, SignInButton } from '@kivacore/signin';
59
+
60
+ function App() {
61
+ return (
62
+ <DocyrusAuthProvider
63
+ apiUrl="https://alpha-api.docyrus.com"
64
+ clientId="your-oauth2-client-id"
65
+ redirectUri="http://localhost:3000/callback"
66
+ scopes={['offline_access', 'Read.All', 'Users.Read']}
67
+ callbackPath="/callback">
68
+ <Dashboard />
69
+ </DocyrusAuthProvider>
70
+ );
71
+ }
72
+
73
+ function Dashboard() {
74
+ const { status, signOut } = useDocyrusAuth();
75
+ const client = useDocyrusClient();
76
+
77
+ if (status === 'loading') return <div>Loading...</div>;
78
+ if (status === 'unauthenticated') return <SignInButton />;
79
+
80
+ return (
81
+ <div>
82
+ <p>Authenticated!</p>
83
+ <button onClick={() => client!.get('/v1/users/me').then(console.log)}>
84
+ Fetch user
85
+ </button>
86
+ <button onClick={signOut}>Sign out</button>
87
+ </div>
88
+ );
89
+ }
90
+ ```
91
+
92
+ ## Quick Start (Vue)
93
+
94
+ ```vue
95
+ <!-- App.vue -->
96
+ <script setup lang="ts">
97
+ import { RouterView } from 'vue-router';
98
+ import { DocyrusAuthProvider } from '@kivacore/signin/vue';
99
+ </script>
100
+
101
+ <template>
102
+ <DocyrusAuthProvider
103
+ apiUrl="https://alpha-api.docyrus.com"
104
+ clientId="your-oauth2-client-id"
105
+ redirectUri="http://localhost:5173/callback"
106
+ :scopes="['offline_access', 'Read.All', 'Users.Read']"
107
+ callbackPath="/callback">
108
+ <RouterView />
109
+ </DocyrusAuthProvider>
110
+ </template>
111
+ ```
112
+
113
+ ```vue
114
+ <!-- Dashboard.vue -->
115
+ <script setup lang="ts">
116
+ import { useDocyrusAuth } from '@kivacore/signin/vue';
117
+
118
+ const { status, client, signIn, signOut } = useDocyrusAuth();
119
+ </script>
120
+
121
+ <template>
122
+ <div v-if="status === 'loading'">Loading...</div>
123
+ <button v-else-if="status === 'unauthenticated'" @click="signIn">Sign in</button>
124
+ <div v-else>
125
+ <p>Authenticated!</p>
126
+ <button @click="signOut">Sign out</button>
127
+ </div>
128
+ </template>
129
+ ```
130
+
131
+ ## Quick Start (Electron)
132
+
133
+ ```tsx
134
+ import { DocyrusAuthProvider, useDocyrusAuth } from '@kivacore/signin';
135
+ import { ElectronTokenStorage } from '@kivacore/signin/electron';
136
+
137
+ const tokenStorage = new ElectronTokenStorage();
138
+
139
+ function App() {
140
+ return (
141
+ <DocyrusAuthProvider
142
+ apiUrl="https://alpha-api.docyrus.com"
143
+ clientId="your-oauth2-client-id"
144
+ redirectUri="docyrus://callback"
145
+ scopes={['offline_access', 'Read.All', 'Users.Read']}
146
+ callbackPath="/callback"
147
+ tokenStorage={tokenStorage}>
148
+ <LoginPage />
149
+ </DocyrusAuthProvider>
150
+ );
151
+ }
152
+
153
+ function LoginPage() {
154
+ const { status, getAuthorizationUrl } = useDocyrusAuth();
155
+
156
+ const handleLogin = async () => {
157
+ const url = await getAuthorizationUrl();
158
+ if (url) {
159
+ // Open in system browser instead of navigating
160
+ await window.electronAPI.openExternal(url);
161
+ }
162
+ };
163
+
164
+ return <button onClick={handleLogin} disabled={status === 'loading'}>Sign in</button>;
165
+ }
166
+ ```
167
+
168
+ ## Quick Start (React Native / Expo)
169
+
170
+ ```tsx
171
+ import { DocyrusAuthProvider, useDocyrusAuth } from '@kivacore/signin/react-native';
172
+ import { createTokenStorage, ReactNativeCryptoProvider } from '@kivacore/api-client/react-native';
173
+ import * as WebBrowser from 'expo-web-browser';
174
+ import * as ExpoCrypto from 'expo-crypto';
175
+ import * as SecureStore from 'expo-secure-store';
176
+
177
+ const tokenStorage = createTokenStorage({
178
+ getItem: (key) => SecureStore.getItemAsync(key),
179
+ setItem: (key, value) => SecureStore.setItemAsync(key, value),
180
+ removeItem: (key) => SecureStore.deleteItemAsync(key),
181
+ });
182
+
183
+ function App() {
184
+ return (
185
+ <DocyrusAuthProvider
186
+ clientId="your-oauth2-client-id"
187
+ forceMode="react-native"
188
+ nativeRedirectUri="myapp://auth/callback"
189
+ openAuthSession={WebBrowser.openAuthSessionAsync}
190
+ tokenStorage={tokenStorage}
191
+ cryptoProvider={new ReactNativeCryptoProvider(ExpoCrypto)}>
192
+ <HomeScreen />
193
+ </DocyrusAuthProvider>
194
+ );
195
+ }
196
+
197
+ function HomeScreen() {
198
+ const { status, signIn, signOut } = useDocyrusAuth();
199
+ const client = useDocyrusClient();
200
+
201
+ if (status === 'loading') return <Text>Loading...</Text>;
202
+ if (status === 'unauthenticated') return <Button title="Sign In" onPress={signIn} />;
203
+
204
+ return (
205
+ <View>
206
+ <Text>Authenticated!</Text>
207
+ <Button title="Sign Out" onPress={signOut} />
208
+ </View>
209
+ );
210
+ }
211
+ ```
212
+
213
+ ### React Native Props
214
+
215
+ | Prop | Type | Description |
216
+ |------|------|-------------|
217
+ | `forceMode` | `'react-native'` | **Required** — enables mobile OAuth2 flow |
218
+ | `nativeRedirectUri` | `string` | **Required** — deep link URI scheme (e.g., `myapp://auth/callback`) |
219
+ | `openAuthSession` | `(url, redirectUri) => Promise<{type, url?}>` | **Required** — `WebBrowser.openAuthSessionAsync` from expo-web-browser |
220
+ | `tokenStorage` | `OAuth2TokenStorage` | Token storage (use `createTokenStorage()` from api-client) |
221
+ | `cryptoProvider` | `CryptoProvider` | PKCE crypto (use `ReactNativeCryptoProvider` from api-client) |
222
+
223
+ ## Configuration
224
+
225
+ Pass props to `DocyrusAuthProvider` to override defaults:
226
+
227
+ ```tsx
228
+ <DocyrusAuthProvider
229
+ apiUrl="https://alpha-api.docyrus.com"
230
+ clientId="your-oauth2-client-id"
231
+ redirectUri="http://localhost:3000/callback"
232
+ scopes={['offline_access', 'Read.All', 'Users.Read']}
233
+ callbackPath="/callback"
234
+ forceMode="standalone"
235
+ >
236
+ <App />
237
+ </DocyrusAuthProvider>
238
+ ```
239
+
240
+ | Prop | Type | Default | Description |
241
+ |------|------|---------|-------------|
242
+ | `apiUrl` | `string` | `https://alpha-api.docyrus.com` | Docyrus API base URL |
243
+ | `clientId` | `string` | **Required** | OAuth2 client ID (throws if missing) |
244
+ | `redirectUri` | `string` | `window.location.origin + callbackPath` | OAuth2 redirect URI |
245
+ | `scopes` | `string[]` | `['offline_access', 'Read.All', ...]` | OAuth2 scopes |
246
+ | `callbackPath` | `string` | `/auth/callback` | Path to detect OAuth callback |
247
+ | `forceMode` | `'standalone' \| 'iframe' \| 'react-native'` | Auto-detected | Force a specific auth mode |
248
+ | `nativeRedirectUri` | `string` | — | Deep link URI for React Native OAuth2 callback |
249
+ | `openAuthSession` | `Function` | — | `WebBrowser.openAuthSessionAsync` for React Native |
250
+ | `cryptoProvider` | `CryptoProvider` | Browser crypto | Custom crypto for PKCE (React Native) |
251
+ | `storageKeyPrefix` | `string` | `docyrus_oauth2_` | localStorage key prefix |
252
+ | `tokenStorage` | `OAuth2TokenStorage` | Browser localStorage | Custom token storage (e.g., `ElectronTokenStorage`) |
253
+ | `initialTokens` | `OAuth2Tokens` | `undefined` | Bootstrap a standalone / React Native session from existing tokens |
254
+ | `autoRefresh` | `boolean` | `true` | When `false`, the provider never refreshes tokens itself (no pre-expiry timer, no pre-request refresh, no reactive 401 refresh). The current access token is used until replaced via `signInWithTokens`. Use when an external system owns the token lifecycle. |
255
+ | `allowedHostOrigins` | `string[]` | `undefined` | Extra trusted iframe origins |
256
+ | `ssr` | `boolean` | `false` | Sync access token to cookie for server components |
257
+ | `ssrCookieKey` | `string` | `docyrus-token` | Cookie name for SSR token sync |
258
+ | `syncRouteToHost` | `boolean` | `false` | Iframe mode: post `route-change` to the host on every history change |
259
+ | `enableGuidyBridge` | `boolean` | `false` | Iframe mode: let the host assistant (Guidy) scan, highlight, and click this app's visible UI (see below) |
260
+ | `guidyRoutes` | `GuidyRoute[]` | `undefined` | Iframe mode: routes Guidy may navigate the user to inside this app (see below). Requires `enableGuidyBridge` |
261
+
262
+ ## Guidy Bridge (host-driven guidance)
263
+
264
+ When an app runs embedded in the Docyrus shell, the host AI assistant (Guidy)
265
+ can guide users _through the app_ — pointing at and clicking real in-app
266
+ buttons — once the app opts in:
267
+
268
+ ```tsx
269
+ <DocyrusAuthProvider apiUrl="..." clientId="..." enableGuidyBridge>
270
+ <App />
271
+ </DocyrusAuthProvider>
272
+ ```
273
+
274
+ This starts a small runtime (`GuidyBridge`) that, in iframe mode only:
275
+
276
+ - pushes the app's clickable inventory (`a[id]` / `button[id]` that are visible
277
+ and labeled) to the host on mount, route change, and DOM mutation;
278
+ - on a host `guidy:point`, scrolls to, highlights, optionally annotates, and
279
+ optionally clicks the target element, then acknowledges.
280
+
281
+ It is opt-in and intentionally narrow: it only exposes already-visible
282
+ interactive elements and only runs a fixed command vocabulary — **no arbitrary
283
+ script is accepted from the host**. All traffic rides the same origin-validated
284
+ postMessage channel as auth.
285
+
286
+ ```text
287
+ App → Host: { type: 'guidy:elements', path, elements: [{ id, label, tag }] }
288
+ App → Host: { type: 'guidy:routes', routes: [{ path, label }] }
289
+ Host → App: { type: 'guidy:scan' } // re-request inventory + routes
290
+ Host → App: { type: 'guidy:point', id, click?, message? } // point / click / annotate
291
+ App → Host: { type: 'guidy:point-ack', id, ok }
292
+ ```
293
+
294
+ Give the elements Guidy should reach a stable `id` and an accessible label
295
+ (`aria-label`, text content, or `title`).
296
+
297
+ ### In-app navigation (routes)
298
+
299
+ Elements are auto-discovered from the DOM; routes are not, so the app declares
300
+ which pages Guidy may send the user to. The host merges them into Guidy's
301
+ navigation tree as deep links and drives them through the existing host→app
302
+ `navigation` message. Declare them statically:
303
+
304
+ ```tsx
305
+ <DocyrusAuthProvider
306
+ apiUrl="..."
307
+ clientId="..."
308
+ enableGuidyBridge
309
+ guidyRoutes={[
310
+ { path: "/leads", label: "Leads" },
311
+ { path: "/leads/new", label: "New Lead" }
312
+ ]}
313
+ >
314
+ <App />
315
+ </DocyrusAuthProvider>
316
+ ```
317
+
318
+ …or dynamically (e.g. when routes depend on permissions) with the hook:
319
+
320
+ ```tsx
321
+ import { useDocyrusGuidyRoutes } from "@kivacore/signin"
322
+
323
+ useDocyrusGuidyRoutes(visibleRoutes) // re-syncs whenever the array changes
324
+ ```
325
+
326
+ Driving a route requires the app to handle inbound host navigation — wire
327
+ `useDocyrusHostNavigation` (or `syncRouteToHost`) so the deep link reaches your
328
+ router. `path` is app-internal (e.g. `/leads`); the host prefixes it with the
329
+ app's mount path.
330
+
331
+ ## App → Host actions
332
+
333
+ Embedded apps can also **initiate** actions against host surfaces — Send to Docy,
334
+ Send to Chat, Send to Email, Send to Calendar, and host-proxied Microsoft Graph.
335
+ Unlike the Guidy bridge (host-driven, opt-in consent), these are app-driven — no
336
+ config flag is needed; the host decides whether to honour each request. They all
337
+ ride the same origin-validated postMessage channel and use a request/response
338
+ correlation (a `requestId` the host echoes back), so the calls are `Promise`s
339
+ that resolve on the host's reply and reject on error or timeout. Available in
340
+ iframe/WebView mode only (outside it, the `sendTo*` methods reject and `msGraph`
341
+ is `null`).
342
+
343
+ ### Send to Docy / Send to Chat
344
+
345
+ Hand a payload to the host AI assistant (**Docy**) or the host **team-chat** app —
346
+ for "Send to Docy" / "Send to Chat" buttons and menu items. Two payload kinds:
347
+ `text` and `adaptiveCard`.
348
+
349
+ ```tsx
350
+ import { useDocyrusSendToDocy, useDocyrusSendToChat } from '@kivacore/signin';
351
+
352
+ function ShareButtons({ record }) {
353
+ const sendToDocy = useDocyrusSendToDocy();
354
+ const sendToChat = useDocyrusSendToChat();
355
+
356
+ return (
357
+ <>
358
+ <button onClick={() => sendToDocy({ kind: 'text', text: `Summarize ${record.name}` })}>
359
+ Send to Docy
360
+ </button>
361
+ <button
362
+ onClick={() =>
363
+ sendToChat({
364
+ kind: 'adaptiveCard',
365
+ card: { type: 'AdaptiveCard', version: '1.5', body: [/* … */] },
366
+ fallbackText: record.name
367
+ })
368
+ }
369
+ >
370
+ Send to Chat
371
+ </button>
372
+ </>
373
+ );
374
+ }
375
+ ```
376
+
377
+ Both resolve when the host acknowledges delivery, so you can show loading /
378
+ success / error UI:
379
+
380
+ ```tsx
381
+ try {
382
+ await sendToDocy({ kind: 'text', text, title });
383
+ toast.success('Sent to Docy');
384
+ } catch (err) {
385
+ toast.error(err.message); // host rejected or timed out
386
+ }
387
+ ```
388
+
389
+ ```text
390
+ App → Host: { type: 'docy:send', requestId, payload } // payload: { kind: 'text' | 'adaptiveCard', … }
391
+ Host → App: { type: 'docy:send-ack', requestId, ok, error? }
392
+ App → Host: { type: 'chat:send', requestId, payload }
393
+ Host → App: { type: 'chat:send-ack', requestId, ok, error? }
394
+ ```
395
+
396
+ ### Send to Email / Send to Calendar
397
+
398
+ Hand a draft **email** or a **calendar event** to the host — for "Send to Email" /
399
+ "Send to Calendar" buttons and menu items. Both resolve when the host
400
+ acknowledges, so you can show loading / success / error UI.
401
+
402
+ ```tsx
403
+ import { useDocyrusSendToEmail, useDocyrusSendToCalendar } from '@kivacore/signin';
404
+
405
+ function RecordActions({ record }) {
406
+ const sendToEmail = useDocyrusSendToEmail();
407
+ const sendToCalendar = useDocyrusSendToCalendar();
408
+
409
+ return (
410
+ <>
411
+ <button
412
+ onClick={() =>
413
+ sendToEmail({
414
+ to: record.ownerEmail, // string | string[]
415
+ cc: ['team@acme.com'],
416
+ subject: `Re: ${record.name}`,
417
+ body: 'Following up on this record.'
418
+ })
419
+ }
420
+ >
421
+ Send to Email
422
+ </button>
423
+ <button
424
+ onClick={() =>
425
+ sendToCalendar({
426
+ subject: `Review: ${record.name}`,
427
+ description: 'Kickoff review',
428
+ participants: record.ownerEmail, // string | string[]
429
+ start: '2026-07-20T09:00:00Z', // ISO 8601
430
+ end: '2026-07-20T09:30:00Z'
431
+ })
432
+ }
433
+ >
434
+ Send to Calendar
435
+ </button>
436
+ </>
437
+ );
438
+ }
439
+ ```
440
+
441
+ `sendToEmail` payload: `{ to, subject, body, cc? }` (`to`/`cc` accept a string
442
+ or string array). `sendToCalendar` payload: `{ subject, start, end,
443
+ description?, participants? }` — `start`/`end` are ISO 8601 datetime strings.
444
+
445
+ ```text
446
+ App → Host: { type: 'email:send', requestId, payload } // { to, subject, body, cc? }
447
+ Host → App: { type: 'email:send-ack', requestId, ok, error? }
448
+ App → Host: { type: 'calendar:send', requestId, payload } // { subject, description?, participants?, start, end }
449
+ Host → App: { type: 'calendar:send-ack', requestId, ok, error? }
450
+ ```
451
+
452
+ ### Microsoft Graph (host MSAL) bridge
453
+
454
+ If the host is signed into Microsoft via MSAL, an embedded app can make Graph
455
+ calls **through the host**. This is **proxy-only**: the app sends
456
+ `{ method, path, body }`, the host acquires the token via MSAL, performs the
457
+ `graph.microsoft.com` request, and returns only `{ ok, status, data }`. **The
458
+ MSAL access token never crosses the frame boundary** — the app cannot read it.
459
+
460
+ ```tsx
461
+ import { useDocyrusMsGraph } from '@kivacore/signin';
462
+
463
+ function GraphPanel() {
464
+ const graph = useDocyrusMsGraph(); // MsGraphClient | null (null outside iframe mode)
465
+
466
+ async function load() {
467
+ if (!graph) return;
468
+
469
+ if (!(await graph.isSignedIn())) {
470
+ // host has no MSAL session — prompt the user in the host, or hide the feature
471
+ return;
472
+ }
473
+
474
+ const me = await graph.getMe(); // GET /me
475
+ const msgs = await graph.get('/me/messages?$top=5');
476
+
477
+ if (me.ok) console.log(me.data);
478
+ }
479
+
480
+ return <button onClick={load} disabled={!graph}>Load from Microsoft</button>;
481
+ }
482
+ ```
483
+
484
+ `MsGraphClient` methods: `status()`, `isSignedIn()`, `request(req)`,
485
+ `get(path, opts?)`, `post(path, body?, opts?)`, `patch(...)`, `put(...)`,
486
+ `delete(...)`, `getMe()`. A completed Graph call resolves even on a non-2xx —
487
+ inspect `ok` / `status` / `data`; the Promise only rejects when the host could
488
+ not perform the request at all (e.g. no MSAL session, timeout).
489
+
490
+ ```text
491
+ App → Host: { type: 'msgraph:status-request', requestId }
492
+ Host → App: { type: 'msgraph:status-response', requestId, signedIn, account?, error? }
493
+ App → Host: { type: 'msgraph:request', requestId, request: { method?, path, headers?, body?, scopes? } }
494
+ Host → App: { type: 'msgraph:response', requestId, ok, status, data?, error? }
495
+ ```
496
+
497
+ > The host implements the listeners for these messages (in its
498
+ > `ExternalAppManager`), importing the exported message/payload types from
499
+ > `@kivacore/signin` to stay in lockstep. It should allowlist which Graph paths
500
+ > embedded apps may reach. See the
501
+ > **[Host App Integration Guide](../../docs/signin-host-app-integration.md)**
502
+ > for the full host-side contract, a reference `ExternalAppManager`, and the
503
+ > MSAL proxy implementation.
504
+
505
+ **Vue** — the same capabilities are on `getDocyrusAuth()`:
506
+ `sendToDocy`, `sendToChat`, `sendToEmail`, `sendToCalendar`, and `msGraph`.
507
+
508
+ ## Hooks / Composables
509
+
510
+ ### useDocyrusAuth()
511
+
512
+ Returns the full authentication context. Available in both React and Vue (`@kivacore/signin/vue`).
513
+
514
+ ```tsx
515
+ const {
516
+ status, // 'loading' | 'authenticated' | 'unauthenticated' | 'error'
517
+ mode, // 'standalone' | 'iframe'
518
+ client, // RestApiClient | null
519
+ tokens, // { accessToken, refreshToken, ... } | null
520
+ user, // DocyrusUser | null (auto-fetched from /v1/users/me)
521
+ signIn, // () => void (redirects to Docyrus login)
522
+ signInWithTokens, // (tokens) => Promise<void> (bootstrap from device flow / external auth)
523
+ getAuthorizationUrl, // () => Promise<string | null> (returns URL without navigating — for Electron)
524
+ signOut, // () => Promise<void>
525
+ hasRole, // (role) => boolean — check if user has a role by slug or uid
526
+ hasPermission, // (operation, scope?) => boolean — check ACL permission (scope: data source id, {appId}/{aiToolId}, or omitted for tenant-wide)
527
+ refreshUser, // () => Promise<void> — re-fetch user from API
528
+ onHostNavigation, // (handler) => () => void — subscribe to host navigation messages (iframe mode)
529
+ onHostNotification, // (handler) => () => void — subscribe to host notification messages (iframe mode)
530
+ enableHostRouteSync, // () => void — patch history + fire `route-change` on every change (iframe mode)
531
+ notifyRouteChange, // (payload?) => void — post a single `route-change` to the host (iframe mode)
532
+ requestHostNavigation, // (url, options?) => void — ask the host shell to navigate (iframe mode)
533
+ sendToDocy, // (payload) => Promise<void> — hand a payload to the host AI assistant (iframe mode)
534
+ sendToChat, // (payload) => Promise<void> — hand a payload to the host team-chat app (iframe mode)
535
+ sendToEmail, // (payload) => Promise<void> — hand a draft email to the host (iframe mode)
536
+ sendToCalendar, // (payload) => Promise<void> — hand a calendar event to the host (iframe mode)
537
+ msGraph, // MsGraphClient | null — host-proxied Microsoft Graph client (iframe mode)
538
+ error // Error | null
539
+ } = useDocyrusAuth();
540
+ ```
541
+
542
+ ### useDocyrusSendToDocy() / useDocyrusSendToChat() / useDocyrusSendToEmail() / useDocyrusSendToCalendar() / useDocyrusMsGraph()
543
+
544
+ React-only convenience hooks for the app→host actions above. See
545
+ [App → Host actions](#app--host-actions).
546
+
547
+ ### useDocyrusHostNavigation() / useDocyrusHostNotification()
548
+
549
+ React-only convenience hooks for subscribing to host postMessage events
550
+ from within an embedded iframe/WebView. Both subscribe on mount and
551
+ unsubscribe on unmount; the latest closure is always invoked so the
552
+ handler does not need to be memoized. No-op outside iframe mode.
553
+
554
+ ```tsx
555
+ import {
556
+ useDocyrusHostNavigation,
557
+ useDocyrusHostNotification,
558
+ type DocyrusNotification
559
+ } from '@kivacore/signin';
560
+
561
+ useDocyrusHostNavigation(({ url }) => {
562
+ navigate(url);
563
+ });
564
+
565
+ useDocyrusHostNotification((notification: DocyrusNotification) => {
566
+ showToast(notification.subject, notification.message);
567
+ });
568
+ ```
569
+
570
+ ### useDocyrusClient()
571
+
572
+ Shorthand hook/composable that returns just the API client:
573
+
574
+ ```tsx
575
+ const client = useDocyrusClient(); // RestApiClient | null
576
+
577
+ if (client) {
578
+ const response = await client.get('/v1/users/me');
579
+ }
580
+ ```
581
+
582
+ ## Components
583
+
584
+ ### SignInButton
585
+
586
+ Unstyled button that triggers sign-in. Automatically hidden when authenticated or in iframe mode. Available in both React and Vue.
587
+
588
+ **React:**
589
+ ```tsx
590
+ // Basic
591
+ <SignInButton />
592
+
593
+ // With custom styling
594
+ <SignInButton className="btn btn-primary" label="Log in with Docyrus" />
595
+
596
+ // Render prop for full customization
597
+ <SignInButton>
598
+ {({ signIn, isLoading }) => (
599
+ <button onClick={signIn} disabled={isLoading}>
600
+ {isLoading ? 'Redirecting...' : 'Sign in'}
601
+ </button>
602
+ )}
603
+ </SignInButton>
604
+ ```
605
+
606
+ **Vue:**
607
+ ```vue
608
+ <!-- Basic -->
609
+ <SignInButton />
610
+
611
+ <!-- With custom styling -->
612
+ <SignInButton label="Login" class="btn-primary" />
613
+
614
+ <!-- Scoped slot for custom rendering -->
615
+ <SignInButton v-slot="{ signIn, status }">
616
+ <MyCustomButton @click="signIn" :loading="status === 'loading'" />
617
+ </SignInButton>
618
+ ```
619
+
620
+ ## Electron Token Storage
621
+
622
+ `ElectronTokenStorage` stores OAuth2 tokens via IPC bridge to the Electron main process. Falls back to localStorage if the Electron API is not available.
623
+
624
+ ```tsx
625
+ import { ElectronTokenStorage } from '@kivacore/signin/electron';
626
+
627
+ // Auto-detects window.electronAPI
628
+ const storage = new ElectronTokenStorage();
629
+
630
+ // Or pass a custom IPC bridge
631
+ const storage = new ElectronTokenStorage(myElectronAPI);
632
+
633
+ // Custom key prefix
634
+ const storage = new ElectronTokenStorage(undefined, 'my_app_oauth2');
635
+ ```
636
+
637
+ The Electron preload script must expose `storeGet`, `storeSet`, and `storeDelete` IPC methods via `contextBridge`.
638
+
639
+ ## Bootstrap From Existing Tokens
640
+
641
+ If you already have Docyrus `accessToken` and `refreshToken` from another flow such as device authorization, you can start a web session without redirecting through the browser login flow again.
642
+
643
+ The simplest option is `initialTokens`:
644
+
645
+ ```tsx
646
+ <DocyrusAuthProvider
647
+ apiUrl="https://alpha-api.docyrus.com"
648
+ clientId="your-oauth2-client-id"
649
+ initialTokens={deviceFlowTokens}
650
+ forceMode="standalone">
651
+ <App />
652
+ </DocyrusAuthProvider>
653
+ ```
654
+
655
+ Or bootstrap later with `signInWithTokens()`:
656
+
657
+ ```tsx
658
+ import { useEffect } from 'react';
659
+ import { useDocyrusAuth } from '@kivacore/signin';
660
+
661
+ function TokenHandoff({ deviceFlowTokens }) {
662
+ const { signInWithTokens } = useDocyrusAuth();
663
+
664
+ useEffect(() => {
665
+ if (!deviceFlowTokens) return;
666
+ signInWithTokens(deviceFlowTokens).catch(console.error);
667
+ }, [deviceFlowTokens, signInWithTokens]);
668
+
669
+ return null;
670
+ }
671
+ ```
672
+
673
+ `@kivacore/signin` will persist those tokens into its configured storage, create the authenticated API client, and continue normal refresh-token handling. In iframe mode this bootstrap path is intentionally unsupported; use the host `postMessage` signin flow instead.
674
+
675
+ ## Auth Modes
676
+
677
+ ### Standalone Mode (OAuth2 PKCE)
678
+
679
+ Used when the app runs directly in the browser (not in an iframe). The flow:
680
+
681
+ 1. User clicks sign-in
682
+ 2. Page redirects to Docyrus authorization endpoint
683
+ 3. After login, redirects back with authorization code
684
+ 4. Provider automatically exchanges code for tokens
685
+ 5. Tokens stored in localStorage (or custom `tokenStorage`), auto-refreshed before expiry
686
+
687
+ ### Iframe Mode (postMessage)
688
+
689
+ Used when the app is embedded in an iframe on `*.docyrus.app`. The flow:
690
+
691
+ 1. Provider detects iframe environment and validates host origin
692
+ 2. Host sends `{ type: 'signin', accessToken, refreshToken }` via `postMessage`
693
+ 3. Provider creates API client with received tokens
694
+ 4. When tokens expire, provider sends `{ type: 'token-refresh-request' }` to host
695
+ 5. Host responds with fresh tokens
696
+
697
+ #### Backend URL at startup
698
+
699
+ The shell can include its API base URL in the iframe URL, for example
700
+ `?embedded=true&apiUrl=http%3A%2F%2Flocalhost%3A3000`. Sign-in reads it once
701
+ when the app starts and uses it for the API client, SSO exchange, and any OAuth
702
+ refresh performed by the app. Iframe token refresh still asks the host for new
703
+ tokens over postMessage.
704
+
705
+ The accepted hosts are `localhost`, `127.0.0.1`, and `[::1]` over HTTP or HTTPS
706
+ on any port, and `docyrus.com`, `attornaid.com`, and their subdomains over HTTPS.
707
+ Supply a base URL without credentials, a query, or a fragment. Apps opened
708
+ without `embedded=true` and embedded apps whose URL omits `apiUrl` use the
709
+ provider's configured `apiUrl` or the default `https://alpha-api.docyrus.com`.
710
+
711
+ An invalid host URL sets `status` to `'error'` and `error.message` to
712
+ `'invalid-host-api-url'`. Authentication and API requests are blocked, and the
713
+ provider displays an error message in place of the app. To customize that
714
+ message, pass `renderAuthError={(error) => …}` to the React provider or supply
715
+ the Vue provider's `#error="{ error }"` slot.
716
+
717
+ The host may post `signin` as often as it likes. Only a new session — the
718
+ first token, or one for a different user/tenant — creates a new `client` and
719
+ re-fetches the user. Repeats of the current token are ignored, and refreshed
720
+ tokens for the same session just update `tokens`, so `client` keeps its
721
+ identity and anything keyed on it (query caches, inventory) stays warm. Two
722
+ tokens belong to the same session when their JWT payloads match apart from
723
+ `exp`, `iat`, `nbf` and `jti`; a token that isn't a decodable JWT always counts
724
+ as a new session. Proactive refreshes are spaced at least 10s apart, so a host
725
+ that answers with a token still inside the 60s expiry buffer can't cause a
726
+ refresh loop.
727
+
728
+ In addition to auth messages, the host may push two side-channel messages
729
+ that the embedded app can subscribe to:
730
+
731
+ | Message | Payload | Purpose |
732
+ |---------|---------|---------|
733
+ | `{ type: 'navigation', url }` | `url: string` | Host asks the app to navigate (e.g. deep-link from a host menu) |
734
+ | `{ type: 'notification', notification }` | `DocyrusNotification` | Host pushes a notification to the embedded app |
735
+
736
+ The embedded app can also **initiate** app→host actions over the same channel —
737
+ Send to Docy, Send to Chat, and host-proxied Microsoft Graph calls. See
738
+ [App → Host actions](#app--host-actions).
739
+
740
+ **React** — register handlers with the provided hooks (latest closure is
741
+ always invoked, no need to memoize):
742
+
743
+ ```tsx
744
+ import {
745
+ useDocyrusHostNavigation,
746
+ useDocyrusHostNotification
747
+ } from '@kivacore/signin';
748
+
749
+ function Shell() {
750
+ const navigate = useNavigate();
751
+
752
+ useDocyrusHostNavigation(({ url }) => {
753
+ navigate(url);
754
+ });
755
+
756
+ useDocyrusHostNotification((notification) => {
757
+ toast({
758
+ title: notification.subject,
759
+ description: notification.message
760
+ });
761
+ });
762
+
763
+ return <Routes />;
764
+ }
765
+ ```
766
+
767
+ **Vue** — register handlers via the composable; both return an
768
+ unsubscribe function:
769
+
770
+ ```vue
771
+ <script setup lang="ts">
772
+ import { onMounted, onUnmounted } from 'vue';
773
+ import { getDocyrusAuth } from '@kivacore/signin/vue';
774
+
775
+ const auth = getDocyrusAuth();
776
+ let stopNav: (() => void) | undefined;
777
+ let stopNote: (() => void) | undefined;
778
+
779
+ onMounted(() => {
780
+ stopNav = auth.onHostNavigation(({ url }) => {
781
+ router.push(url);
782
+ });
783
+ stopNote = auth.onHostNotification((notification) => {
784
+ toast.show(notification.subject, notification.message);
785
+ });
786
+ });
787
+
788
+ onUnmounted(() => {
789
+ stopNav?.();
790
+ stopNote?.();
791
+ });
792
+ </script>
793
+ ```
794
+
795
+ Both subscriptions are no-ops outside iframe/WebView mode, so handlers
796
+ are safe to register unconditionally.
797
+
798
+ #### Route → Host sync (address bar reflection)
799
+
800
+ When the embedded app is inside a host shell, the shell often wants its
801
+ own browser address bar to reflect the app's current route (so users can
802
+ copy/share/bookmark URLs). The embedded app reports route changes with:
803
+
804
+ ```
805
+ App → Host: { type: 'route-change', path, search, hash, url }
806
+ ```
807
+
808
+ The simplest setup — pass `syncRouteToHost` to the provider. It patches
809
+ `history.pushState/replaceState` and listens for `popstate`/`hashchange`,
810
+ so every route change in the embedded app — regardless of router
811
+ (React Router, TanStack Router, Next, plain history) — posts a message:
812
+
813
+ ```tsx
814
+ <DocyrusAuthProvider apiUrl="..." clientId="..." syncRouteToHost>
815
+ <App />
816
+ </DocyrusAuthProvider>
817
+ ```
818
+
819
+ Or opt in scoped to a component with the hook:
820
+
821
+ ```tsx
822
+ import { useDocyrusHostRouteSync } from '@kivacore/signin';
823
+
824
+ function Shell() {
825
+ useDocyrusHostRouteSync();
826
+ return <Routes />;
827
+ }
828
+ ```
829
+
830
+ Or report routes manually from a router subscription (avoids history
831
+ patching, lets the router be the source of truth):
832
+
833
+ ```tsx
834
+ import { useDocyrusAuth } from '@kivacore/signin';
835
+
836
+ function RouteReporter() {
837
+ const { notifyRouteChange } = useDocyrusAuth();
838
+ const location = useLocation(); // React Router / TanStack Router / etc.
839
+
840
+ useEffect(() => {
841
+ notifyRouteChange({
842
+ path: location.pathname,
843
+ search: location.search,
844
+ hash: location.hash
845
+ });
846
+ }, [location, notifyRouteChange]);
847
+
848
+ return null;
849
+ }
850
+ ```
851
+
852
+ All three are no-ops outside iframe/WebView mode.
853
+
854
+ #### App → Host navigation request
855
+
856
+ The host can ask the app to navigate (`{ type: 'navigation' }`, above). The
857
+ reverse direction lets the embedded app ask the **host shell** to navigate —
858
+ for example, a button inside the app that should deep-link the host, switch the
859
+ host view, or open a sibling app. The app posts:
860
+
861
+ ```
862
+ App → Host: { type: 'navigation-request', url, replace?, newTab? }
863
+ ```
864
+
865
+ The host decides how to honour the request (push/replace its own router, open a
866
+ new tab, etc.). Unlike `route-change` — which passively reports where the app
867
+ already is — this is an explicit request to move the host.
868
+
869
+ **React** — call `requestHostNavigation` from `useDocyrusAuth()`, or use the
870
+ `useDocyrusRequestHostNavigation` convenience hook:
871
+
872
+ ```tsx
873
+ import { useDocyrusRequestHostNavigation } from '@kivacore/signin';
874
+
875
+ function OpenSettingsButton() {
876
+ const requestHostNavigation = useDocyrusRequestHostNavigation();
877
+
878
+ return (
879
+ <button onClick={() => requestHostNavigation('/settings/billing')}>
880
+ Go to billing
881
+ </button>
882
+ );
883
+ }
884
+ ```
885
+
886
+ ```tsx
887
+ // With options
888
+ const { requestHostNavigation } = useDocyrusAuth();
889
+
890
+ requestHostNavigation('/reports/q3', { replace: true });
891
+ requestHostNavigation('https://docs.docyrus.com', { newTab: true });
892
+ ```
893
+
894
+ **Vue** — call `requestHostNavigation` from the composable:
895
+
896
+ ```vue
897
+ <script setup lang="ts">
898
+ import { getDocyrusAuth } from '@kivacore/signin/vue';
899
+
900
+ const auth = getDocyrusAuth();
901
+
902
+ function goToBilling() {
903
+ auth.requestHostNavigation('/settings/billing');
904
+ }
905
+ </script>
906
+ ```
907
+
908
+ No-op outside iframe/WebView mode.
909
+
910
+ ## SSR Support (Next.js)
911
+
912
+ Enable `ssr` on the client-side provider to sync the access token to a cookie. The cookie is written with `max-age` (matching the token lifetime) and `Secure` flag (on HTTPS origins) automatically.
913
+
914
+ ### 1. Client — Enable SSR in AuthProvider
915
+
916
+ ```tsx
917
+ <DocyrusAuthProvider
918
+ apiUrl="https://alpha-api.docyrus.com"
919
+ clientId="your-oauth2-client-id"
920
+ scopes={['offline_access', 'Read.All', 'Users.Read']}
921
+ callbackPath="/auth/callback"
922
+ ssr>
923
+ {children}
924
+ </DocyrusAuthProvider>
925
+ ```
926
+
927
+ The cookie is automatically **set** on login and token refresh, **cleared** on sign out, and **expires** with the token (via `max-age`).
928
+
929
+ ### 2. Middleware — Route Protection
930
+
931
+ Use the pre-built `authMiddleware` for automatic route protection:
932
+
933
+ ```ts
934
+ // middleware.ts
935
+ import { authMiddleware } from '@kivacore/signin/nextjs';
936
+
937
+ export default authMiddleware({
938
+ publicRoutes: ['/login', '/callback'],
939
+ loginPath: '/login',
940
+ });
941
+
942
+ export const config = {
943
+ matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)'],
944
+ };
945
+ ```
946
+
947
+ Or use `getMiddlewareSession` for custom middleware logic:
948
+
949
+ ```ts
950
+ // middleware.ts
951
+ import { NextResponse, type NextRequest } from 'next/server';
952
+ import { getMiddlewareSession } from '@kivacore/signin/nextjs';
953
+
954
+ export function middleware(request: NextRequest) {
955
+ const session = getMiddlewareSession(request);
956
+ if (!session.isAuthenticated && request.nextUrl.pathname.startsWith('/dashboard')) {
957
+ return NextResponse.redirect(new URL('/login', request.url));
958
+ }
959
+ return NextResponse.next();
960
+ }
961
+ ```
962
+
963
+ ### 3. Server Components — Authenticated API Calls
964
+
965
+ ```tsx
966
+ import { cookies } from 'next/headers';
967
+ import { createServerClient, getSession } from '@kivacore/signin/nextjs';
968
+ import { redirect } from 'next/navigation';
969
+
970
+ export default async function DashboardPage() {
971
+ const cookieStore = await cookies();
972
+ const session = getSession(cookieStore);
973
+ if (!session.isAuthenticated) redirect('/login');
974
+
975
+ const client = createServerClient(cookieStore);
976
+ const { data: user } = await client.get('/v1/users/me');
977
+ return <div>Welcome, {user.name}</div>;
978
+ }
979
+ ```
980
+
981
+ ### 4. Server Actions
982
+
983
+ ```ts
984
+ 'use server';
985
+ import { cookies } from 'next/headers';
986
+ import { createServerClient } from '@kivacore/signin/nextjs';
987
+
988
+ export async function getUser() {
989
+ const client = createServerClient(await cookies());
990
+ return client.get('/v1/users/me');
991
+ }
992
+ ```
993
+
994
+ ### Next.js SSR API Reference
995
+
996
+ | Function | Import | Usage |
997
+ |----------|--------|-------|
998
+ | `getSession(cookies)` | `@kivacore/signin/nextjs` | Read auth session in server components/actions |
999
+ | `createServerClient(cookies)` | `@kivacore/signin/nextjs` | Create authenticated `RestApiClient` on server |
1000
+ | `authMiddleware(config)` | `@kivacore/signin/nextjs` | Pre-built route protection middleware |
1001
+ | `getMiddlewareSession(request)` | `@kivacore/signin/nextjs` | Read auth session in custom middleware |
1002
+ | `createMiddlewareClient(request)` | `@kivacore/signin/nextjs` | Create authenticated client in middleware |
1003
+
1004
+ ### Cookie Behavior
1005
+
1006
+ | Attribute | Value | Reason |
1007
+ |-----------|-------|--------|
1008
+ | `path` | `/` | Available to all routes |
1009
+ | `SameSite` | `Lax` | Sent on same-site navigations |
1010
+ | `Secure` | Auto (`https:` only) | Only sent over HTTPS in production |
1011
+ | `max-age` | Token lifetime (seconds) | Expires with the token, survives browser restart |
1012
+ | `httpOnly` | No | Client-side auth provider must read/write it |
1013
+
1014
+ ### Cookie Helper (Client-Side)
1015
+
1016
+ ```tsx
1017
+ import { getTokenFromCookie } from '@kivacore/signin';
1018
+
1019
+ const token = getTokenFromCookie(); // reads 'docyrus-token' cookie
1020
+ const token = getTokenFromCookie('custom-key'); // custom cookie name
1021
+ ```
1022
+
1023
+ ## Authorization (Roles & Permissions)
1024
+
1025
+ The provider auto-fetches the current user from `/v1/users/me` after authentication and exposes `hasRole` and `hasPermission` helpers.
1026
+
1027
+ ### Via Hooks (React / React Native)
1028
+
1029
+ ```tsx
1030
+ function DataSourceView({ dataSourceId }: { dataSourceId: string }) {
1031
+ const { user, hasRole, hasPermission } = useDocyrusAuth();
1032
+
1033
+ if (!user) return <div>Loading user...</div>;
1034
+
1035
+ // Check role by slug or uid
1036
+ if (hasRole('super_admin')) {
1037
+ return <AdminPanel />;
1038
+ }
1039
+
1040
+ // Check data source permission
1041
+ const canEdit = hasPermission('edit', dataSourceId);
1042
+ const canDelete = hasPermission('delete', dataSourceId);
1043
+
1044
+ // Check a tenant-wide operation — no entity to scope it to
1045
+ const canUseAi = hasPermission('ai-access');
1046
+
1047
+ // Check an app / AI tool operation
1048
+ const canOpenApp = hasPermission('app_access', { appId });
1049
+
1050
+ // Check multiple roles
1051
+ if (hasRole(['editor', 'reviewer'])) {
1052
+ return <EditorView canEdit={canEdit} canDelete={canDelete} />;
1053
+ }
1054
+
1055
+ return <ReadOnlyView />;
1056
+ }
1057
+ ```
1058
+
1059
+ ### Via Pure Functions (Framework-Agnostic)
1060
+
1061
+ ```tsx
1062
+ import { hasRole, hasPermission, getAllowedOperations } from '@kivacore/signin/core';
1063
+ import type { DocyrusUser } from '@kivacore/signin/core';
1064
+
1065
+ function checkAccess(user: DocyrusUser) {
1066
+ // hasRole returns true when role arg is null/undefined (no requirement)
1067
+ hasRole(user, null); // true
1068
+ hasRole(user, 'super_admin'); // checks slug or uid
1069
+ hasRole(user, ['editor', 'viewer']); // any match
1070
+
1071
+ // hasPermission checks: super_admin → global_editor → global_viewer → always-permitted → rules
1072
+ hasPermission(user, 'view', 'some-ds-id');
1073
+ hasPermission(user, 'edit', 'some-ds-id');
1074
+
1075
+ // Everything the user may do within a scope
1076
+ getAllowedOperations(user, 'some-ds-id'); // ['view', 'edit', ...]
1077
+ getAllowedOperations(user); // tenant-wide: ['ai-access', 'manage_users', ...]
1078
+ }
1079
+ ```
1080
+
1081
+ ### Permission Scopes
1082
+
1083
+ `hasPermission` and `getAllowedOperations` take an optional scope as their last
1084
+ positional argument. What you pass decides which ACL target type answers the
1085
+ check:
1086
+
1087
+ | Scope argument | Target type | Example operations |
1088
+ | --- | --- | --- |
1089
+ | `'ds-id'` or `{ dataSourceId }` | `data_source` | `view`, `create`, `edit`, `delete`, `export`, `print` |
1090
+ | `{ appId }` | `app` | `app_access` |
1091
+ | `{ aiToolId }` | `ai_tool` | `allow` |
1092
+ | omitted / `null` | `ai`, `settings`, `devtools` | `ai-access`, `manage_users`, `studio`, `automations` |
1093
+
1094
+ Pass `{ targetType }` alongside an id to pin the check to a single target type
1095
+ (for example `{ dataSourceId, targetType: 'field' }` to read field
1096
+ restrictions, which are never treated as grants otherwise).
1097
+
1098
+ ```tsx
1099
+ // Tenant-wide capabilities carry no entity id
1100
+ hasPermission(user, 'ai-access');
1101
+ hasPermission(user, 'manage_users');
1102
+
1103
+ // Entity-scoped, but not a data source
1104
+ hasPermission(user, 'app_access', { appId });
1105
+ hasPermission(user, 'allow', { aiToolId });
1106
+ ```
1107
+
1108
+ ### Permission Resolution Order
1109
+
1110
+ 1. `super_admin` role → always granted
1111
+ 2. `global_editor` role + data source scope → granted for: view, create, edit, delete, create_bulk, export, import, print
1112
+ 3. `global_viewer` role + data source scope → granted only for: view
1113
+ 4. Always-permitted system data sources (reports, todos, notes, etc.)
1114
+ 5. The user's rules for the scope — `permissions` when the API returns it, otherwise the legacy `aclRules` array (both merged from all roles by the server)
1115
+
1116
+ > `permissions` is the target-type-aware shape (`{ targetType, dataSourceId?,
1117
+ > appId?, aiToolId?, allowedOperations }`). The older `aclRules` shape is keyed
1118
+ > by data source alone, so it collapses every entity-less rule into a single
1119
+ > null-keyed entry and cannot answer app or AI tool scopes; it is used only when
1120
+ > `permissions` is absent.
1121
+
1122
+ ### Refreshing User Data
1123
+
1124
+ If roles or permissions change while the app is running:
1125
+
1126
+ ```tsx
1127
+ const { refreshUser } = useDocyrusAuth();
1128
+
1129
+ // After a role change
1130
+ await refreshUser();
1131
+ ```
1132
+
1133
+ ## Advanced Usage
1134
+
1135
+ ### Core (Framework-Agnostic)
1136
+
1137
+ Core classes are exported for advanced use cases without any framework dependency:
1138
+
1139
+ ```tsx
1140
+ import {
1141
+ AuthManager,
1142
+ StandaloneOAuth2Auth,
1143
+ IframeAuth,
1144
+ detectAuthMode,
1145
+ } from '@kivacore/signin/core';
1146
+ ```
1147
+
1148
+ ### React Entrypoint
1149
+
1150
+ ```tsx
1151
+ import {
1152
+ DocyrusAuthProvider,
1153
+ useDocyrusAuth,
1154
+ useDocyrusClient,
1155
+ SignInButton,
1156
+ AuthManager,
1157
+ detectAuthMode
1158
+ } from '@kivacore/signin';
1159
+ ```
1160
+
1161
+ ### Vue Entrypoint
1162
+
1163
+ ```tsx
1164
+ import {
1165
+ DocyrusAuthProvider,
1166
+ useDocyrusAuth,
1167
+ useDocyrusClient,
1168
+ SignInButton
1169
+ } from '@kivacore/signin/vue';
1170
+ ```
1171
+
1172
+ ## Development
1173
+
1174
+ ```bash
1175
+ # Install dependencies
1176
+ pnpm install
1177
+
1178
+ # Development mode with watch
1179
+ pnpm dev
1180
+
1181
+ # Build the package
1182
+ pnpm build
1183
+
1184
+ # Run linting
1185
+ pnpm lint
1186
+
1187
+ # Type checking
1188
+ pnpm typecheck
1189
+ ```
1190
+
1191
+ ## License
1192
+
1193
+ MIT