@docyrus/signin 0.18.0 → 0.18.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/constants.ts","../../src/nextjs/server-client.ts","../../src/nextjs/session.ts","../../src/nextjs/middleware.ts"],"names":["MemoryTokenManager","RestApiClient"],"mappings":";;;;;AAAO,IAAM,eAAA,GAAkB,+BAAA;AA8BxB,IAAM,sBAAA,GAAyB,eAAA;;;ACM/B,SAAS,kBAAA,CACd,WAAA,EACA,MAAA,GAA6B,EAAC,EACf;AACf,EAAA,MAAM,MAAA,GAAS,OAAO,MAAA,IAAU,eAAA;AAChC,EAAA,MAAM,SAAA,GAAY,OAAO,SAAA,IAAa,sBAAA;AAEtC,EAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,GAAA,CAAI,SAAS,GAAG,KAAA,IAAS,IAAA;AACnD,EAAA,MAAM,YAAA,GAAe,KAAA,GAAQ,kBAAA,CAAmB,KAAK,CAAA,GAAI,IAAA;AAEzD,EAAA,MAAM,YAAA,GAAe,IAAI,kBAAA,EAAmB;AAE5C,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,YAAA,CAAa,SAAS,YAAY,CAAA;AAAA,EACpC;AAEA,EAAA,OAAO,IAAI,aAAA,CAAc;AAAA,IACvB,OAAA,EAAS,MAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;;;AC/BO,SAAS,UAAA,CACd,aACA,SAAA,EACa;AACb,EAAA,MAAM,MAAM,SAAA,IAAa,sBAAA;AACzB,EAAA,MAAM,WAAA,GAAc,WAAA,CAAY,GAAA,CAAI,GAAG,CAAA;AAEvC,EAAA,MAAM,cAAc,WAAA,EAAa,KAAA,GAAQ,kBAAA,CAAmB,WAAA,CAAY,KAAK,CAAA,GAAI,IAAA;AAEjF,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,iBAAiB,WAAA,KAAgB;AAAA,GACnC;AACF;ACT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.js","sourcesContent":["export const DEFAULT_API_URL = 'https://alpha-api.docyrus.com';\n\nexport const DEFAULT_OAUTH_SCOPES = [\n 'offline_access',\n 'Read.All',\n 'User.Read',\n 'Users.Read.All',\n 'DS.Read.All'\n];\n\nexport const DEFAULT_CALLBACK_PATH = '/auth/callback';\n\nexport const DEFAULT_ALLOWED_HOST_PATTERN = /^https:\\/\\/[^/]+\\.docyrus\\.app$/;\n\n/** localStorage key to persist the pre-redirect location */\nexport const REDIRECT_RETURN_KEY = 'docyrus_auth_return_url';\n\n/** Buffer in seconds before token expiration to trigger refresh */\nexport const TOKEN_EXPIRY_BUFFER_SECONDS = 60;\n\n/** Timeout for iframe token refresh requests (ms) */\nexport const IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 10_000;\n\n/** Timeout for app→host action acks (Send to Docy / Send to Chat) (ms) */\nexport const HOST_ACTION_TIMEOUT_MS = 15_000;\n\n/** Timeout for host-proxied Microsoft Graph requests (ms) — Graph can be slow */\nexport const MSGRAPH_REQUEST_TIMEOUT_MS = 30_000;\n\n/** Default cookie name for SSR token sync */\nexport const DEFAULT_SSR_COOKIE_KEY = 'docyrus-token';\n\n/** URL query parameter name for SSO session tokens */\nexport const SSO_TOKEN_PARAM = 'sso_token';\n","import { RestApiClient, MemoryTokenManager } from '@docyrus/api-client';\n\nimport { DEFAULT_API_URL, DEFAULT_SSR_COOKIE_KEY } from '../constants';\nimport { type ReadonlyCookieStore, type ServerClientConfig } from './types';\n\n/**\n * Create an authenticated `RestApiClient` for use in Next.js\n * Server Components, Server Actions, and Route Handlers.\n *\n * Reads the access token from cookies. The client cannot refresh tokens —\n * that is handled client-side by `DocyrusAuthProvider`.\n *\n * @example Server Component\n * ```ts\n * import { cookies } from 'next/headers';\n * import { createServerClient } from '@docyrus/signin/nextjs';\n *\n * export default async function Page() {\n * const client = createServerClient(await cookies());\n * const { data: user } = await client.get('/v1/users/me');\n * return <div>{user.name}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```ts\n * 'use server';\n * import { cookies } from 'next/headers';\n * import { createServerClient } from '@docyrus/signin/nextjs';\n *\n * export async function getUser() {\n * const client = createServerClient(await cookies());\n * return client.get('/v1/users/me');\n * }\n * ```\n */\nexport function createServerClient(\n cookieStore: ReadonlyCookieStore,\n config: ServerClientConfig = {}\n): RestApiClient {\n const apiUrl = config.apiUrl ?? DEFAULT_API_URL;\n const cookieKey = config.cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n\n const token = cookieStore.get(cookieKey)?.value ?? null;\n const decodedToken = token ? decodeURIComponent(token) : null;\n\n const tokenManager = new MemoryTokenManager();\n\n if (decodedToken) {\n tokenManager.setToken(decodedToken);\n }\n\n return new RestApiClient({\n baseURL: apiUrl,\n tokenManager\n });\n}\n","import { DEFAULT_SSR_COOKIE_KEY } from '../constants';\nimport { type ReadonlyCookieStore, type AuthSession } from './types';\n\n/**\n * Read the current auth session from cookies.\n *\n * Because the SSR cookie is written with `max-age` matching the token\n * lifetime, the browser automatically removes it once the token expires.\n * If the cookie is present the token is considered valid.\n *\n * Works in Server Components, Server Actions, Route Handlers, and Middleware.\n *\n * @example\n * ```ts\n * import { cookies } from 'next/headers';\n * import { getSession } from '@docyrus/signin/nextjs';\n * import { redirect } from 'next/navigation';\n *\n * export default async function Page() {\n * const session = getSession(await cookies());\n * if (!session.isAuthenticated) redirect('/login');\n * // ...\n * }\n * ```\n */\nexport function getSession(\n cookieStore: ReadonlyCookieStore,\n cookieKey?: string\n): AuthSession {\n const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n const tokenCookie = cookieStore.get(key);\n\n const accessToken = tokenCookie?.value ? decodeURIComponent(tokenCookie.value) : null;\n\n return {\n accessToken,\n isAuthenticated: accessToken !== null\n };\n}\n","import { RestApiClient, MemoryTokenManager } from '@docyrus/api-client';\n\nimport { DEFAULT_API_URL, DEFAULT_SSR_COOKIE_KEY } from '../constants';\nimport {\n type MiddlewareRequest,\n type ServerClientConfig,\n type AuthMiddlewareConfig,\n type AuthSession\n} from './types';\n\n/**\n * Read the auth session from middleware request cookies.\n *\n * Use this when you need full control over your middleware logic.\n *\n * @example\n * ```ts\n * import { NextResponse, type NextRequest } from 'next/server';\n * import { getMiddlewareSession } from '@docyrus/signin/nextjs';\n *\n * export function middleware(request: NextRequest) {\n * const session = getMiddlewareSession(request);\n * if (!session.isAuthenticated && request.nextUrl.pathname.startsWith('/dashboard')) {\n * return NextResponse.redirect(new URL('/login', request.url));\n * }\n * return NextResponse.next();\n * }\n * ```\n */\nexport function getMiddlewareSession(\n request: MiddlewareRequest,\n cookieKey?: string\n): AuthSession {\n const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n const tokenCookie = request.cookies.get(key);\n\n const accessToken = tokenCookie?.value ? decodeURIComponent(tokenCookie.value) : null;\n\n return {\n accessToken,\n isAuthenticated: accessToken !== null\n };\n}\n\n/**\n * Create an authenticated `RestApiClient` for use in Next.js middleware.\n *\n * @example\n * ```ts\n * import { type NextRequest } from 'next/server';\n * import { createMiddlewareClient } from '@docyrus/signin/nextjs';\n *\n * export function middleware(request: NextRequest) {\n * const client = createMiddlewareClient(request);\n * // use client for API calls if needed\n * }\n * ```\n */\nexport function createMiddlewareClient(\n request: MiddlewareRequest,\n config: ServerClientConfig = {}\n): RestApiClient {\n const apiUrl = config.apiUrl ?? DEFAULT_API_URL;\n const cookieKey = config.cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n\n const token = request.cookies.get(cookieKey)?.value ?? null;\n const decodedToken = token ? decodeURIComponent(token) : null;\n\n const tokenManager = new MemoryTokenManager();\n\n if (decodedToken) {\n tokenManager.setToken(decodedToken);\n }\n\n return new RestApiClient({\n baseURL: apiUrl,\n tokenManager\n });\n}\n\n/**\n * Check if a pathname matches any of the given route patterns.\n * Supports `(.*)` suffix for catch-all matching.\n */\nfunction matchesRoute(pathname: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n const regexStr = pattern\n .replace(/[.+?^${}|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\\\\\(\\\\\\.\\\\\\*\\\\\\)/g, '.*')\n .replace(/\\\\\\*/g, '[^/]*');\n\n return new RegExp(`^${regexStr}$`).test(pathname);\n });\n}\n\nconst DEFAULT_PUBLIC_ROUTES = ['/login', '/auth/callback'];\n\n/**\n * Pre-built auth middleware for route protection.\n *\n * Uses standard `Response.redirect()` for redirects and returns `undefined`\n * for pass-through (Next.js treats this as \"continue to next middleware/page\").\n *\n * @example\n * ```ts\n * // middleware.ts\n * import { authMiddleware } from '@docyrus/signin/nextjs';\n *\n * export default authMiddleware({\n * publicRoutes: ['/login', '/callback'],\n * loginPath: '/login',\n * });\n *\n * export const config = {\n * matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\\\..*).*)'],\n * };\n * ```\n */\nexport function authMiddleware(config: AuthMiddlewareConfig = {}) {\n const {\n protectedRoutes,\n publicRoutes = DEFAULT_PUBLIC_ROUTES,\n loginPath = '/login',\n afterLoginPath = '/',\n cookieKey = DEFAULT_SSR_COOKIE_KEY\n } = config;\n\n const allPublicRoutes = publicRoutes.includes(loginPath) ? publicRoutes : [...publicRoutes, loginPath];\n\n return (request: MiddlewareRequest): Response | undefined => {\n const { pathname } = request.nextUrl;\n const session = getMiddlewareSession(request, cookieKey);\n\n const isPublicRoute = matchesRoute(pathname, allPublicRoutes);\n const isProtectedRoute = protectedRoutes ? matchesRoute(pathname, protectedRoutes) : !isPublicRoute;\n\n // Redirect authenticated users away from login page\n if (session.isAuthenticated && pathname === loginPath) {\n return Response.redirect(new URL(afterLoginPath, request.url));\n }\n\n // Redirect unauthenticated users to login\n if (!session.isAuthenticated && isProtectedRoute) {\n return Response.redirect(new URL(loginPath, request.url));\n }\n\n // Pass through\n return undefined;\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/constants.ts","../../src/nextjs/server-client.ts","../../src/nextjs/session.ts","../../src/nextjs/middleware.ts"],"names":["MemoryTokenManager","RestApiClient"],"mappings":";;;;;AAAO,IAAM,eAAA,GAAkB,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AA,GAAe,qBAAA;AAAA,IACf,SAAA,GAAY,QAAA;AAAA,IACZ,cAAA,GAAiB,GAAA;AAAA,IACjB,SAAA,GAAY;AAAA,GACd,GAAI,MAAA;AAEJ,EAAA,MAAM,eAAA,GAAkB,aAAa,QAAA,CAAS,SAAS,IAAI,YAAA,GAAe,CAAC,GAAG,YAAA,EAAc,SAAS,CAAA;AAErG,EAAA,OAAO,CAAC,OAAA,KAAqD;AAC3D,IAAA,MAAM,EAAE,QAAA,EAAS,GAAI,OAAA,CAAQ,OAAA;AAC7B,IAAA,MAAM,OAAA,GAAU,oBAAA,CAAqB,OAAA,EAAS,SAAS,CAAA;AAEvD,IAAA,MAAM,aAAA,GAAgB,YAAA,CAAa,QAAA,EAAU,eAAe,CAAA;AAC5D,IAAA,MAAM,mBAAmB,eAAA,GAAkB,YAAA,CAAa,QAAA,EAAU,eAAe,IAAI,CAAC,aAAA;AAGtF,IAAA,IAAI,OAAA,CAAQ,eAAA,IAAmB,QAAA,KAAa,SAAA,EAAW;AACrD,MAAA,OAAO,SAAS,QAAA,CAAS,IAAI,IAAI,cAAA,EAAgB,OAAA,CAAQ,GAAG,CAAC,CAAA;AAAA,IAC/D;AAGA,IAAA,IAAI,CAAC,OAAA,CAAQ,eAAA,IAAmB,gBAAA,EAAkB;AAChD,MAAA,OAAO,SAAS,QAAA,CAAS,IAAI,IAAI,SAAA,EAAW,OAAA,CAAQ,GAAG,CAAC,CAAA;AAAA,IAC1D;AAGA,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AACF","file":"index.js","sourcesContent":["export const DEFAULT_API_URL = 'https://alpha-api.docyrus.com';\n\nexport const DEFAULT_OAUTH_SCOPES = [\n 'offline_access',\n 'Read.All',\n 'User.Read',\n 'Users.Read.All',\n 'DS.Read.All'\n];\n\nexport const DEFAULT_CALLBACK_PATH = '/auth/callback';\n\nexport const DEFAULT_ALLOWED_HOST_PATTERN = /^https:\\/\\/[^/]+\\.docyrus\\.app$/;\n\n/** localStorage key to persist the pre-redirect location */\nexport const REDIRECT_RETURN_KEY = 'docyrus_auth_return_url';\n\n/** Buffer in seconds before token expiration to trigger refresh */\nexport const TOKEN_EXPIRY_BUFFER_SECONDS = 60;\n\n/**\n * Minimum gap between two proactive token refreshes (ms). Stops a refresh that\n * returns a token still inside the expiry buffer from re-triggering itself.\n */\nexport const MIN_TOKEN_REFRESH_INTERVAL_MS = 10_000;\n\n/** Timeout for iframe token refresh requests (ms) */\nexport const IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 10_000;\n\n/** Timeout for app→host action acks (Send to Docy / Send to Chat) (ms) */\nexport const HOST_ACTION_TIMEOUT_MS = 15_000;\n\n/** Timeout for host-proxied Microsoft Graph requests (ms) — Graph can be slow */\nexport const MSGRAPH_REQUEST_TIMEOUT_MS = 30_000;\n\n/** Default cookie name for SSR token sync */\nexport const DEFAULT_SSR_COOKIE_KEY = 'docyrus-token';\n\n/** URL query parameter name for SSO session tokens */\nexport const SSO_TOKEN_PARAM = 'sso_token';\n","import { RestApiClient, MemoryTokenManager } from '@docyrus/api-client';\n\nimport { DEFAULT_API_URL, DEFAULT_SSR_COOKIE_KEY } from '../constants';\nimport { type ReadonlyCookieStore, type ServerClientConfig } from './types';\n\n/**\n * Create an authenticated `RestApiClient` for use in Next.js\n * Server Components, Server Actions, and Route Handlers.\n *\n * Reads the access token from cookies. The client cannot refresh tokens —\n * that is handled client-side by `DocyrusAuthProvider`.\n *\n * @example Server Component\n * ```ts\n * import { cookies } from 'next/headers';\n * import { createServerClient } from '@docyrus/signin/nextjs';\n *\n * export default async function Page() {\n * const client = createServerClient(await cookies());\n * const { data: user } = await client.get('/v1/users/me');\n * return <div>{user.name}</div>;\n * }\n * ```\n *\n * @example Server Action\n * ```ts\n * 'use server';\n * import { cookies } from 'next/headers';\n * import { createServerClient } from '@docyrus/signin/nextjs';\n *\n * export async function getUser() {\n * const client = createServerClient(await cookies());\n * return client.get('/v1/users/me');\n * }\n * ```\n */\nexport function createServerClient(\n cookieStore: ReadonlyCookieStore,\n config: ServerClientConfig = {}\n): RestApiClient {\n const apiUrl = config.apiUrl ?? DEFAULT_API_URL;\n const cookieKey = config.cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n\n const token = cookieStore.get(cookieKey)?.value ?? null;\n const decodedToken = token ? decodeURIComponent(token) : null;\n\n const tokenManager = new MemoryTokenManager();\n\n if (decodedToken) {\n tokenManager.setToken(decodedToken);\n }\n\n return new RestApiClient({\n baseURL: apiUrl,\n tokenManager\n });\n}\n","import { DEFAULT_SSR_COOKIE_KEY } from '../constants';\nimport { type ReadonlyCookieStore, type AuthSession } from './types';\n\n/**\n * Read the current auth session from cookies.\n *\n * Because the SSR cookie is written with `max-age` matching the token\n * lifetime, the browser automatically removes it once the token expires.\n * If the cookie is present the token is considered valid.\n *\n * Works in Server Components, Server Actions, Route Handlers, and Middleware.\n *\n * @example\n * ```ts\n * import { cookies } from 'next/headers';\n * import { getSession } from '@docyrus/signin/nextjs';\n * import { redirect } from 'next/navigation';\n *\n * export default async function Page() {\n * const session = getSession(await cookies());\n * if (!session.isAuthenticated) redirect('/login');\n * // ...\n * }\n * ```\n */\nexport function getSession(\n cookieStore: ReadonlyCookieStore,\n cookieKey?: string\n): AuthSession {\n const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n const tokenCookie = cookieStore.get(key);\n\n const accessToken = tokenCookie?.value ? decodeURIComponent(tokenCookie.value) : null;\n\n return {\n accessToken,\n isAuthenticated: accessToken !== null\n };\n}\n","import { RestApiClient, MemoryTokenManager } from '@docyrus/api-client';\n\nimport { DEFAULT_API_URL, DEFAULT_SSR_COOKIE_KEY } from '../constants';\nimport {\n type MiddlewareRequest,\n type ServerClientConfig,\n type AuthMiddlewareConfig,\n type AuthSession\n} from './types';\n\n/**\n * Read the auth session from middleware request cookies.\n *\n * Use this when you need full control over your middleware logic.\n *\n * @example\n * ```ts\n * import { NextResponse, type NextRequest } from 'next/server';\n * import { getMiddlewareSession } from '@docyrus/signin/nextjs';\n *\n * export function middleware(request: NextRequest) {\n * const session = getMiddlewareSession(request);\n * if (!session.isAuthenticated && request.nextUrl.pathname.startsWith('/dashboard')) {\n * return NextResponse.redirect(new URL('/login', request.url));\n * }\n * return NextResponse.next();\n * }\n * ```\n */\nexport function getMiddlewareSession(\n request: MiddlewareRequest,\n cookieKey?: string\n): AuthSession {\n const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n const tokenCookie = request.cookies.get(key);\n\n const accessToken = tokenCookie?.value ? decodeURIComponent(tokenCookie.value) : null;\n\n return {\n accessToken,\n isAuthenticated: accessToken !== null\n };\n}\n\n/**\n * Create an authenticated `RestApiClient` for use in Next.js middleware.\n *\n * @example\n * ```ts\n * import { type NextRequest } from 'next/server';\n * import { createMiddlewareClient } from '@docyrus/signin/nextjs';\n *\n * export function middleware(request: NextRequest) {\n * const client = createMiddlewareClient(request);\n * // use client for API calls if needed\n * }\n * ```\n */\nexport function createMiddlewareClient(\n request: MiddlewareRequest,\n config: ServerClientConfig = {}\n): RestApiClient {\n const apiUrl = config.apiUrl ?? DEFAULT_API_URL;\n const cookieKey = config.cookieKey ?? DEFAULT_SSR_COOKIE_KEY;\n\n const token = request.cookies.get(cookieKey)?.value ?? null;\n const decodedToken = token ? decodeURIComponent(token) : null;\n\n const tokenManager = new MemoryTokenManager();\n\n if (decodedToken) {\n tokenManager.setToken(decodedToken);\n }\n\n return new RestApiClient({\n baseURL: apiUrl,\n tokenManager\n });\n}\n\n/**\n * Check if a pathname matches any of the given route patterns.\n * Supports `(.*)` suffix for catch-all matching.\n */\nfunction matchesRoute(pathname: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n const regexStr = pattern\n .replace(/[.+?^${}|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\\\\\(\\\\\\.\\\\\\*\\\\\\)/g, '.*')\n .replace(/\\\\\\*/g, '[^/]*');\n\n return new RegExp(`^${regexStr}$`).test(pathname);\n });\n}\n\nconst DEFAULT_PUBLIC_ROUTES = ['/login', '/auth/callback'];\n\n/**\n * Pre-built auth middleware for route protection.\n *\n * Uses standard `Response.redirect()` for redirects and returns `undefined`\n * for pass-through (Next.js treats this as \"continue to next middleware/page\").\n *\n * @example\n * ```ts\n * // middleware.ts\n * import { authMiddleware } from '@docyrus/signin/nextjs';\n *\n * export default authMiddleware({\n * publicRoutes: ['/login', '/callback'],\n * loginPath: '/login',\n * });\n *\n * export const config = {\n * matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\\\..*).*)'],\n * };\n * ```\n */\nexport function authMiddleware(config: AuthMiddlewareConfig = {}) {\n const {\n protectedRoutes,\n publicRoutes = DEFAULT_PUBLIC_ROUTES,\n loginPath = '/login',\n afterLoginPath = '/',\n cookieKey = DEFAULT_SSR_COOKIE_KEY\n } = config;\n\n const allPublicRoutes = publicRoutes.includes(loginPath) ? publicRoutes : [...publicRoutes, loginPath];\n\n return (request: MiddlewareRequest): Response | undefined => {\n const { pathname } = request.nextUrl;\n const session = getMiddlewareSession(request, cookieKey);\n\n const isPublicRoute = matchesRoute(pathname, allPublicRoutes);\n const isProtectedRoute = protectedRoutes ? matchesRoute(pathname, protectedRoutes) : !isPublicRoute;\n\n // Redirect authenticated users away from login page\n if (session.isAuthenticated && pathname === loginPath) {\n return Response.redirect(new URL(afterLoginPath, request.url));\n }\n\n // Redirect unauthenticated users to login\n if (!session.isAuthenticated && isProtectedRoute) {\n return Response.redirect(new URL(loginPath, request.url));\n }\n\n // Pass through\n return undefined;\n };\n}\n"]}
@@ -2,7 +2,7 @@ import { OAuth2Tokens } from '@docyrus/api-client';
2
2
  import { D as DocyrusAuthConfig } from '../types-BcLDyMdw.js';
3
3
  export { A as AclOperation, a as AclTargetType, b as AdaptiveCard, c as AuthMode, d as AuthSessionResult, e as AuthStatus, f as DocyrusAclRule, g as DocyrusAuthContextValue, h as DocyrusCalendarEventPayload, i as DocyrusEmailPayload, j as DocyrusPermission, k as DocyrusRole, l as DocyrusShareAdaptiveCardPayload, m as DocyrusSharePayload, n as DocyrusShareTextPayload, o as DocyrusUser, M as MsGraphAccount, p as MsGraphClient, q as MsGraphRequest, r as MsGraphRequestOptions, s as MsGraphResponse, t as MsGraphStatus, O as OpenAuthSessionFn, P as PermissionConfig, u as PermissionScope } from '../types-BcLDyMdw.js';
4
4
  export { D as DocyrusAuthContext, a as DocyrusAuthProvider, b as DocyrusAuthProviderProps, u as useDocyrusAuth, c as useDocyrusClient } from '../use-docyrus-client-C9uiHma9.js';
5
- export { A as AuthManager, D as DEFAULT_API_URL, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, b as getAllowedOperations, h as hasPermission, c as hasRole } from '../constants-C9ezX9zG.js';
5
+ export { A as AuthManager, D as DEFAULT_API_URL, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, b as getAllowedOperations, h as hasPermission, c as hasRole } from '../constants-CvMiR-RM.js';
6
6
  import 'react';
7
7
 
8
8
  /**
@@ -17,6 +17,7 @@ var DEFAULT_CALLBACK_PATH = "/auth/callback";
17
17
  var DEFAULT_ALLOWED_HOST_PATTERN = /^https:\/\/[^/]+\.docyrus\.app$/;
18
18
  var REDIRECT_RETURN_KEY = "docyrus_auth_return_url";
19
19
  var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
20
+ var MIN_TOKEN_REFRESH_INTERVAL_MS = 1e4;
20
21
  var IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 1e4;
21
22
  var HOST_ACTION_TIMEOUT_MS = 15e3;
22
23
  var MSGRAPH_REQUEST_TIMEOUT_MS = 3e4;
@@ -231,18 +232,34 @@ var StandaloneOAuth2Auth = class {
231
232
  };
232
233
 
233
234
  // src/core/jwt.ts
234
- function parseJwtExp(accessToken) {
235
+ var PER_ISSUANCE_CLAIMS = /* @__PURE__ */ new Set([
236
+ "exp",
237
+ "iat",
238
+ "nbf",
239
+ "jti"
240
+ ]);
241
+ function decodeJwtPayload(accessToken) {
235
242
  const parts = accessToken?.split(".");
236
243
  if (!parts || parts.length < 2) return null;
237
244
  try {
238
245
  const payload = JSON.parse(
239
246
  atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
240
247
  );
241
- return typeof payload["exp"] === "number" ? payload["exp"] : null;
248
+ return payload && typeof payload === "object" ? payload : null;
242
249
  } catch {
243
250
  return null;
244
251
  }
245
252
  }
253
+ function parseJwtExp(accessToken) {
254
+ const exp = decodeJwtPayload(accessToken)?.["exp"];
255
+ return typeof exp === "number" ? exp : null;
256
+ }
257
+ function getJwtSessionKey(accessToken) {
258
+ const payload = decodeJwtPayload(accessToken);
259
+ if (!payload) return null;
260
+ const stableClaims = Object.keys(payload).filter((claim) => !PER_ISSUANCE_CLAIMS.has(claim)).sort().map((claim) => [claim, payload[claim]]);
261
+ return JSON.stringify(stableClaims);
262
+ }
246
263
 
247
264
  // src/core/iframe-auth.ts
248
265
  function postToHost(data) {
@@ -1091,12 +1108,18 @@ var AuthManager = class {
1091
1108
  error = null;
1092
1109
  client = null;
1093
1110
  user = null;
1111
+ /** In-flight `/v1/users/me` request, tied to the client that issued it. */
1112
+ userFetch = null;
1094
1113
  standaloneAuth = null;
1095
1114
  iframeAuth = null;
1096
1115
  guidyBridge = null;
1097
1116
  msGraphClient = null;
1098
1117
  reactNativeAuth = null;
1099
1118
  tokenRefreshTimer = null;
1119
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
1120
+ lastScheduledRefreshAt = 0;
1121
+ /** Session the current client was created for — see `getJwtSessionKey`. */
1122
+ sessionKey = null;
1100
1123
  /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
1101
1124
  refreshInFlight = null;
1102
1125
  listeners = /* @__PURE__ */ new Set();
@@ -1488,40 +1511,82 @@ var AuthManager = class {
1488
1511
  }
1489
1512
  this.tokens = null;
1490
1513
  this.client = null;
1514
+ this.sessionKey = null;
1491
1515
  this.user = null;
1492
1516
  this.status = "unauthenticated";
1493
1517
  this.error = null;
1494
1518
  this.notify();
1495
1519
  }
1496
1520
  /**
1497
- * Called when valid tokens are received (either mode).
1498
- * Creates/updates the RestApiClient and schedules token refresh.
1499
- * Fires a user fetch in the background — the first notify() fires with user: null,
1500
- * and a second notify() fires once the user is fetched.
1521
+ * Called when valid tokens are received (any mode). In iframe mode that is
1522
+ * every host `signin` message — the first sign-in, the host's answer to each
1523
+ * `token-refresh-request`, and repeats of a token we already hold (the host
1524
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
1525
+ *
1526
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
1527
+ * refreshed token needs no new client. A new client — plus a user fetch —
1528
+ * is reserved for a new session (first sign-in, or the host switching user
1529
+ * or tenant): consumers key caches on client identity, so a fresh instance
1530
+ * makes them reload everything.
1531
+ *
1532
+ * On a new session the first notify() fires with user: null, and a second
1533
+ * one fires once the user is fetched.
1501
1534
  */
1502
1535
  setAuthenticated(tokens) {
1536
+ const isRepeat = this.status === "authenticated" && tokens.accessToken === this.tokens?.accessToken && tokens.refreshToken === this.tokens?.refreshToken;
1537
+ if (isRepeat) {
1538
+ this.scheduleTokenRefresh(tokens);
1539
+ return;
1540
+ }
1541
+ const sessionKey = getJwtSessionKey(tokens.accessToken);
1542
+ const isNewSession = !this.client || sessionKey === null || sessionKey !== this.sessionKey;
1503
1543
  this.tokens = tokens;
1544
+ this.sessionKey = sessionKey;
1504
1545
  this.error = null;
1505
1546
  this.status = "authenticated";
1506
1547
  if (this.config.ssr) {
1507
1548
  syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
1508
1549
  }
1509
- this.createClient();
1550
+ if (isNewSession) {
1551
+ this.createClient();
1552
+ }
1510
1553
  this.scheduleTokenRefresh(tokens);
1511
1554
  this.notify();
1512
- this.fetchUser();
1513
- }
1514
- /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
1515
- async fetchUser() {
1516
- if (!this.client) return;
1517
- try {
1518
- const response = await this.client.get("/v1/users/me");
1519
- const maybeUser = response;
1520
- this.user = maybeUser && typeof maybeUser === "object" && "id" in maybeUser && "email" in maybeUser ? maybeUser : response.data;
1521
- } catch {
1522
- this.user = null;
1555
+ if (isNewSession || !this.user) {
1556
+ void this.fetchUser();
1523
1557
  }
1524
- this.notify();
1558
+ }
1559
+ /**
1560
+ * Fetch the current user from /v1/users/me. Silently sets user to null on failure.
1561
+ *
1562
+ * Concurrent calls share one request: `setAuthenticated` fetches whenever the
1563
+ * user is still missing, so a second token push that lands while the first
1564
+ * fetch is in flight (e.g. stored tokens restored on load, then the host or a
1565
+ * bridge pushing its session) would otherwise fire a duplicate request. A
1566
+ * result is dropped if the client changed meanwhile (sign-out or a new
1567
+ * session), so a stale user never overwrites the current one.
1568
+ */
1569
+ fetchUser() {
1570
+ const { client } = this;
1571
+ if (!client) return Promise.resolve();
1572
+ if (this.userFetch?.client === client) return this.userFetch.promise;
1573
+ const promise = (async () => {
1574
+ let user = null;
1575
+ try {
1576
+ const response = await client.get("/v1/users/me");
1577
+ const maybeUser = response;
1578
+ user = maybeUser && typeof maybeUser === "object" && "id" in maybeUser && "email" in maybeUser ? maybeUser : response.data;
1579
+ } catch {
1580
+ user = null;
1581
+ }
1582
+ if (this.client !== client) return;
1583
+ this.user = user;
1584
+ this.notify();
1585
+ })().finally(() => {
1586
+ if (this.userFetch?.promise === promise) this.userFetch = null;
1587
+ });
1588
+ this.userFetch = { client, promise };
1589
+ return promise;
1525
1590
  }
1526
1591
  /**
1527
1592
  * Create a RestApiClient with a custom TokenManager that proactively
@@ -1620,18 +1685,13 @@ var AuthManager = class {
1620
1685
  if (!this.autoRefreshEnabled) return;
1621
1686
  const expiresAt = this.resolveExpiry(tokens);
1622
1687
  if (!expiresAt) return;
1623
- const expiresAtMs = expiresAt * 1e3;
1624
- const bufferMs = TOKEN_EXPIRY_BUFFER_SECONDS * 1e3;
1625
- const refreshInMs = expiresAtMs - bufferMs - Date.now();
1626
- if (refreshInMs <= 0) {
1627
- this.handleTokenRefresh().catch((err) => {
1628
- this.error = err instanceof Error ? err : new Error(String(err));
1629
- this.status = "unauthenticated";
1630
- this.notify();
1631
- });
1632
- return;
1633
- }
1688
+ const now = Date.now();
1689
+ const dueInMs = expiresAt * 1e3 - TOKEN_EXPIRY_BUFFER_SECONDS * 1e3 - now;
1690
+ const throttleMs = this.lastScheduledRefreshAt + MIN_TOKEN_REFRESH_INTERVAL_MS - now;
1691
+ const refreshInMs = Math.max(dueInMs, throttleMs, 0);
1634
1692
  this.tokenRefreshTimer = setTimeout(() => {
1693
+ this.tokenRefreshTimer = null;
1694
+ this.lastScheduledRefreshAt = Date.now();
1635
1695
  this.handleTokenRefresh().catch((err) => {
1636
1696
  this.error = err instanceof Error ? err : new Error(String(err));
1637
1697
  this.status = "unauthenticated";