@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.
@@ -0,0 +1,271 @@
1
+ import { OAuth2Tokens, RestApiClient } from '@kivacore/api-client';
2
+ import { D as DocyrusAuthConfig, c as AuthMode, e as AuthStatus, o as DocyrusUser, G as GuidyRoute, R as RouteChangePayload, w as HostNavigationRequestOptions, m as DocyrusSharePayload, i as DocyrusEmailPayload, h as DocyrusCalendarEventPayload, p as MsGraphClient, H as HostNavigationHandler, v as HostNotificationHandler, k as DocyrusRole, u as PermissionScope, P as PermissionConfig } from './types-DmIgZa_v.js';
3
+
4
+ type AuthStateListener = (state: {
5
+ status: AuthStatus;
6
+ tokens: OAuth2Tokens | null;
7
+ error: Error | null;
8
+ user: DocyrusUser | null;
9
+ }) => void;
10
+ /**
11
+ * Unified authentication manager.
12
+ * Orchestrates standalone OAuth2 and iframe postMessage modes,
13
+ * exposes a pre-configured RestApiClient, and manages token lifecycle.
14
+ */
15
+ declare class AuthManager {
16
+ private mode;
17
+ private status;
18
+ private tokens;
19
+ private error;
20
+ private client;
21
+ private user;
22
+ /** In-flight `/v1/users/me` request, tied to the client that issued it. */
23
+ private userFetch;
24
+ private standaloneAuth;
25
+ private iframeAuth;
26
+ private guidyBridge;
27
+ private msGraphClient;
28
+ private reactNativeAuth;
29
+ private tokenRefreshTimer;
30
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
31
+ private lastScheduledRefreshAt;
32
+ /** Session the current client was created for — see `getJwtSessionKey`. */
33
+ private sessionKey;
34
+ /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
35
+ private refreshInFlight;
36
+ private listeners;
37
+ private navigationHandlers;
38
+ private notificationHandlers;
39
+ private config;
40
+ constructor(config?: DocyrusAuthConfig);
41
+ /** Whether the provider may refresh tokens on its own. Default: true. */
42
+ private get autoRefreshEnabled();
43
+ getMode(): AuthMode;
44
+ getStatus(): AuthStatus;
45
+ getTokens(): OAuth2Tokens | null;
46
+ getClient(): RestApiClient | null;
47
+ getError(): Error | null;
48
+ getUser(): DocyrusUser | null;
49
+ /** Re-fetch the current user from the API. No-op if not authenticated. */
50
+ refreshUser(): Promise<void>;
51
+ subscribe(listener: AuthStateListener): () => void;
52
+ private notify;
53
+ private getInitialTokens;
54
+ /** Initialize the auth manager. Must be called once on mount. */
55
+ initialize(): Promise<void>;
56
+ /**
57
+ * Standalone mode initialization.
58
+ * 1. Check if we're returning from an OAuth callback.
59
+ * 2. If not, check for existing tokens in localStorage.
60
+ * 3. If tokens are expired, try to refresh.
61
+ */
62
+ private initializeStandaloneMode;
63
+ /**
64
+ * Iframe mode initialization.
65
+ * Listen for postMessage tokens from the host.
66
+ * Status remains 'loading' until the host sends the first signin message.
67
+ */
68
+ private initializeIframeMode;
69
+ /**
70
+ * Start the Guidy bridge runtime: report the app's clickable inventory to
71
+ * the host and execute host scan/point/click commands. Iframe mode only.
72
+ */
73
+ private startGuidyBridge;
74
+ /**
75
+ * Iframe mode: replace the routes the Guidy bridge advertises to the host.
76
+ * No-op unless the bridge is running (`enableGuidyBridge`).
77
+ */
78
+ setGuidyRoutes(routes: GuidyRoute[]): void;
79
+ /**
80
+ * Iframe/WebView mode: start auto-syncing the embedded app's route
81
+ * to the host. Patches history methods and listens for popstate /
82
+ * hashchange. Idempotent. No-op outside iframe mode.
83
+ */
84
+ enableHostRouteSync(): void;
85
+ /**
86
+ * Iframe/WebView mode: post a single `route-change` message to the
87
+ * host. With no argument, reads `window.location`. Pass a payload
88
+ * from a router subscription to report a known route. No-op outside
89
+ * iframe mode.
90
+ */
91
+ notifyHostRouteChange(payload?: RouteChangePayload): void;
92
+ /**
93
+ * Iframe/WebView mode: ask the host shell to navigate to a path/URL.
94
+ * Posts a `navigation-request` message; the host decides how to honour it.
95
+ * No-op outside iframe mode.
96
+ */
97
+ requestHostNavigation(url: string, options?: HostNavigationRequestOptions): void;
98
+ /**
99
+ * Iframe/WebView mode: hand a payload to the host AI assistant (Docy).
100
+ * Resolves when the host acknowledges delivery. Rejects outside iframe mode.
101
+ */
102
+ sendToDocy(payload: DocyrusSharePayload): Promise<void>;
103
+ /**
104
+ * Iframe/WebView mode: hand a payload to the host team-chat app.
105
+ * Resolves when the host acknowledges delivery. Rejects outside iframe mode.
106
+ */
107
+ sendToChat(payload: DocyrusSharePayload): Promise<void>;
108
+ /**
109
+ * Iframe/WebView mode: hand a draft email to the host. Resolves when the
110
+ * host acknowledges. Rejects outside iframe mode.
111
+ */
112
+ sendToEmail(payload: DocyrusEmailPayload): Promise<void>;
113
+ /**
114
+ * Iframe/WebView mode: hand a calendar event to the host. Resolves when the
115
+ * host acknowledges. Rejects outside iframe mode.
116
+ */
117
+ sendToCalendar(payload: DocyrusCalendarEventPayload): Promise<void>;
118
+ /**
119
+ * Iframe/WebView mode: get the client for the host's Microsoft Graph (MSAL)
120
+ * session. Returns `null` outside iframe mode.
121
+ */
122
+ getMsGraphClient(): MsGraphClient | null;
123
+ /**
124
+ * Subscribe to host `navigation` messages. Returns an unsubscribe function.
125
+ * Handlers registered before iframe mode is initialized are retained and
126
+ * will fire once messages arrive. No-op in non-iframe modes.
127
+ */
128
+ onHostNavigation(handler: HostNavigationHandler): () => void;
129
+ /**
130
+ * Subscribe to host `notification` messages. Returns an unsubscribe function.
131
+ * Handlers registered before iframe mode is initialized are retained and
132
+ * will fire once messages arrive. No-op in non-iframe modes.
133
+ */
134
+ onHostNotification(handler: HostNotificationHandler): () => void;
135
+ /**
136
+ * React Native mode initialization.
137
+ * No callback URL check needed — the in-app browser returns the URL directly.
138
+ * Just check for existing tokens and refresh if expired.
139
+ */
140
+ private initializeReactNativeMode;
141
+ /** Initiate sign-in. Works in standalone and react-native modes. */
142
+ signIn(): Promise<void>;
143
+ /**
144
+ * Bootstrap an authenticated session from tokens obtained outside the
145
+ * browser redirect flow, such as a prior device authorization flow.
146
+ */
147
+ signInWithTokens(tokens: OAuth2Tokens): Promise<void>;
148
+ /**
149
+ * Get the OAuth2 authorization URL without navigating.
150
+ * Use this in Electron apps to open the URL in an external browser.
151
+ * Returns null if not in standalone mode.
152
+ */
153
+ getAuthorizationUrl(): Promise<string | null>;
154
+ /**
155
+ * Sign out.
156
+ * Standalone: revoke token, clear localStorage, reset state.
157
+ * Iframe: clear local state (host manages the actual session).
158
+ */
159
+ signOut(): Promise<void>;
160
+ /**
161
+ * Called when valid tokens are received (any mode). In iframe mode that is
162
+ * every host `signin` message — the first sign-in, the host's answer to each
163
+ * `token-refresh-request`, and repeats of a token we already hold (the host
164
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
165
+ *
166
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
167
+ * refreshed token needs no new client. A new client — plus a user fetch —
168
+ * is reserved for a new session (first sign-in, or the host switching user
169
+ * or tenant): consumers key caches on client identity, so a fresh instance
170
+ * makes them reload everything.
171
+ *
172
+ * On a new session the first notify() fires with user: null, and a second
173
+ * one fires once the user is fetched.
174
+ */
175
+ private setAuthenticated;
176
+ /**
177
+ * Fetch the current user from /v1/users/me. Silently sets user to null on failure.
178
+ *
179
+ * Concurrent calls share one request: `setAuthenticated` fetches whenever the
180
+ * user is still missing, so a second token push that lands while the first
181
+ * fetch is in flight (e.g. stored tokens restored on load, then the host or a
182
+ * bridge pushing its session) would otherwise fire a duplicate request. A
183
+ * result is dropped if the client changed meanwhile (sign-out or a new
184
+ * session), so a stale user never overwrites the current one.
185
+ */
186
+ private fetchUser;
187
+ /**
188
+ * Create a RestApiClient with a custom TokenManager that proactively
189
+ * refreshes the token in getToken(). This is necessary because
190
+ * BaseApiClient.getAccessToken() only calls tokenManager.getToken()
191
+ * and does NOT auto-call refreshToken() when the token is expired.
192
+ */
193
+ private createClient;
194
+ /**
195
+ * Get a valid access token, proactively refreshing if expired.
196
+ * Called by the RestApiClient on every request via tokenManager.getToken().
197
+ */
198
+ private getValidToken;
199
+ /**
200
+ * Handle token refresh depending on mode, sharing a single in-flight
201
+ * request across concurrent callers. Multiple requests crossing the expiry
202
+ * buffer at once (e.g. a dashboard firing several queries) would otherwise
203
+ * each trigger their own refresh; with refresh-token rotation only the first
204
+ * succeeds and the rest can leave us holding an expired token — exactly the
205
+ * backend "JWTExpired" the proactive path is meant to prevent.
206
+ */
207
+ private handleTokenRefresh;
208
+ /**
209
+ * Refresh depending on mode.
210
+ * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
211
+ * Iframe: send postMessage to host requesting new tokens.
212
+ */
213
+ private performTokenRefresh;
214
+ /** Schedule proactive token refresh before expiry. */
215
+ private scheduleTokenRefresh;
216
+ private clearTokenRefreshTimer;
217
+ /**
218
+ * Resolve token expiry from stored expiresAt, falling back to the JWT exp
219
+ * claim when expiresAt is absent (e.g. server omitted expires_in).
220
+ */
221
+ private resolveExpiry;
222
+ /** Cleanup: remove listeners, timers, stop iframe auth. */
223
+ destroy(): void;
224
+ }
225
+
226
+ /**
227
+ * Get all roles for a user (primaryRole + roles array), deduplicated by uid.
228
+ */
229
+ declare function getAllRoles(user: DocyrusUser | null | undefined): DocyrusRole[];
230
+ /**
231
+ * Check if the user has a specific role.
232
+ *
233
+ * - If `role` is null/undefined, returns true (no role requirement).
234
+ * - Checks both primaryRole and roles array.
235
+ * - Matches by slug or uid.
236
+ */
237
+ declare function hasRole(user: DocyrusUser | null | undefined, role: string | string[] | null | undefined): boolean;
238
+ /**
239
+ * Every operation the user is granted within a scope, merged across roles.
240
+ *
241
+ * Omit `scope` (or pass one with no ids) for tenant-wide operations; pass a
242
+ * data source id, or a {@link PermissionScope} for app / AI tool targets.
243
+ *
244
+ * Role shortcuts are deliberately excluded — this reports what the user's rules
245
+ * actually carry. Use {@link hasPermission} for an access decision.
246
+ */
247
+ declare function getAllowedOperations(user: DocyrusUser | null | undefined, scope?: string | null | PermissionScope): string[];
248
+ /**
249
+ * Check if the user has permission for an operation.
250
+ *
251
+ * `scope` accepts a data source id, a {@link PermissionScope} for app / AI tool
252
+ * targets, or nothing at all for tenant-wide operations such as `ai-access`,
253
+ * `manage_users` or `studio`.
254
+ *
255
+ * Permission resolution order:
256
+ * 1. super_admin role → always true
257
+ * 2. global_editor role + dataSourceId → true if operation is in the global_editor set
258
+ * 3. global_viewer role + dataSourceId → true only for 'view'
259
+ * 4. Always-permitted data sources (configurable)
260
+ * 5. The user's permissions for the scope (`permissions`, falling back to `aclRules`)
261
+ */
262
+ declare function hasPermission(user: DocyrusUser | null | undefined, operation: string, scope?: string | null | PermissionScope, config?: PermissionConfig): boolean;
263
+
264
+ declare const DEFAULT_API_URL = "https://alpha-api.docyrus.com";
265
+ declare const DEFAULT_OAUTH_SCOPES: string[];
266
+ declare const DEFAULT_CALLBACK_PATH = "/auth/callback";
267
+ /** Default cookie name for SSR token sync */
268
+ declare const DEFAULT_SSR_COOKIE_KEY = "docyrus-token";
269
+
270
+ export { AuthManager as A, DEFAULT_API_URL as D, DEFAULT_OAUTH_SCOPES as a, getAllowedOperations as b, hasRole as c, DEFAULT_CALLBACK_PATH as d, DEFAULT_SSR_COOKIE_KEY as e, getAllRoles as g, hasPermission as h };
271
+ export type { AuthStateListener as f };
@@ -0,0 +1,124 @@
1
+ export { A as AuthManager, f as AuthStateListener, D as DEFAULT_API_URL, d as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, b as getAllowedOperations, h as hasPermission, c as hasRole } from './constants-jx2_MXlr.js';
2
+ import { OAuth2Tokens } from '@kivacore/api-client';
3
+ import { D as DocyrusAuthConfig, T as GuidyElementsMessage, W as GuidyRoutesMessage, U as GuidyPointAckMessage, G as GuidyRoute, Q as GuidyCommandMessage, c as AuthMode } from './types-DmIgZa_v.js';
4
+ export { A as AclOperation, a as AclTargetType, b as AdaptiveCard, x as AppNavigationRequestMessage, y as AppRouteChangeMessage, e as AuthStatus, C as CalendarSendAckMessage, z as CalendarSendMessage, B as ChatSendAckMessage, E as ChatSendMessage, F as DocySendAckMessage, I as DocySendMessage, f as DocyrusAclRule, g as DocyrusAuthContextValue, h as DocyrusCalendarEventPayload, i as DocyrusEmailPayload, J as DocyrusNotification, j as DocyrusPermission, k as DocyrusRole, l as DocyrusShareAdaptiveCardPayload, m as DocyrusSharePayload, n as DocyrusShareTextPayload, o as DocyrusUser, K as EmailSendAckMessage, L as EmailSendMessage, N as GuidyCommandHandler, S as GuidyElement, V as GuidyPointMessage, X as GuidyScanMessage, H as HostNavigationHandler, Y as HostNavigationMessage, w as HostNavigationRequestOptions, v as HostNotificationHandler, Z as HostNotificationMessage, _ as HostSignInMessage, $ as IframeAuth, M as MsGraphAccount, p as MsGraphClient, q as MsGraphRequest, a0 as MsGraphRequestMessage, r as MsGraphRequestOptions, s as MsGraphResponse, a1 as MsGraphResponseMessage, t as MsGraphStatus, a2 as MsGraphStatusRequestMessage, a3 as MsGraphStatusResponseMessage, P as PermissionConfig, u as PermissionScope, R as RouteChangePayload, a4 as TokenRefreshRequestMessage } from './types-DmIgZa_v.js';
5
+
6
+ /**
7
+ * Standalone OAuth2 authorization code flow with PKCE via page redirect.
8
+ * Wraps api-client's OAuth2Client and BrowserOAuth2TokenStorage.
9
+ */
10
+ declare class StandaloneOAuth2Auth {
11
+ private oauth2Client;
12
+ private storage;
13
+ private callbackPath;
14
+ constructor(config?: DocyrusAuthConfig);
15
+ /**
16
+ * Check if the current page URL is the OAuth2 callback.
17
+ * Called on app initialization to detect returning from the auth server.
18
+ */
19
+ isCallbackUrl(): boolean;
20
+ /**
21
+ * Initiate the OAuth2 authorization code flow.
22
+ * Stores the current URL for post-auth redirect, then navigates
23
+ * the page to the authorization endpoint.
24
+ *
25
+ * PKCE state (codeVerifier, state) is stored in localStorage
26
+ * by the OAuth2Client and survives the page redirect.
27
+ */
28
+ initiateLogin(): Promise<void>;
29
+ /**
30
+ * Get the authorization URL without navigating.
31
+ * Useful for Electron apps that open the URL in an external browser.
32
+ * PKCE state is stored in storage just like initiateLogin().
33
+ */
34
+ getAuthorizationUrl(): Promise<string>;
35
+ /**
36
+ * Handle the OAuth2 callback URL.
37
+ * Reads PKCE state from localStorage, validates the state param,
38
+ * exchanges the authorization code for tokens, and stores them.
39
+ */
40
+ handleCallback(): Promise<OAuth2Tokens>;
41
+ /**
42
+ * Get the URL the user was on before the OAuth redirect.
43
+ * Clears the stored value after retrieval.
44
+ */
45
+ getReturnUrl(): string | null;
46
+ /** Get currently stored tokens (e.g., on page reload). */
47
+ getStoredTokens(): Promise<OAuth2Tokens | null>;
48
+ /** Persist externally obtained tokens for immediate authenticated use. */
49
+ setTokens(tokens: OAuth2Tokens): Promise<void>;
50
+ /** Check if the stored token is expired (with 60s buffer). */
51
+ isTokenExpired(): Promise<boolean>;
52
+ /** Refresh the access token using the stored refresh token. */
53
+ refreshToken(): Promise<OAuth2Tokens>;
54
+ /** Get a valid access token, refreshing if needed. */
55
+ getValidAccessToken(): Promise<string>;
56
+ /** Logout: revoke token and clear storage. */
57
+ logout(): Promise<void>;
58
+ }
59
+
60
+ /** Post an app → host message (elements, routes, or a point ack). */
61
+ type GuidyBridgeSender = (message: GuidyElementsMessage | GuidyRoutesMessage | GuidyPointAckMessage) => void;
62
+ /**
63
+ * Runs inside an embedded Docyrus app and lets the host assistant (Guidy)
64
+ * inspect and drive the app's visible UI over the existing postMessage
65
+ * channel.
66
+ *
67
+ * It only ever exposes labels/ids of already-visible interactive elements and
68
+ * only executes a fixed command vocabulary (scan / point / click) — the same
69
+ * exposure profile the host assistant already has on its own chrome. No
70
+ * arbitrary script is accepted from the host.
71
+ *
72
+ * Protocol (paired with the host's ExternalAppManager):
73
+ * - App → Host: `guidy:elements` (pushed on start, route change, mutation)
74
+ * - App → Host: `guidy:routes` (pushed on start and when routes change)
75
+ * - Host → App: `guidy:scan` → app re-posts `guidy:elements` + `guidy:routes`
76
+ * - Host → App: `guidy:point` → app scrolls/highlights/(clicks), then
77
+ * - App → Host: `guidy:point-ack`
78
+ */
79
+ declare class GuidyBridge {
80
+ private send;
81
+ private routes;
82
+ private started;
83
+ private observer;
84
+ private scanTimer;
85
+ private routeListener;
86
+ private highlightTimer;
87
+ private clickTimer;
88
+ private annotationTimer;
89
+ constructor(send: GuidyBridgeSender, routes?: GuidyRoute[]);
90
+ /** Replace the declared navigable routes and re-post them to the host. */
91
+ setRoutes(routes: GuidyRoute[]): void;
92
+ /**
93
+ * Begin reporting the element inventory and watching for changes.
94
+ * Idempotent. No-op outside a browser document.
95
+ */
96
+ start(): void;
97
+ /** Stop watching and tear down any injected overlay. Idempotent. */
98
+ stop(): void;
99
+ /** Dispatch a host `guidy:*` command. Wired to `IframeAuth.onGuidyCommand`. */
100
+ handleCommand(message: GuidyCommandMessage): void;
101
+ /** Collect every visible anchor/button that exposes an id and a label. */
102
+ private collectElements;
103
+ private postElements;
104
+ private postRoutes;
105
+ private scheduleScan;
106
+ private handlePoint;
107
+ private ensureStyle;
108
+ private highlight;
109
+ private clearHighlight;
110
+ private annotate;
111
+ private clearAnnotation;
112
+ private clearTimer;
113
+ }
114
+
115
+ /**
116
+ * Detect whether the app is inside an iframe from a trusted *.docyrus.app host
117
+ * or running as a standalone page.
118
+ *
119
+ * If we are in an iframe but NOT from a trusted origin, we fall back
120
+ * to standalone mode (graceful degradation).
121
+ */
122
+ declare function detectAuthMode(allowedOrigins?: string[], allowedPattern?: RegExp): AuthMode;
123
+
124
+ export { AuthMode, DocyrusAuthConfig, GuidyBridge, GuidyCommandMessage, GuidyElementsMessage, GuidyPointAckMessage, GuidyRoute, GuidyRoutesMessage, StandaloneOAuth2Auth, detectAuthMode };