@docyrus/signin 0.18.2 → 0.19.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 +21 -1
- package/dist/{constants-CvMiR-RM.d.ts → constants-DXgxjFEl.d.ts} +3 -2
- package/dist/core-index.d.ts +3 -3
- package/dist/core-index.js +48 -1
- package/dist/core-index.js.map +1 -1
- package/dist/electron/index.d.ts +2 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +69 -17
- package/dist/index.js.map +1 -1
- package/dist/nextjs/index.d.ts +2 -1
- package/dist/nextjs/index.js.map +1 -1
- package/dist/react-native/index.d.ts +4 -4
- package/dist/react-native/index.js +69 -17
- package/dist/react-native/index.js.map +1 -1
- package/dist/{types-BcLDyMdw.d.ts → types-C3TY5WcX.d.ts} +3 -2
- package/dist/{use-docyrus-client-C9uiHma9.d.ts → use-docyrus-client-D-oTYabD.d.ts} +6 -3
- package/dist/vue/index.d.ts +7 -3
- package/dist/vue/index.js +72 -19
- package/dist/vue/index.js.map +1 -1
- package/package.json +14 -8
package/dist/nextjs/index.d.ts
CHANGED
|
@@ -176,4 +176,5 @@ declare function createMiddlewareClient(request: MiddlewareRequest, config?: Ser
|
|
|
176
176
|
*/
|
|
177
177
|
declare function authMiddleware(config?: AuthMiddlewareConfig): (request: MiddlewareRequest) => Response | undefined;
|
|
178
178
|
|
|
179
|
-
export {
|
|
179
|
+
export { authMiddleware, createMiddlewareClient, createServerClient, getMiddlewareSession, getSession };
|
|
180
|
+
export type { AuthMiddlewareConfig, AuthSession, CookieStore, MiddlewareRequest, ReadonlyCookieStore, ServerClientConfig };
|
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;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e,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"]}
|
|
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;AAsCxB,IAAM,sBAAA,GAAyB,eAAA;;;ACF/B,SAAS,kBAAA,CACd,WAAA,EACA,MAAA,GAA6B,EAAC,EACf;AACf,EAAA,MAAM,MAAA,GAAS,OAAO,MAAA,IAAU,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AkB,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';\nexport const INVALID_HOST_API_URL = 'invalid-host-api-url';\nexport const UNTRUSTED_BACKEND_MESSAGE = 'This app can’t run because its host gave it an untrusted backend address.';\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 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-
|
|
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, b as getAllowedOperations, h as hasPermission, c as hasRole } from '../constants-
|
|
2
|
+
import { D as DocyrusAuthConfig } from '../types-C3TY5WcX.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-C3TY5WcX.js';
|
|
4
|
+
export { D as DocyrusAuthContext, a as DocyrusAuthProvider, b as DocyrusAuthProviderProps, u as useDocyrusAuth, c as useDocyrusClient } from '../use-docyrus-client-D-oTYabD.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-DXgxjFEl.js';
|
|
6
6
|
import 'react';
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { MemoryOAuth2TokenStorage, OAuth2Client, RestApiClient, BrowserOAuth2TokenStorage } from '@docyrus/api-client';
|
|
2
|
-
import { createContext,
|
|
2
|
+
import { createContext, useRef, useState, useEffect, useMemo, use } from 'react';
|
|
3
3
|
import { jsx } from 'react/jsx-runtime';
|
|
4
4
|
|
|
5
5
|
// src/react-native/rn-oauth2-auth.ts
|
|
6
6
|
|
|
7
7
|
// src/constants.ts
|
|
8
8
|
var DEFAULT_API_URL = "https://alpha-api.docyrus.com";
|
|
9
|
+
var INVALID_HOST_API_URL = "invalid-host-api-url";
|
|
10
|
+
var UNTRUSTED_BACKEND_MESSAGE = "This app can\u2019t run because its host gave it an untrusted backend address.";
|
|
9
11
|
var DEFAULT_OAUTH_SCOPES = [
|
|
10
12
|
"offline_access",
|
|
11
13
|
"Read.All",
|
|
@@ -1100,6 +1102,39 @@ function clearTokenCookie(cookieKey) {
|
|
|
1100
1102
|
document.cookie = `${key}=;path=/;max-age=0;SameSite=Lax${secure}`;
|
|
1101
1103
|
}
|
|
1102
1104
|
|
|
1105
|
+
// src/core/host-api-url.ts
|
|
1106
|
+
var LOOPBACK_HOSTS = [
|
|
1107
|
+
"localhost",
|
|
1108
|
+
"127.0.0.1",
|
|
1109
|
+
"[::1]"
|
|
1110
|
+
];
|
|
1111
|
+
var TRUSTED_DOMAINS = ["docyrus.com", "attornaid.com"];
|
|
1112
|
+
function readHostApiUrl() {
|
|
1113
|
+
if (typeof window === "undefined" || !window.location) return void 0;
|
|
1114
|
+
const params = new URLSearchParams(window.location.search);
|
|
1115
|
+
const value = params.get("apiUrl");
|
|
1116
|
+
if (params.get("embedded") !== "true" || value === null) return void 0;
|
|
1117
|
+
try {
|
|
1118
|
+
const url = new URL(value);
|
|
1119
|
+
const {
|
|
1120
|
+
protocol,
|
|
1121
|
+
hostname,
|
|
1122
|
+
username,
|
|
1123
|
+
password,
|
|
1124
|
+
search,
|
|
1125
|
+
hash
|
|
1126
|
+
} = url;
|
|
1127
|
+
const loopback = LOOPBACK_HOSTS.includes(hostname);
|
|
1128
|
+
const trustedDomain = TRUSTED_DOMAINS.some((domain) => hostname === domain || hostname.endsWith(`.${domain}`));
|
|
1129
|
+
if (username || password || search || hash) return null;
|
|
1130
|
+
if (protocol !== "https:" && !(loopback && protocol === "http:")) return null;
|
|
1131
|
+
if (!loopback && !trustedDomain) return null;
|
|
1132
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
1133
|
+
} catch {
|
|
1134
|
+
return null;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1103
1138
|
// src/core/auth-manager.ts
|
|
1104
1139
|
var AuthManager = class {
|
|
1105
1140
|
mode;
|
|
@@ -1127,7 +1162,12 @@ var AuthManager = class {
|
|
|
1127
1162
|
notificationHandlers = /* @__PURE__ */ new Set();
|
|
1128
1163
|
config;
|
|
1129
1164
|
constructor(config = {}) {
|
|
1130
|
-
|
|
1165
|
+
const hostApiUrl = readHostApiUrl();
|
|
1166
|
+
this.config = hostApiUrl ? { ...config, apiUrl: hostApiUrl } : config;
|
|
1167
|
+
if (hostApiUrl === null) {
|
|
1168
|
+
this.status = "error";
|
|
1169
|
+
this.error = new Error(INVALID_HOST_API_URL);
|
|
1170
|
+
}
|
|
1131
1171
|
this.mode = config.forceMode ?? detectAuthMode(config.allowedHostOrigins);
|
|
1132
1172
|
}
|
|
1133
1173
|
/** Whether the provider may refresh tokens on its own. Default: true. */
|
|
@@ -1175,6 +1215,11 @@ var AuthManager = class {
|
|
|
1175
1215
|
}
|
|
1176
1216
|
/** Initialize the auth manager. Must be called once on mount. */
|
|
1177
1217
|
async initialize() {
|
|
1218
|
+
if (this.status === "error") {
|
|
1219
|
+
console.error("[docyrus-signin]", UNTRUSTED_BACKEND_MESSAGE);
|
|
1220
|
+
this.notify();
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1178
1223
|
try {
|
|
1179
1224
|
if (this.mode === "iframe" && this.getInitialTokens()) {
|
|
1180
1225
|
throw new Error(
|
|
@@ -1457,6 +1502,7 @@ var AuthManager = class {
|
|
|
1457
1502
|
* browser redirect flow, such as a prior device authorization flow.
|
|
1458
1503
|
*/
|
|
1459
1504
|
async signInWithTokens(tokens) {
|
|
1505
|
+
if (this.status === "error") throw this.error;
|
|
1460
1506
|
if (this.mode === "iframe") {
|
|
1461
1507
|
throw new Error(
|
|
1462
1508
|
"signInWithTokens() is not supported in iframe mode. Use the host postMessage signin flow or force standalone mode."
|
|
@@ -1491,6 +1537,7 @@ var AuthManager = class {
|
|
|
1491
1537
|
* Iframe: clear local state (host manages the actual session).
|
|
1492
1538
|
*/
|
|
1493
1539
|
async signOut() {
|
|
1540
|
+
if (this.status === "error") return;
|
|
1494
1541
|
this.clearTokenRefreshTimer();
|
|
1495
1542
|
if (this.mode === "standalone" && this.standaloneAuth) {
|
|
1496
1543
|
await this.standaloneAuth.logout();
|
|
@@ -1878,33 +1925,34 @@ function hasPermission(user, operation, scope, config) {
|
|
|
1878
1925
|
var DocyrusAuthContext = createContext(null);
|
|
1879
1926
|
function DocyrusAuthProvider({
|
|
1880
1927
|
children,
|
|
1928
|
+
renderAuthError,
|
|
1881
1929
|
...config
|
|
1882
1930
|
}) {
|
|
1883
|
-
const [status, setStatus] = useState("loading");
|
|
1884
|
-
const [tokens, setTokens] = useState(null);
|
|
1885
|
-
const [client, setClient] = useState(null);
|
|
1886
|
-
const [error, setError] = useState(null);
|
|
1887
|
-
const [user, setUser] = useState(null);
|
|
1888
|
-
const configRef = useRef(config);
|
|
1889
1931
|
const managerRef = useRef(null);
|
|
1890
1932
|
if (!managerRef.current) {
|
|
1891
|
-
managerRef.current = new AuthManager(
|
|
1933
|
+
managerRef.current = new AuthManager(config);
|
|
1892
1934
|
}
|
|
1893
|
-
const
|
|
1935
|
+
const manager = managerRef.current;
|
|
1936
|
+
const mode = manager.getMode();
|
|
1937
|
+
const [status, setStatus] = useState(() => manager.getStatus());
|
|
1938
|
+
const [tokens, setTokens] = useState(null);
|
|
1939
|
+
const [client, setClient] = useState(null);
|
|
1940
|
+
const [error, setError] = useState(() => manager.getError());
|
|
1941
|
+
const [user, setUser] = useState(null);
|
|
1894
1942
|
useEffect(() => {
|
|
1895
|
-
const
|
|
1896
|
-
if (!
|
|
1897
|
-
const unsubscribe =
|
|
1943
|
+
const manager2 = managerRef.current;
|
|
1944
|
+
if (!manager2) return;
|
|
1945
|
+
const unsubscribe = manager2.subscribe((state) => {
|
|
1898
1946
|
setStatus(state.status);
|
|
1899
1947
|
setTokens(state.tokens);
|
|
1900
1948
|
setError(state.error);
|
|
1901
|
-
setClient(
|
|
1949
|
+
setClient(manager2.getClient());
|
|
1902
1950
|
setUser(state.user);
|
|
1903
1951
|
});
|
|
1904
|
-
|
|
1952
|
+
manager2.initialize();
|
|
1905
1953
|
return () => {
|
|
1906
1954
|
unsubscribe();
|
|
1907
|
-
|
|
1955
|
+
manager2.destroy();
|
|
1908
1956
|
};
|
|
1909
1957
|
}, []);
|
|
1910
1958
|
const signIn = useMemo(() => {
|
|
@@ -2044,7 +2092,11 @@ function DocyrusAuthProvider({
|
|
|
2044
2092
|
msGraph,
|
|
2045
2093
|
error
|
|
2046
2094
|
]);
|
|
2047
|
-
|
|
2095
|
+
let content = children;
|
|
2096
|
+
if (status === "error" && error) {
|
|
2097
|
+
content = renderAuthError ? renderAuthError(error) : /* @__PURE__ */ jsx("p", { role: "alert", children: UNTRUSTED_BACKEND_MESSAGE });
|
|
2098
|
+
}
|
|
2099
|
+
return /* @__PURE__ */ jsx(DocyrusAuthContext, { value, children: content });
|
|
2048
2100
|
}
|
|
2049
2101
|
function useDocyrusAuth() {
|
|
2050
2102
|
const context = use(DocyrusAuthContext);
|