Skip to content

Commit

Permalink
refactor(types): 🏷️ Improved typings
Browse files Browse the repository at this point in the history
  • Loading branch information
itpropro committed Dec 24, 2023
1 parent 5c11215 commit 71e7fa2
Show file tree
Hide file tree
Showing 15 changed files with 57 additions and 35 deletions.
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ coverage
*.lcov
.nyc_output

# VSCode
.vscode

# Intellij idea
*.iml
.idea
Expand Down
19 changes: 19 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"files.eol": "\n",
// Enable the ESlint flat config support
"eslint.experimental.useFlatConfig": false,
"prettier.enable": false,
"editor.formatOnSave": false,
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
// TypeScript formatter options
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false,
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false,
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": true,
"typescript.format.semicolons": "remove",
"typescript.format.enable": true,
"typescript.preferences.quoteStyle": "single",
"html.format.wrapAttributes": "force-expand-multiline"
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"@nuxt/kit": "^3.8.2",
"defu": "^6.1.3",
"jose": "^5.1.3",
"ofetch": "^1.3.3"
"ofetch": "^1.3.3",
"uncrypto": "^0.1.3"
},
"devDependencies": {
"@nuxt/devtools": "latest",
Expand All @@ -49,6 +50,7 @@
"nuxt": "^3.8.2",
"scule": "^1.1.1",
"typescript": "^5.3.3",
"ufo": "^1.3.2",
"vitest": "^1.1.0",
"vue-tsc": "^1.8.26"
}
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 9 additions & 9 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { defineNuxtModule, addPlugin, createResolver, addImportsDir, addServerHandler, useLogger, extendRouteRules, addRouteMiddleware } from '@nuxt/kit'
import { defu } from 'defu'
import { fileURLToPath } from 'node:url'
import * as providerConfigs from './runtime/providers'
import type { ModuleOptions, ProviderConfigs, Providers } from './runtime/types'
import * as providerPresets from './runtime/providers'
import type { ModuleOptions, ProviderConfigs, ProviderKeys } from './runtime/types'
import { withoutTrailingSlash, cleanDoubleSlashes, withHttps, joinURL } from 'ufo'
import { subtle } from 'uncrypto'
import { genBase64FromBytes, generateRandomUrlSafeString } from './runtime/server/utils/security'
Expand Down Expand Up @@ -40,7 +40,7 @@ export default defineNuxtModule<ModuleOptions>({
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.build.transpile.push(runtimeDir, 'nuxt-oidc-auth')

nuxt.options.alias['#oidc-auth'] = resolve('./types/index')
nuxt.options.alias['#oidcauth'] = resolve('./runtime/types')

if (!options.enabled) { return }

Expand Down Expand Up @@ -130,17 +130,17 @@ export default defineNuxtModule<ModuleOptions>({
}

// Per provider tasks
const providers = Object.keys(options.providers)
const providers = Object.keys(options.providers) as ProviderKeys[]
providers.forEach((provider) => {
// Generate provider routes
if ((options.providers as ProviderConfigs)[provider as Providers].baseUrl) {
options.providers[provider as Providers] = {} as any
if ((options.providers as ProviderConfigs)[provider as ProviderKeys].baseUrl) {
options.providers[provider] = {} as any
// @ts-ignore
options.providers[provider as Providers].authorizationUrl = withoutTrailingSlash(cleanDoubleSlashes(withHttps(joinURL((options.providers)[provider].baseUrl as string, `/${providerConfigs[provider].authorizationUrl}`))))
options.providers[provider].authorizationUrl = withoutTrailingSlash(cleanDoubleSlashes(withHttps(joinURL((options.providers)[provider].baseUrl as string, `/${providerPresets[provider].authorizationUrl}`))))
// @ts-ignore
options.providers[provider as Providers].tokenUrl = withoutTrailingSlash(cleanDoubleSlashes(withHttps(joinURL((options.providers)[provider].baseUrl as string, `/${providerConfigs[provider].tokenUrl}`))))
options.providers[provider].tokenUrl = withoutTrailingSlash(cleanDoubleSlashes(withHttps(joinURL((options.providers)[provider].baseUrl as string, `/${providerPresets[provider].tokenUrl}`))))
// @ts-ignore
options.providers[provider as Providers].userinfoUrl = withoutTrailingSlash(cleanDoubleSlashes(withHttps(joinURL((options.providers)[provider].baseUrl as string, `/${providerConfigs[provider].userinfoUrl}`))))
options.providers[provider].userinfoUrl = withoutTrailingSlash(cleanDoubleSlashes(withHttps(joinURL((options.providers)[provider].baseUrl as string, `/${providerPresets[provider].userinfoUrl}`))))
}
// Validate config

Expand Down
2 changes: 1 addition & 1 deletion src/runtime/composables/oidcAuth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState, computed, useRequestFetch, navigateTo, useRuntimeConfig } from '#imports'
import type { UserSession } from '#oidc-auth'
import type { UserSession } from '#oidcauth'

const useSessionState = () => useState<UserSession>('nuxt-session', () => ({}))

Expand Down
2 changes: 1 addition & 1 deletion src/runtime/providers/auth0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const auth0 = defineOidcProvider<Auth0ProviderConfig, Auth0RequiredFields
'authorizationUrl',
'tokenUrl',
],
async openIdConfiguration(config) {
async openIdConfiguration(config: any) {
const baseUrl = normalizeURL(withoutTrailingSlash(withHttps(config.baseUrl as string)))
return await ofetch(`${baseUrl}/.well-known/openid-configuration`)
},
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/providers/entra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const entra = defineOidcProvider<EntraIdProviderConfig, EntraIdRequiredFi
'tokenUrl',
'redirectUri',
],
async openIdConfiguration(config) {
async openIdConfiguration(config: any) {
const tenantId = parseURL(config.authorizationUrl).pathname.split('/')[1]
const openIdConfig = await ofetch(`https://login.microsoftonline.com/${tenantId}/.well-known/openid-configuration`)
openIdConfig.issuer = [`https://login.microsoftonline.com/${tenantId}/v2.0`, openIdConfig.issuer]
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/providers/provider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { OidcProviderConfig } from '#oidc-auth'
import type { OidcProviderConfig } from '#oidcauth'
import { createDefu } from 'defu'

type MakePropertiesRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;
Expand Down
17 changes: 8 additions & 9 deletions src/runtime/server/lib/oidc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import { eventHandler, createError, getQuery, sendRedirect } from 'h3'
import { withQuery, parseURL, normalizeURL } from 'ufo'
import { ofetch } from 'ofetch'
import { useRuntimeConfig } from '#imports'
import type { OAuthConfig, UserSession, AuthSession, AuthorizationRequest, PkceAuthorizationRequest, TokenRequest, TokenRespose, Providers, PersistentSession, OidcProviderConfig } from '#oidc-auth'
import type { OAuthConfig, UserSession, AuthSession, AuthorizationRequest, PkceAuthorizationRequest, TokenRequest, TokenRespose, ProviderKeys, PersistentSession, OidcProviderConfig, Tokens } from '#oidcauth'
import { validateConfig } from '../utils/config'
import { generateRandomUrlSafeString, generatePkceVerifier, generatePkceCodeChallenge, parseJwtToken, encryptToken, validateToken, genBase64FromString } from '../utils/security'
import * as providerConfigs from '../../providers'
import type { Tokens } from '#oidc-auth/session'
import * as providerPresets from '../../providers'
import { getUserSessionId, clearUserSession } from '../utils/session'
import { configMerger, convertObjectToSnakeCase, generateFormDataRequest, oidcErrorHandler } from '../utils/oidc'
import { useLogger } from '@nuxt/kit'
Expand All @@ -27,8 +26,8 @@ const logger = useLogger('oidc-auth')
export function loginEventHandler({ onError }: OAuthConfig<UserSession>) {
return eventHandler(async (event: H3Event) => {
// TODO: Is this the best way to get the current provider?
const provider = event.path.split('/')[2] as Providers
const config = configMerger(useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig, providerConfigs[provider])
const provider = event.path.split('/')[2] as ProviderKeys
const config = configMerger(useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig, providerPresets[provider])
const validationResult = validateConfig(config, config.requiredProperties)

if (!validationResult.valid) {
Expand Down Expand Up @@ -77,8 +76,8 @@ export function loginEventHandler({ onError }: OAuthConfig<UserSession>) {

export function callbackEventHandler({ onSuccess, onError }: OAuthConfig<UserSession, Omit<Tokens, 'refreshToken'>>) {
return eventHandler(async (event: H3Event) => {
const provider = event.path.split('/')[2] as Providers
const config = configMerger(useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig, providerConfigs[provider])
const provider = event.path.split('/')[2] as ProviderKeys
const config = configMerger(useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig, providerPresets[provider])
const validationResult = validateConfig(config, config.requiredProperties)

if (!validationResult.valid) {
Expand Down Expand Up @@ -253,8 +252,8 @@ export function callbackEventHandler({ onSuccess, onError }: OAuthConfig<UserSes
export function logoutEventHandler({ onSuccess }: OAuthConfig<UserSession>) {
return eventHandler(async (event: H3Event) => {
// TODO: Is this the best way to get the current provider?
const provider = event.path.split('/')[2] as Providers
const config = configMerger(useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig, providerConfigs[provider])
const provider = event.path.split('/')[2] as ProviderKeys
const config = configMerger(useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig, providerPresets[provider])

// Clear session
await clearUserSession(event)
Expand Down
10 changes: 5 additions & 5 deletions src/runtime/server/utils/oidc.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ofetch } from 'ofetch'
import type { Providers, RefreshTokenRequest, TokenRequest, TokenRespose, UserSession } from '#oidc-auth'
import type { RefreshTokenRequest, TokenRequest, TokenRespose, UserSession, ProviderKeys, OidcProviderConfig } from '#oidcauth'
import { snakeCase } from 'scule'
import { normalizeURL } from 'ufo'
import * as providerConfigs from '../../providers'
import * as providerPresets from '../../providers'
import type { H3Event, H3Error } from 'h3'
import { useLogger } from '@nuxt/kit'
import { genBase64FromString, parseJwtToken } from './security'
Expand All @@ -17,8 +17,8 @@ export const configMerger = createDefu((obj, key, value) => {
}
})

export async function refreshAccessToken(provider: Providers, refreshToken: string) {
const config = configMerger(useRuntimeConfig().oidc.providers[provider], providerConfigs[provider])
export async function refreshAccessToken(provider: ProviderKeys, refreshToken: string) {
const config = configMerger(useRuntimeConfig().oidc.providers[provider] as OidcProviderConfig, providerPresets[provider])
// Construct request header object
const headers: HeadersInit = {}

Expand All @@ -33,7 +33,7 @@ export async function refreshAccessToken(provider: Providers, refreshToken: stri
client_id: config.clientId,
refresh_token: refreshToken,
grant_type: 'refresh_token',
...config.scopeInTokenRequest && { scope: config.scope.join(' ') },
...(config.scopeInTokenRequest && config.scope) && { scope: config.scope.join(' ') },
...(config.authenticationScheme === 'body') && { client_secret: normalizeURL(config.clientSecret) }
}
const requestForm = generateFormDataRequest(requestBody)
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/server/utils/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useSession, createError } from 'h3'
import { defu } from 'defu'
import { createHooks } from 'hookable'
import { useRuntimeConfig } from '#imports'
import type { AuthSessionConfig, PersistentSession, Providers, UserSession } from '#oidc-auth'
import type { AuthSessionConfig, PersistentSession, Providers, UserSession } from '#oidcauth'
import { refreshAccessToken } from './oidc'
import { decryptToken, encryptToken, parseJwtToken } from './security'
import { useLogger } from '@nuxt/kit'
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/types/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { H3Event, H3Error } from 'h3'
import type { UserSession } from '#oidc-auth'
import type { UserSession } from '#oidcauth'

export interface OAuthConfig<TUser = UserSession, TTokens = any> {
onSuccess: (
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export * from './session'
export * from './config'
export * from './oidc'

export type Providers = keyof typeof _PROVIDERS
export type ProviderKeys = keyof typeof _PROVIDERS
export type ProviderConfigs = typeof _PROVIDERS

export type RemoveOptionalProps<T> = {
Expand Down
1 change: 0 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"extends": "./.nuxt/tsconfig.json",
"exclude": [
"playground",
"src/module/runtime/server",
"dist",
],
}

0 comments on commit 71e7fa2

Please sign in to comment.