import { FetchInstance, FetchConfig } from '@refactorjs/ofetch'; import { FetchResponse } from 'ofetch'; import { NuxtApp } from '#app'; import { CookieSerializeOptions } from 'cookie-es'; import { Ref } from 'vue'; import { _StoreWithState } from 'pinia'; import * as _nuxt_schema from '@nuxt/schema'; import { Nuxt, NuxtPlugin } from '@nuxt/schema'; import { RouteLocationNormalized } from '#vue-router'; interface LocalSchemeEndpoints extends EndpointsOption { login: HTTPRequest; logout: HTTPRequest | false; user: HTTPRequest | false; } interface LocalSchemeOptions extends TokenableSchemeOptions { endpoints: LocalSchemeEndpoints; user: UserOptions; clientId: string; grantType: 'implicit' | 'authorization_code' | 'client_credentials' | 'password' | 'refresh_token' | 'urn:ietf:params:oauth:grant-type:device_code'; scope: string | string[]; } interface CookieSchemeEndpoints extends LocalSchemeEndpoints { csrf?: HTTPRequest | false; } interface CookieSchemeCookie { name: string; } interface CookieSchemeOptions extends LocalSchemeOptions { url?: string; endpoints: CookieSchemeEndpoints; cookie: CookieSchemeCookie; } interface Oauth2SchemeEndpoints extends EndpointsOption { authorization: string; token: string; userInfo: string; logout: string | false; } interface Oauth2SchemeOptions extends SchemeOptions, TokenableSchemeOptions, RefreshableSchemeOptions { endpoints: Oauth2SchemeEndpoints; user: UserOptions; responseMode: 'query.jwt' | 'fragment.jwt' | 'form_post.jwt' | 'jwt' | ''; responseType: 'code' | 'token' | 'id_token' | 'none' | string; grantType: 'implicit' | 'authorization_code' | 'client_credentials' | 'password' | 'refresh_token' | 'urn:ietf:params:oauth:grant-type:device_code'; accessType: 'online' | 'offline'; redirectUri: string; logoutRedirectUri: string; clientId: string; clientSecretTransport: 'body' | 'aurthorization_header'; scope: string | string[]; state: string; codeChallengeMethod: 'implicit' | 'S256' | 'plain' | '' | false; acrValues: string; audience: string; autoLogout: boolean; clientWindow: boolean; clientWindowWidth: number; clientWindowHeight: number; organization?: string; } interface OpenIDConnectSchemeEndpoints extends Oauth2SchemeEndpoints { configuration: string; } interface OpenIDConnectSchemeOptions extends Oauth2SchemeOptions, IdTokenableSchemeOptions { fetchRemote: boolean; endpoints: OpenIDConnectSchemeEndpoints; } /** * @class Storage * @classdesc Storage class for stores and cookies * @param { NuxtApp } ctx - Nuxt app context * @param { ModuleOptions } options - Module options */ declare class Storage { #private; ctx: NuxtApp; options: ModuleOptions; state: AuthState; memory: AuthState; constructor(ctx: NuxtApp, options: ModuleOptions); setUniversal(key: string, value: V, include?: StoreIncludeOptions): V | void; getUniversal(key: string): any; syncUniversal(key: string, defaultValue?: any, include?: StoreIncludeOptions): any; removeUniversal(key: string): void; get pinia(): AuthStore; get store(): Ref; setState(key: string, value: any): unknown; getState(key: string): unknown; watchState(watchKey: string, fn: (value: any) => void): void; removeState(key: string): void; setLocalStorage(key: string, value: V): V | void; getLocalStorage(key: string): any; removeLocalStorage(key: string): void; isLocalStorageEnabled(): boolean; setSessionStorage(key: string, value: V): V | void; getSessionStorage(key: string): any; removeSessionStorage(key: string): void; isSessionStorageEnabled(): boolean; setCookie(key: string, value: V, options?: CookieSerializeOptions): void; getCookies(): Record | void; getCookie(key: string): string | null | undefined; removeCookie(key: string, options?: CookieSerializeOptions): void; isCookiesEnabled(): boolean; } declare class RefreshController { #private; scheme: RefreshableScheme; $auth: Auth; constructor(scheme: RefreshableScheme); handleRefresh(): Promise | void>; } declare class TokenStatus { #private; constructor(token: string | boolean, tokenExpiresAt: number | false, httpOnly?: boolean); unknown(): boolean; valid(): boolean; expired(): boolean; } declare class RefreshToken { #private; scheme: RefreshableScheme; $storage: Storage; constructor(scheme: RefreshableScheme, storage: Storage); get(): string | boolean; set(tokenValue: string | boolean): string | boolean | void | null | undefined; sync(): string | boolean | void | null | undefined; reset(): void; status(): TokenStatus; } declare class RequestHandler { #private; scheme: TokenableScheme | RefreshableScheme; auth: Auth; http: FetchInstance; requestInterceptor: number | null; responseErrorInterceptor: number | null; currentToken: string; constructor(scheme: TokenableScheme | RefreshableScheme, http: FetchInstance, auth: Auth); setHeader(token: string): void; clearHeader(): void; initializeRequestInterceptor(refreshEndpoint?: string | Request): void; reset(): void; } declare class Token { #private; scheme: TokenableScheme; $storage: Storage; constructor(scheme: TokenableScheme, storage: Storage); get(): string | boolean; set(tokenValue: string | boolean, expiresIn?: number | boolean): string | boolean | void | null | undefined; sync(): string | boolean | void | null | undefined; reset(): void; status(): TokenStatus; } type RecursivePartial = { [P in keyof T]?: T[P] extends (infer U)[] ? RecursivePartial[any] : RecursivePartial; }; type PartialExcept = RecursivePartial &Pick; type SchemeNames = 'local' | 'cookie' | 'laravelJWT' | 'openIDConnect' | 'refresh' | 'oauth2' | 'auth0' | N interface UserOptions { property: string | false; autoFetch: boolean; } interface EndpointsOption { [endpoint: string]: string | HTTPRequest | false | undefined; } // Scheme interface SchemeOptions { name?: string; ssr?: boolean; } interface SchemeCheck { valid: boolean; tokenExpired?: boolean; refreshTokenExpired?: boolean; idTokenExpired?: boolean; isRefreshable?: boolean; } interface Scheme { options: OptionsT; name?: string; $auth: Auth; mounted?(...args: any[]): Promise | void>; check?(checkStatus?: boolean): SchemeCheck; login(...args: any[]): Promise | void>; fetchUser(endpoint?: HTTPRequest): Promise | void>; setUserToken?( token: string | boolean, refreshToken?: string | boolean ): Promise | void>; logout?(endpoint?: HTTPRequest): Promise | void; reset?(options?: { resetInterceptor: boolean }): void; } // Token interface TokenOptions { property: string; expiresProperty: string; type: string | false; name: string; maxAge: number | false; global: boolean; required: boolean; prefix: string; expirationPrefix: string; httpOnly: boolean } interface TokenableSchemeOptions extends SchemeOptions { token?: TokenOptions; endpoints: EndpointsOption; } interface TokenableScheme extends Scheme { token?: Token; requestHandler: RequestHandler; } // ID Token interface IdTokenableSchemeOptions extends SchemeOptions { idToken: TokenOptions; } // Refrash interface RefreshTokenOptions { property: string | false; type: string | false; data: string | false; maxAge: number | false; required: boolean; tokenRequired: boolean; prefix: string; expirationPrefix: string; httpOnly: boolean; } interface RefreshableSchemeOptions extends TokenableSchemeOptions { refreshToken: RefreshTokenOptions; } interface RefreshableScheme extends TokenableScheme { refreshToken: RefreshToken; refreshController: RefreshController; refreshTokens(): Promise | void>; } type ProviderNames = 'laravel/sanctum' | 'laravel/jwt' | 'laravel/passport' | 'google' | 'github' | 'facebook' | 'discord' | 'auth0' | N | ((nuxt: Nuxt, strategy: StrategyOptions, ...args: any[]) => void); interface ProviderOptions { scheme?: SchemeNames; clientSecret: string | number; } type ProviderOptionsKeys = Exclude; type ProviderPartialOptions = PartialExcept; type Strategy = S & Strategies; // @ts-ignore: endpoints dont match interface AuthSchemeOptions extends RefreshableSchemeOptions, Oauth2SchemeOptions, CookieSchemeOptions, OpenIDConnectSchemeOptions {} interface Strategies { provider?: ProviderNames; enabled?: boolean; } type StrategyOptions = RecursivePartial> = ProviderPartialOptions; interface ModuleOptions { /** * Whether the global middleware is enabled or not. * This option is disabled if `enableMiddleware` is `false` */ globalMiddleware?: boolean; /** * Whether middleware is enabled or not. */ enableMiddleware?: boolean; /** * Plugins to be used by the module. */ plugins?: (NuxtPlugin | string)[]; /** * Authentication strategies used by the module. */ strategies?: Record; /** * Whether exceptions should be ignored or not. */ ignoreExceptions: boolean; /** * Whether the auth module should reset login data on an error. */ resetOnError: boolean | ((...args: any[]) => boolean); /** * Whether to reset on a response error. */ resetOnResponseError: boolean | ((error: any, auth: Auth, scheme: TokenableScheme | RefreshableScheme) => void); /** * Default authentication strategy to be used by the module. * This is used internally. */ defaultStrategy: string | undefined; /** * Whether to watch user logged in state or not. */ watchLoggedIn: boolean; /** * Interval for token validation. */ tokenValidationInterval: boolean | number; /** * Whether to rewrite redirects or not. */ rewriteRedirects: boolean; /** * Whether to redirect with full path or not. */ fullPathRedirect: boolean; /** * Redirect strategy to be used: 'query' or 'storage' */ redirectStrategy?: 'query' | 'storage'; /** * Key for scope. */ scopeKey: string; /** * Store options for the auth module. The `pinia` store will not * be utilized unless you enable it. By default `useState()` will be * used instead. */ stores: Partial<{ state: { namespace?: string }; pinia: { enabled?: boolean; namespace?: string; }; cookie: { enabled?: boolean; prefix?: string; options?: CookieSerializeOptions; }; local: { enabled: boolean; prefix?: string; }; session: { enabled?: boolean; prefix?: string; }; }>; /** * Redirect URL for login, logout, callback and home. * * *Note:* The `trans` argument is only available if * `nuxt/i18n` is available. */ redirect: { login: string | ((auth: Auth, trans?: Function) => string); logout: string | ((auth: Auth, trans?: Function) => string); callback: string | ((auth: Auth, trans?: Function) => string); home: string | ((auth: Auth, trans?: Function) => string); }; /** * Initial state for Auth. This is used Internally. */ initialState?: AuthState; } type HTTPRequest = FetchConfig & { body?: Record; }; type HTTPResponse = FetchResponse; type Route = RouteLocationNormalized; type AuthStore = _StoreWithState & { [key: string]: AuthState } interface StoreIncludeOptions { cookie?: boolean | CookieSerializeOptions; session?: boolean; local?: boolean; } interface UserInfo { [key: string]: unknown; } type AuthState = { [key: string]: unknown; // user object user?: UserInfo; // indicates whether the user is logged in loggedIn?: boolean; // indicates the strategy of authentication used strategy?: string; // indicates if the authentication system is busy performing tasks, may not be defined initially busy?: boolean; } declare module '#app' { interface NuxtApp { $auth: Auth; } } declare module 'vue-router' { interface RouteMeta { auth?: 'guest' | false } } declare module '@nuxt/schema' { interface NuxtConfig { ['auth']?: Partial } interface NuxtOptions { ['auth']?: ModuleOptions } } type ErrorListener = (...args: any[]) => void; type RedirectListener = (to: string, from: string) => string; declare class Auth { #private; ctx: NuxtApp; options: ModuleOptions; strategies: Record; $storage: Storage; $state: AuthState; error?: Error; constructor(ctx: NuxtApp, options: ModuleOptions); getStrategy(throwException?: boolean): Scheme; get tokenStrategy(): TokenableScheme; get refreshStrategy(): RefreshableScheme; get strategy(): Scheme; get user(): AuthState['user']; get loggedIn(): boolean; get busy(): boolean; init(): Promise; registerStrategy(name: string, strategy: Scheme): void; setStrategy(name: string): Promise | void>; mounted(...args: any[]): Promise | void>; loginWith(name: string, ...args: any[]): Promise | void>; login(...args: any[]): Promise | void>; fetchUser(...args: any[]): Promise | void>; logout(...args: any[]): Promise; setUserToken(token: string | boolean, refreshToken?: string | boolean): Promise | void>; reset(...args: any[]): void; refreshTokens(): Promise | void>; check(...args: any[]): SchemeCheck; fetchUserOnce(...args: any[]): Promise | void>; setUser(user: AuthState | false, schemeCheck?: boolean): void; request(endpoint: HTTPRequest, defaults?: HTTPRequest): Promise>; requestWith(endpoint?: HTTPRequest, defaults?: HTTPRequest): Promise>; wrapLogin(promise: Promise | void>): Promise | void>; onError(listener: ErrorListener): void; callOnError(error: Error, payload?: {}): void; /** * * @param name redirect name * @param route (default: false) Internal useRoute() (false) or manually specify * @param router (default: true) Whether to use nuxt redirect (true) or window redirect (false) * * @returns */ redirect(name: string, route?: Route | false, router?: boolean): void | Promise; onRedirect(listener: RedirectListener): void; callOnRedirect(to: string, from: string): string; hasScope(scope: string): boolean; } declare const _default: _nuxt_schema.NuxtModule<{ stores: { cookie: { secure: boolean; }; }; globalMiddleware?: boolean | undefined; enableMiddleware?: boolean | undefined; plugins?: (string | _nuxt_schema.NuxtPlugin)[] | undefined; strategies?: Record | undefined; ignoreExceptions: boolean; resetOnError: boolean | ((...args: any[]) => boolean); resetOnResponseError: boolean | ((error: any, auth: Auth, scheme: TokenableScheme | RefreshableScheme) => void); defaultStrategy: string | undefined; watchLoggedIn: boolean; tokenValidationInterval: number | boolean; rewriteRedirects: boolean; fullPathRedirect: boolean; redirectStrategy?: "query" | "storage" | undefined; scopeKey: string; redirect: { login: string | ((auth: Auth, trans?: Function | undefined) => string); logout: string | ((auth: Auth, trans?: Function | undefined) => string); callback: string | ((auth: Auth, trans?: Function | undefined) => string); home: string | ((auth: Auth, trans?: Function | undefined) => string); }; initialState?: AuthState | undefined; }>; export { _default as default };