@altafusion/fugue-access-gate 0.0.0-stage → 0.9.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.
@@ -0,0 +1,21 @@
1
+ import type { FugueSimpleAuthConfig } from '../types/config'
2
+ import { shouldShowSimpleAuthSignOut } from '../lib/login'
3
+
4
+ export function useSimpleAuthSignOut(options?: { redirectTo?: string }) {
5
+ const { data: session, refresh } = useSimpleAuthSession()
6
+ const redirectTo = options?.redirectTo ?? '/'
7
+
8
+ const showSignOut = computed(() => shouldShowSimpleAuthSignOut(session.value))
9
+
10
+ async function signOut() {
11
+ const config = useRuntimeConfig().public.fugueSimpleAuth as FugueSimpleAuthConfig
12
+ await $fetch(`${config.apiPrefix}/logout`, { method: 'POST' })
13
+ await refresh()
14
+ await navigateTo(redirectTo)
15
+ }
16
+
17
+ return {
18
+ showSignOut,
19
+ signOut
20
+ }
21
+ }
@@ -0,0 +1,6 @@
1
+ // @ts-check
2
+ import { createPackageEslintConfig } from '@altafusion/eslint-config-preset'
3
+
4
+ export default createPackageEslintConfig({
5
+ ignores: ['**/*.md', 'DESIGN.md']
6
+ })
package/lib/env.ts ADDED
@@ -0,0 +1,61 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import process from 'node:process'
4
+
5
+ export function accessKeyEnvName(envPrefix: string): string {
6
+ return [envPrefix, 'ACCESS', 'KEY'].join('_')
7
+ }
8
+
9
+ export function authEnabledEnvName(envPrefix: string): string {
10
+ return [envPrefix, 'AUTH', 'ENABLED'].join('_')
11
+ }
12
+
13
+ export function parseEnvValue(raw: string): string {
14
+ const value = raw.trim()
15
+ const quoted = (value.startsWith('"') && value.endsWith('"'))
16
+ || (value.startsWith('\'') && value.endsWith('\''))
17
+ return quoted
18
+ ? value.slice(1, -1)
19
+ : value
20
+ }
21
+
22
+ export function readEnvFileValue(name: string): string | undefined {
23
+ try {
24
+ const envPath = join(process.cwd(), '.env')
25
+ const line = readFileSync(envPath, 'utf8')
26
+ .split('\n')
27
+ .find(entry => entry.startsWith(`${name}=`))
28
+
29
+ if (!line)
30
+ return undefined
31
+
32
+ return parseEnvValue(line.slice(name.length + 1))
33
+ } catch {
34
+ return undefined
35
+ }
36
+ }
37
+
38
+ /** Build-time only — checks presence, never serializes the secret. */
39
+ export function isAuthEnabledAtBuild(envPrefix: string): boolean {
40
+ const enabledName = authEnabledEnvName(envPrefix)
41
+ const enabled = process.env[enabledName] ?? readEnvFileValue(enabledName)
42
+ if (enabled === 'true')
43
+ return true
44
+
45
+ const keyName = accessKeyEnvName(envPrefix)
46
+ const key = process.env[keyName] ?? readEnvFileValue(keyName)
47
+ return typeof key === 'string' && key.length > 0
48
+ }
49
+
50
+ /** Runtime access key — dynamic env name avoids Nitro inlining (Netlify secret scan). */
51
+ export function readAccessKey(envPrefix: string, devReloadFromDotEnv = false): string {
52
+ const name = accessKeyEnvName(envPrefix)
53
+ const fromFile = devReloadFromDotEnv
54
+ ? readEnvFileValue(name)
55
+ : undefined
56
+ return fromFile ?? process.env[name] ?? ''
57
+ }
58
+
59
+ export function isAccessKeyConfigured(envPrefix: string, devReloadFromDotEnv = false): boolean {
60
+ return Boolean(readAccessKey(envPrefix, devReloadFromDotEnv))
61
+ }
package/lib/login.ts ADDED
@@ -0,0 +1,67 @@
1
+ export interface SimpleAuthSession {
2
+ authenticated: boolean
3
+ required: boolean
4
+ }
5
+
6
+ /**
7
+ * After the access-key gate, send editors to a public page — not `/_studio`.
8
+ * Studio OAuth is started from the header **Edit** control.
9
+ */
10
+ export function normalizeAuthGateLoginRedirect(targetPath: string, fallback = '/'): string {
11
+ if (!targetPath.startsWith('/'))
12
+ return fallback
13
+
14
+ const queryIndex = targetPath.indexOf('?')
15
+ const pathname = queryIndex === -1
16
+ ? targetPath
17
+ : targetPath.slice(0, queryIndex)
18
+ const search = queryIndex === -1
19
+ ? ''
20
+ : targetPath.slice(queryIndex + 1)
21
+
22
+ if (pathname.startsWith('/__nuxt_studio/'))
23
+ return fallback
24
+
25
+ if (pathname !== '/_studio' && !pathname.startsWith('/_studio/'))
26
+ return targetPath
27
+
28
+ if (search) {
29
+ const inner = new URLSearchParams(search).get('redirect')
30
+ if (inner?.startsWith('/'))
31
+ return inner
32
+ }
33
+
34
+ return fallback
35
+ }
36
+
37
+ export function resolveSimpleAuthRedirect(
38
+ redirectQuery: unknown,
39
+ fallback = '/'
40
+ ): string {
41
+ if (typeof redirectQuery === 'string' && redirectQuery.startsWith('/'))
42
+ return normalizeAuthGateLoginRedirect(redirectQuery, fallback)
43
+
44
+ return fallback
45
+ }
46
+
47
+ export function shouldShowSimpleAuthLogin(session: SimpleAuthSession | null | undefined): boolean {
48
+ return Boolean(session?.required && !session?.authenticated)
49
+ }
50
+
51
+ export function shouldShowSimpleAuthSignOut(session: SimpleAuthSession | null | undefined): boolean {
52
+ return Boolean(session?.required && session?.authenticated)
53
+ }
54
+
55
+ /**
56
+ * POST /api/auth/logout to clear orphan peek-gate cookies when the session API
57
+ * reports they are not active (invalid token, gate off at runtime, or anonymous).
58
+ */
59
+ export function shouldClearStaleAuthSession(session: SimpleAuthSession | null | undefined): boolean {
60
+ if (!session)
61
+ return false
62
+
63
+ if (!session.required)
64
+ return true
65
+
66
+ return !session.authenticated
67
+ }
@@ -0,0 +1,48 @@
1
+ import type { FugueSimpleAuthConfig } from '../types/config'
2
+
3
+ function normalizePrefix(prefix: string): string {
4
+ return prefix.endsWith('/')
5
+ ? prefix
6
+ : `${prefix}/`
7
+ }
8
+
9
+ function matchesProtectedRoute(pathname: string, pattern: string): boolean {
10
+ if (pattern.endsWith('/**')) {
11
+ const base = pattern.slice(0, -3)
12
+ return pathname === base || pathname.startsWith(`${base}/`)
13
+ }
14
+
15
+ return pathname === pattern
16
+ }
17
+
18
+ function isAssetOrAuthPath(pathname: string, config: FugueSimpleAuthConfig): boolean {
19
+ if (config.publicExact.includes(pathname))
20
+ return true
21
+
22
+ if (config.publicPaths.includes(pathname))
23
+ return true
24
+
25
+ if (pathname === config.loginPath)
26
+ return true
27
+
28
+ const apiPrefix = normalizePrefix(config.apiPrefix)
29
+ if (pathname.startsWith(apiPrefix) || pathname === config.apiPrefix)
30
+ return true
31
+
32
+ return config.publicPrefixes.some(prefix => pathname.startsWith(prefix))
33
+ }
34
+
35
+ /** Returns true when the path is reachable without authentication. */
36
+ export function isPathPublic(pathname: string, config: FugueSimpleAuthConfig): boolean {
37
+ if (isAssetOrAuthPath(pathname, config))
38
+ return true
39
+
40
+ if (config.mode === 'full')
41
+ return false
42
+
43
+ return !config.protectedRoutes.some(pattern => matchesProtectedRoute(pathname, pattern))
44
+ }
45
+
46
+ export function shouldGatePath(pathname: string, config: FugueSimpleAuthConfig): boolean {
47
+ return !isPathPublic(pathname, config)
48
+ }
package/lib/session.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { createHmac, timingSafeEqual } from 'node:crypto'
3
+
4
+ export function keysMatch(provided: string, expected: string): boolean {
5
+ const providedBuffer = Buffer.from(provided.trim())
6
+ const expectedBuffer = Buffer.from(expected.trim())
7
+
8
+ if (providedBuffer.length !== expectedBuffer.length)
9
+ return false
10
+
11
+ return timingSafeEqual(providedBuffer, expectedBuffer)
12
+ }
13
+
14
+ export function createSessionToken(accessKey: string, sessionLabel: string): string {
15
+ return createHmac('sha256', accessKey)
16
+ .update(sessionLabel)
17
+ .digest('base64url')
18
+ }
19
+
20
+ export function verifySessionToken(
21
+ token: string,
22
+ accessKey: string,
23
+ sessionLabel: string
24
+ ): boolean {
25
+ const expected = createSessionToken(accessKey, sessionLabel)
26
+
27
+ try {
28
+ return timingSafeEqual(Buffer.from(token), Buffer.from(expected))
29
+ } catch {
30
+ return false
31
+ }
32
+ }
@@ -0,0 +1,237 @@
1
+ import type { Nuxt } from '@nuxt/schema'
2
+ import process from 'node:process'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { addComponent, addImports, createResolver, defineNuxtModule, useLogger } from '@nuxt/kit'
5
+ import { defu } from 'defu'
6
+ import { isAuthEnabledAtBuild } from '../lib/env'
7
+ import { fugueSimpleAuthDefaults } from '../types/config'
8
+
9
+ const layerRoot = fileURLToPath(new URL('..', import.meta.url))
10
+ const resolver = createResolver(import.meta.url)
11
+
12
+ /** Netlify sets NETLIFY; NETLIFY_CI covers some CI/build-runner paths. */
13
+ function isNetlifyBuild(): boolean {
14
+ return Boolean(process.env.NETLIFY || process.env.NETLIFY_CI)
15
+ }
16
+
17
+ /** `nuxt generate` — static export; no Netlify server function is deployed. */
18
+ function isNuxtGenerate(): boolean {
19
+ return process.argv.includes('generate')
20
+ }
21
+
22
+ /** SSR auth gate — requires `nuxt build`, not `nuxt generate`. */
23
+ function useNetlifySsrAuth(authEnabled: boolean): boolean {
24
+ return authEnabled && !isNuxtGenerate()
25
+ }
26
+
27
+ /** Bundle these in the function — externalized vue omits server-renderer (nuxt/nuxt#30224). */
28
+ const VUE_SSR_INLINE = ['vue', '@vue/server-renderer', 'vue/server-renderer'] as const
29
+
30
+ interface NitroExternals { inline?: (string | RegExp)[] }
31
+
32
+ function mergeInlineExternals(
33
+ externals: NitroExternals | undefined,
34
+ additions: readonly string[]
35
+ ): NitroExternals {
36
+ const existing = externals?.inline ?? []
37
+ const inline = [
38
+ ...existing,
39
+ ...additions
40
+ ]
41
+ return {
42
+ ...externals,
43
+ inline: [
44
+ ...new Set(inline)
45
+ ]
46
+ }
47
+ }
48
+
49
+ function configureNetlifySsr(nuxt: Nuxt) {
50
+ // Nuxt 4 defaults externalVue: true, which externalizes vue without server-renderer subpath.
51
+ nuxt.options.experimental.externalVue = false
52
+ nuxt.options.nitro.preset = 'netlify'
53
+ nuxt.options.nitro.externals = mergeInlineExternals(
54
+ nuxt.options.nitro.externals as NitroExternals | undefined,
55
+ VUE_SSR_INLINE
56
+ ) as typeof nuxt.options.nitro.externals
57
+ }
58
+
59
+ function authModeStartupMessage(config: typeof fugueSimpleAuthDefaults): string {
60
+ if (config.mode === 'full')
61
+ return 'Mode: full (whole site gated when access key is set)'
62
+
63
+ if (config.protectedRoutes.length)
64
+ return `Mode: routes (public site open; gated: ${config.protectedRoutes.join(', ')})`
65
+
66
+ return 'Mode: routes (public site open; no protected routes configured)'
67
+ }
68
+
69
+ export default defineNuxtModule({
70
+ meta: {
71
+ name: '@altafusion/fugue-access-gate',
72
+ configKey: 'fugueSimpleAuth'
73
+ },
74
+ defaults: fugueSimpleAuthDefaults,
75
+ setup(options, nuxt) {
76
+ nuxt.options.alias = defu(nuxt.options.alias, {
77
+ '#simple-auth': layerRoot
78
+ })
79
+
80
+ nuxt.options.nitro = defu(nuxt.options.nitro, {
81
+ alias: {
82
+ '#simple-auth': layerRoot
83
+ }
84
+ })
85
+
86
+ addImports([
87
+ {
88
+ name: 'useSimpleAuthLogin',
89
+ from: resolver.resolve('../composables/useSimpleAuthLogin')
90
+ },
91
+ {
92
+ name: 'useSimpleAuthSession',
93
+ from: resolver.resolve('../composables/useSimpleAuthSession')
94
+ },
95
+ {
96
+ name: 'useSimpleAuthSignOut',
97
+ from: resolver.resolve('../composables/useSimpleAuthSignOut')
98
+ },
99
+ {
100
+ name: 'useAppBrand',
101
+ from: resolver.resolve('../composables/useAppBrand')
102
+ }
103
+ ])
104
+
105
+ addComponent({
106
+ name: 'SimpleAuthLoginForm',
107
+ filePath: resolver.resolve('../components/SimpleAuthLoginForm.vue')
108
+ })
109
+
110
+ addComponent({
111
+ name: 'SimpleAuthBrandLogo',
112
+ filePath: resolver.resolve('../components/SimpleAuthBrandLogo.vue')
113
+ })
114
+
115
+ const config = defu(
116
+ nuxt.options.runtimeConfig.public.fugueSimpleAuth,
117
+ options
118
+ ) as typeof fugueSimpleAuthDefaults
119
+
120
+ const authEnabled = isAuthEnabledAtBuild(config.envPrefix)
121
+ const ssrAuth = useNetlifySsrAuth(authEnabled)
122
+ config.authRequired = ssrAuth
123
+ nuxt.options.runtimeConfig.public.fugueSimpleAuth = config
124
+
125
+ const logger = useLogger('fugue-access-gate')
126
+ logger.info(
127
+ authEnabled
128
+ ? authModeStartupMessage(config)
129
+ : `Mode: ${config.mode} (inactive — no ${config.envPrefix}_ACCESS_KEY)`
130
+ )
131
+
132
+ if (!authEnabled)
133
+ return
134
+
135
+ if (authEnabled && isNuxtGenerate() && isNetlifyBuild()) {
136
+ nuxt.hooks.hook('build:done', () => {
137
+ logger.warn(
138
+ 'Auth env is set but the build used `nuxt generate`. '
139
+ + 'SSR redirects were skipped — the preview gate is inactive. '
140
+ + 'Use `nuxt build` with Package directory set for Netlify SSR auth.'
141
+ )
142
+ })
143
+ }
144
+
145
+ nuxt.options.routeRules = defu(nuxt.options.routeRules, {
146
+ [config.loginPath]: { prerender: true },
147
+ ...(ssrAuth
148
+ ? {
149
+ '/**': { ssr: true, prerender: false }
150
+ }
151
+ : {})
152
+ })
153
+
154
+ if (config.mode === 'full') {
155
+ // Nuxt types `robots` as the full module options object. Edit `disallow`
156
+ // through a narrower view so a partial update still typechecks.
157
+ const options = nuxt.options as Omit<typeof nuxt.options, 'robots'> & {
158
+ robots?: { disallow?: string | string[] }
159
+ }
160
+ const current = options.robots?.disallow
161
+ const list = current == null
162
+ ? []
163
+ : Array.isArray(current)
164
+ ? [...current]
165
+ : [current]
166
+ if (!list.includes('/'))
167
+ list.unshift('/')
168
+ options.robots = {
169
+ ...options.robots,
170
+ disallow: list
171
+ }
172
+ }
173
+
174
+ nuxt.options.nitro = defu(nuxt.options.nitro, {})
175
+ if (isNetlifyBuild() && ssrAuth)
176
+ configureNetlifySsr(nuxt)
177
+
178
+ nuxt.options.nitro.prerender = {
179
+ ...nuxt.options.nitro.prerender,
180
+ ...(ssrAuth
181
+ ? { crawlLinks: false }
182
+ : {}),
183
+ routes: [
184
+ ...(nuxt.options.nitro.prerender?.routes ?? []),
185
+ config.loginPath
186
+ ]
187
+ }
188
+
189
+ nuxt.hooks.hook('nitro:config', (nitroConfig) => {
190
+ nitroConfig.prerender = {
191
+ ...nitroConfig.prerender,
192
+ ...(ssrAuth
193
+ ? { crawlLinks: false }
194
+ : {}),
195
+ routes: [
196
+ ...(nitroConfig.prerender?.routes ?? []),
197
+ config.loginPath
198
+ ]
199
+ }
200
+
201
+ if (isNetlifyBuild() && ssrAuth) {
202
+ nitroConfig.preset = nitroConfig.preset ?? 'netlify'
203
+ nitroConfig.externals = mergeInlineExternals(
204
+ nitroConfig.externals as NitroExternals | undefined,
205
+ VUE_SSR_INLINE
206
+ ) as typeof nitroConfig.externals
207
+ }
208
+ })
209
+
210
+ if (!ssrAuth)
211
+ return
212
+
213
+ nuxt.hooks.hook('nitro:build:public-assets', async (nitro) => {
214
+ const { readFile, writeFile } = await import('node:fs/promises')
215
+ const { join } = await import('node:path')
216
+ const redirectsPath = join(nitro.options.output.publicDir, '_redirects')
217
+ const catchAll = [
218
+ '/_nuxt/* /_nuxt/:splat 200',
219
+ '/* /.netlify/functions/server 200'
220
+ ].join('\n')
221
+
222
+ let existing = ''
223
+ try {
224
+ existing = await readFile(redirectsPath, 'utf8')
225
+ } catch {
226
+ // no existing redirects file
227
+ }
228
+
229
+ if (!/^\/\* /m.test(existing)) {
230
+ const contents = existing.trim()
231
+ ? `${existing.trim()}\n${catchAll}\n`
232
+ : `${catchAll}\n`
233
+ await writeFile(redirectsPath, contents)
234
+ }
235
+ })
236
+ }
237
+ })
package/nuxt.config.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @altafusion/fugue-access-gate — Nuxt layer
3
+ *
4
+ * Optional access-key gate with signed session cookie and Netlify SSR hooks.
5
+ * Requires a parent layer or app to register @nuxt/ui (Docus, shell, or fugue-theme).
6
+ */
7
+
8
+ /// <reference path="./types/nuxt-fugue-access-gate.d.ts" />
9
+
10
+ import { fileURLToPath } from 'node:url'
11
+
12
+ export default defineNuxtConfig({
13
+ modules: [
14
+ fileURLToPath(new URL('./modules/simple-auth', import.meta.url))
15
+ ],
16
+
17
+ components: [
18
+ {
19
+ path: './components',
20
+ pathPrefix: false
21
+ }
22
+ ],
23
+
24
+ runtimeConfig: {
25
+ public: {
26
+ fugueSimpleAuth: {
27
+ envPrefix: 'APP',
28
+ cookieName: 'fugue-access-gate',
29
+ sessionLabel: 'fugue-access-gateenticated',
30
+ mode: 'full',
31
+ loginPath: '/login',
32
+ apiPrefix: '/api/auth',
33
+ protectedRoutes: [],
34
+ publicExact: ['/favicon.ico', '/favicon.svg'],
35
+ publicPrefixes: ['/_nuxt/', '/__nuxt/'],
36
+ publicPaths: [],
37
+ loginDescription: 'Enter the access key to continue.',
38
+ authRequired: false
39
+ }
40
+ }
41
+ }
42
+ })
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@altafusion/fugue-access-gate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "0.9.0",
5
+ "description": "Optional access-key gate for Nuxt apps: session cookie, SSR-safe Netlify deploy. Not user authentication; Studio sign-in is separate",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/altafusion/fugue/tree/main/packages-fugue/fugue-access-gate#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/altafusion/fugue/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/altafusion/fugue.git",
14
+ "directory": "packages-fugue/fugue-access-gate"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "exports": {
20
+ ".": "./nuxt.config.ts",
21
+ "./lib/*": "./lib/*.ts",
22
+ "./composables/*": "./composables/*.ts",
23
+ "./types/*": "./types/*.ts"
24
+ },
25
+ "main": "./nuxt.config.ts",
26
+ "peerDependencies": {
27
+ "@nuxt/ui": "^4.0.0",
28
+ "nuxt": ">=4.0.0",
29
+ "vue": "^3.5.0"
30
+ },
31
+ "dependencies": {
32
+ "@nuxt/kit": "^4.7.0",
33
+ "defu": "^6.1.7"
34
+ },
35
+ "devDependencies": {
36
+ "@altafusion/eslint-config-preset": "0.9.0",
37
+ "@altafusion/nuxt-base": "0.9.0",
38
+ "@nuxt/ui": "^4.13.1",
39
+ "@types/node": "^26.6.11",
40
+ "eslint": "^10.16.0",
41
+ "nuxt": "^4.7.0",
42
+ "typescript": "^6.0.3",
43
+ "vitest": "^5.1.2",
44
+ "vue": "^3.5.46"
45
+ },
46
+ "files": [
47
+ "**",
48
+ "!**/*.test.ts",
49
+ "!**/.nuxt",
50
+ "!**/.output",
51
+ "!**/.data",
52
+ "!**/coverage",
53
+ "!**/node_modules"
54
+ ],
55
+ "scripts": {
56
+ "clean": "rm -rf .output .nuxt node_modules/.cache dist",
57
+ "lint": "eslint .",
58
+ "lint:fix": "eslint . --fix"
59
+ }
6
60
  }
