@docyrus/signin 0.17.0 → 0.18.1
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 +60 -6
- package/dist/{constants-CB5mfHCf.d.ts → constants-BVfrHdk1.d.ts} +36 -9
- package/dist/core-index.d.ts +3 -3
- package/dist/core-index.js +117 -31
- package/dist/core-index.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +118 -32
- package/dist/index.js.map +1 -1
- package/dist/nextjs/index.js.map +1 -1
- package/dist/react-native/index.d.ts +4 -4
- package/dist/react-native/index.js +118 -32
- package/dist/react-native/index.js.map +1 -1
- package/dist/{types-CFnKr6T_.d.ts → types-BcLDyMdw.d.ts} +46 -5
- package/dist/{use-docyrus-client-BYQdgvz1.d.ts → use-docyrus-client-C9uiHma9.d.ts} +1 -1
- package/dist/vue/index.d.ts +2 -2
- package/dist/vue/index.js +57 -19
- package/dist/vue/index.js.map +1 -1
- package/package.json +1 -1
package/dist/nextjs/index.js.map
CHANGED
|
@@ -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,GA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D,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/** 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,+BAAA;AAoCxB,IAAM,sBAAA,GAAyB,eAAA;;;ACA/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,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AI,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"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { OAuth2Tokens } from '@docyrus/api-client';
|
|
2
|
-
import { D as DocyrusAuthConfig } from '../types-
|
|
3
|
-
export { A as AclOperation, a as
|
|
4
|
-
export { D as DocyrusAuthContext, a as DocyrusAuthProvider, b as DocyrusAuthProviderProps, u as useDocyrusAuth, c as useDocyrusClient } from '../use-docyrus-client-
|
|
5
|
-
export { A as AuthManager, D as DEFAULT_API_URL, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, h as hasPermission,
|
|
2
|
+
import { D as DocyrusAuthConfig } from '../types-BcLDyMdw.js';
|
|
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
|
+
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-BVfrHdk1.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
|
-
|
|
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
|
|
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) {
|
|
@@ -1097,6 +1114,10 @@ var AuthManager = class {
|
|
|
1097
1114
|
msGraphClient = null;
|
|
1098
1115
|
reactNativeAuth = null;
|
|
1099
1116
|
tokenRefreshTimer = null;
|
|
1117
|
+
/** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
|
|
1118
|
+
lastScheduledRefreshAt = 0;
|
|
1119
|
+
/** Session the current client was created for — see `getJwtSessionKey`. */
|
|
1120
|
+
sessionKey = null;
|
|
1100
1121
|
/** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
|
|
1101
1122
|
refreshInFlight = null;
|
|
1102
1123
|
listeners = /* @__PURE__ */ new Set();
|
|
@@ -1488,28 +1509,50 @@ var AuthManager = class {
|
|
|
1488
1509
|
}
|
|
1489
1510
|
this.tokens = null;
|
|
1490
1511
|
this.client = null;
|
|
1512
|
+
this.sessionKey = null;
|
|
1491
1513
|
this.user = null;
|
|
1492
1514
|
this.status = "unauthenticated";
|
|
1493
1515
|
this.error = null;
|
|
1494
1516
|
this.notify();
|
|
1495
1517
|
}
|
|
1496
1518
|
/**
|
|
1497
|
-
* Called when valid tokens are received (
|
|
1498
|
-
*
|
|
1499
|
-
*
|
|
1500
|
-
*
|
|
1519
|
+
* Called when valid tokens are received (any mode). In iframe mode that is
|
|
1520
|
+
* every host `signin` message — the first sign-in, the host's answer to each
|
|
1521
|
+
* `token-refresh-request`, and repeats of a token we already hold (the host
|
|
1522
|
+
* answering more than one `signin-ready`, e.g. under React StrictMode).
|
|
1523
|
+
*
|
|
1524
|
+
* The RestApiClient reads tokens lazily through its TokenManager, so a
|
|
1525
|
+
* refreshed token needs no new client. A new client — plus a user fetch —
|
|
1526
|
+
* is reserved for a new session (first sign-in, or the host switching user
|
|
1527
|
+
* or tenant): consumers key caches on client identity, so a fresh instance
|
|
1528
|
+
* makes them reload everything.
|
|
1529
|
+
*
|
|
1530
|
+
* On a new session the first notify() fires with user: null, and a second
|
|
1531
|
+
* one fires once the user is fetched.
|
|
1501
1532
|
*/
|
|
1502
1533
|
setAuthenticated(tokens) {
|
|
1534
|
+
const isRepeat = this.status === "authenticated" && tokens.accessToken === this.tokens?.accessToken && tokens.refreshToken === this.tokens?.refreshToken;
|
|
1535
|
+
if (isRepeat) {
|
|
1536
|
+
this.scheduleTokenRefresh(tokens);
|
|
1537
|
+
return;
|
|
1538
|
+
}
|
|
1539
|
+
const sessionKey = getJwtSessionKey(tokens.accessToken);
|
|
1540
|
+
const isNewSession = !this.client || sessionKey === null || sessionKey !== this.sessionKey;
|
|
1503
1541
|
this.tokens = tokens;
|
|
1542
|
+
this.sessionKey = sessionKey;
|
|
1504
1543
|
this.error = null;
|
|
1505
1544
|
this.status = "authenticated";
|
|
1506
1545
|
if (this.config.ssr) {
|
|
1507
1546
|
syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
|
|
1508
1547
|
}
|
|
1509
|
-
|
|
1548
|
+
if (isNewSession) {
|
|
1549
|
+
this.createClient();
|
|
1550
|
+
}
|
|
1510
1551
|
this.scheduleTokenRefresh(tokens);
|
|
1511
1552
|
this.notify();
|
|
1512
|
-
this.
|
|
1553
|
+
if (isNewSession || !this.user) {
|
|
1554
|
+
this.fetchUser();
|
|
1555
|
+
}
|
|
1513
1556
|
}
|
|
1514
1557
|
/** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
|
|
1515
1558
|
async fetchUser() {
|
|
@@ -1620,18 +1663,13 @@ var AuthManager = class {
|
|
|
1620
1663
|
if (!this.autoRefreshEnabled) return;
|
|
1621
1664
|
const expiresAt = this.resolveExpiry(tokens);
|
|
1622
1665
|
if (!expiresAt) return;
|
|
1623
|
-
const
|
|
1624
|
-
const
|
|
1625
|
-
const
|
|
1626
|
-
|
|
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
|
-
}
|
|
1666
|
+
const now = Date.now();
|
|
1667
|
+
const dueInMs = expiresAt * 1e3 - TOKEN_EXPIRY_BUFFER_SECONDS * 1e3 - now;
|
|
1668
|
+
const throttleMs = this.lastScheduledRefreshAt + MIN_TOKEN_REFRESH_INTERVAL_MS - now;
|
|
1669
|
+
const refreshInMs = Math.max(dueInMs, throttleMs, 0);
|
|
1634
1670
|
this.tokenRefreshTimer = setTimeout(() => {
|
|
1671
|
+
this.tokenRefreshTimer = null;
|
|
1672
|
+
this.lastScheduledRefreshAt = Date.now();
|
|
1635
1673
|
this.handleTokenRefresh().catch((err) => {
|
|
1636
1674
|
this.error = err instanceof Error ? err : new Error(String(err));
|
|
1637
1675
|
this.status = "unauthenticated";
|
|
@@ -1748,24 +1786,72 @@ function hasRole(user, role) {
|
|
|
1748
1786
|
}
|
|
1749
1787
|
return allRoles.some((r) => r.slug === role || r.uid === role);
|
|
1750
1788
|
}
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1789
|
+
var SCOPE_FIELD_BY_TARGET_TYPE = {
|
|
1790
|
+
data_source: "dataSourceId",
|
|
1791
|
+
field: "dataSourceId",
|
|
1792
|
+
app: "appId",
|
|
1793
|
+
ai_tool: "aiToolId"
|
|
1794
|
+
};
|
|
1795
|
+
var GLOBAL_TARGET_TYPES = [
|
|
1796
|
+
"ai",
|
|
1797
|
+
"settings",
|
|
1798
|
+
"devtools"
|
|
1799
|
+
];
|
|
1800
|
+
function toScope(scope) {
|
|
1801
|
+
if (scope == null) return {};
|
|
1802
|
+
if (typeof scope === "string") return { dataSourceId: scope };
|
|
1803
|
+
return scope;
|
|
1804
|
+
}
|
|
1805
|
+
function resolveTargetTypes(scope) {
|
|
1806
|
+
if (scope.targetType) return [scope.targetType];
|
|
1807
|
+
if (scope.dataSourceId != null) return ["data_source"];
|
|
1808
|
+
if (scope.appId != null) return ["app"];
|
|
1809
|
+
if (scope.aiToolId != null) return ["ai_tool"];
|
|
1810
|
+
return GLOBAL_TARGET_TYPES;
|
|
1811
|
+
}
|
|
1812
|
+
function matchesScope(permission, scope) {
|
|
1813
|
+
const field = SCOPE_FIELD_BY_TARGET_TYPE[permission.targetType];
|
|
1814
|
+
if (!field) return true;
|
|
1815
|
+
return (permission[field] ?? null) === (scope[field] ?? null);
|
|
1816
|
+
}
|
|
1817
|
+
function getAllowedOperations(user, scope) {
|
|
1818
|
+
if (!user) return [];
|
|
1819
|
+
const resolved = toScope(scope);
|
|
1820
|
+
const targetTypes = resolveTargetTypes(resolved);
|
|
1821
|
+
const operations = /* @__PURE__ */ new Set();
|
|
1822
|
+
if (user.permissions) {
|
|
1823
|
+
for (const permission of user.permissions) {
|
|
1824
|
+
if (!targetTypes.includes(permission.targetType)) continue;
|
|
1825
|
+
if (!matchesScope(permission, resolved)) continue;
|
|
1826
|
+
for (const op of permission.allowedOperations ?? []) {
|
|
1827
|
+
operations.add(op);
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
return Array.from(operations);
|
|
1756
1831
|
}
|
|
1757
|
-
if (
|
|
1758
|
-
|
|
1832
|
+
if (resolved.appId != null || resolved.aiToolId != null) return [];
|
|
1833
|
+
const dataSourceId = resolved.dataSourceId ?? null;
|
|
1834
|
+
for (const rule of user.aclRules ?? []) {
|
|
1835
|
+
if ((rule.dataSourceId ?? null) !== dataSourceId) continue;
|
|
1836
|
+
for (const op of rule.allowedOperations ?? []) {
|
|
1837
|
+
operations.add(op);
|
|
1838
|
+
}
|
|
1759
1839
|
}
|
|
1840
|
+
return Array.from(operations);
|
|
1841
|
+
}
|
|
1842
|
+
function hasPermission(user, operation, scope, config) {
|
|
1843
|
+
if (!user) return false;
|
|
1844
|
+
if (hasRole(user, "super_admin")) return true;
|
|
1845
|
+
const resolved = toScope(scope);
|
|
1846
|
+
const { dataSourceId } = resolved;
|
|
1760
1847
|
if (dataSourceId) {
|
|
1848
|
+
if (hasRole(user, "global_editor") && GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
|
|
1849
|
+
if (hasRole(user, "global_viewer") && operation === "view") return true;
|
|
1761
1850
|
const alwaysPermitted = config?.alwaysPermittedDataSources ?? DEFAULT_ALWAYS_PERMITTED;
|
|
1762
1851
|
const permittedOps = alwaysPermitted[dataSourceId];
|
|
1763
1852
|
if (permittedOps?.includes(operation)) return true;
|
|
1764
1853
|
}
|
|
1765
|
-
|
|
1766
|
-
return rules.some(
|
|
1767
|
-
(rule) => rule.dataSourceId === dataSourceId && rule.allowedOperations.includes(operation)
|
|
1768
|
-
);
|
|
1854
|
+
return getAllowedOperations(user, resolved).includes(operation);
|
|
1769
1855
|
}
|
|
1770
1856
|
var DocyrusAuthContext = createContext(null);
|
|
1771
1857
|
function DocyrusAuthProvider({
|
|
@@ -1823,7 +1909,7 @@ function DocyrusAuthProvider({
|
|
|
1823
1909
|
return (role) => hasRole(user, role);
|
|
1824
1910
|
}, [user]);
|
|
1825
1911
|
const hasPermission2 = useMemo(() => {
|
|
1826
|
-
return (operation,
|
|
1912
|
+
return (operation, scope) => hasPermission(user, operation, scope);
|
|
1827
1913
|
}, [user]);
|
|
1828
1914
|
const refreshUser = useMemo(() => {
|
|
1829
1915
|
return async () => {
|
|
@@ -1954,6 +2040,6 @@ function useDocyrusClient() {
|
|
|
1954
2040
|
return client;
|
|
1955
2041
|
}
|
|
1956
2042
|
|
|
1957
|
-
export { AuthManager, DEFAULT_API_URL, DEFAULT_OAUTH_SCOPES, DocyrusAuthContext, DocyrusAuthProvider, ReactNativeOAuth2Auth, getAllRoles, hasPermission, hasRole, useDocyrusAuth, useDocyrusClient };
|
|
2043
|
+
export { AuthManager, DEFAULT_API_URL, DEFAULT_OAUTH_SCOPES, DocyrusAuthContext, DocyrusAuthProvider, ReactNativeOAuth2Auth, getAllRoles, getAllowedOperations, hasPermission, hasRole, useDocyrusAuth, useDocyrusClient };
|
|
1958
2044
|
//# sourceMappingURL=index.js.map
|
|
1959
2045
|
//# sourceMappingURL=index.js.map
|