@@ -0,0 +1,22 @@
1
+ import { keysMatch } from '#simple-auth/lib/session'
2
+ import { getAccessKey, isAuthRequired } from '../../utils/access-key'
3
+ import { setSessionCookie } from '../../utils/session'
4
+
5
+ export default defineEventHandler(async (event) => {
6
+ if (!isAuthRequired())
7
+ return { authenticated: true }
8
+
9
+ const body = await readBody<{ key?: string }>(event)
10
+ const providedKey = String(body?.key ?? '')
11
+
12
+ if (!keysMatch(providedKey, getAccessKey())) {
13
+ throw createError({
14
+ statusCode: 401,
15
+ statusMessage: 'Invalid access key'
16
+ })
17
+ }
18
+
19
+ setSessionCookie(event, getAccessKey())
20
+
21
+ return { authenticated: true }
22
+ })
@@ -0,0 +1,6 @@
1
+ import { clearSessionCookie } from '../../utils/session'
2
+
3
+ export default defineEventHandler((event) => {
4
+ clearSessionCookie(event)
5
+ return { authenticated: false }
6
+ })
@@ -0,0 +1,12 @@
1
+ import { getAccessKey, isAuthRequired } from '../../utils/access-key'
2
+ import { isAuthenticated } from '../../utils/session'
3
+
4
+ export default defineEventHandler((event) => {
5
+ if (!isAuthRequired())
6
+ return { authenticated: true, required: false }
7
+
8
+ return {
9
+ authenticated: isAuthenticated(event, getAccessKey()),
10
+ required: true
11
+ }
12
+ })
@@ -0,0 +1,25 @@
1
+ import { normalizeAuthGateLoginRedirect } from '#simple-auth/lib/login'
2
+ import { shouldGatePath } from '#simple-auth/lib/path-gate'
3
+ import { getAccessKey, isAuthRequired } from '../utils/access-key'
4
+ import { getSimpleAuthConfig } from '../utils/config'
5
+ import { isAuthenticated } from '../utils/session'
6
+
7
+ export default defineEventHandler((event) => {
8
+ if (!isAuthRequired())
9
+ return
10
+
11
+ const config = getSimpleAuthConfig()
12
+ const pathname = getRequestURL(event).pathname
13
+
14
+ if (!shouldGatePath(pathname, config))
15
+ return
16
+
17
+ if (isAuthenticated(event, getAccessKey()))
18
+ return
19
+
20
+ const returnTo = normalizeAuthGateLoginRedirect(
21
+ pathname + (getRequestURL(event).search || '')
22
+ )
23
+ const redirect = encodeURIComponent(returnTo)
24
+ return sendRedirect(event, `${config.loginPath}?redirect=${redirect}`, 302)
25
+ })
@@ -0,0 +1,12 @@
1
+ import { isAccessKeyConfigured, readAccessKey } from '#simple-auth/lib/env'
2
+ import { getSimpleAuthConfig } from './config'
3
+
4
+ export function getAccessKey(): string {
5
+ const { envPrefix } = getSimpleAuthConfig()
6
+ return readAccessKey(envPrefix, import.meta.dev)
7
+ }
8
+
9
+ export function isAuthRequired(): boolean {
10
+ const { envPrefix } = getSimpleAuthConfig()
11
+ return isAccessKeyConfigured(envPrefix, import.meta.dev)
12
+ }
@@ -0,0 +1,5 @@
1
+ import type { FugueSimpleAuthConfig } from '../../types/config'
2
+
3
+ export function getSimpleAuthConfig(): FugueSimpleAuthConfig {
4
+ return useRuntimeConfig().public.fugueSimpleAuth as FugueSimpleAuthConfig
5
+ }