@humanonlyweb/create-nuxtflare 0.2.4 → 0.2.5
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 +0 -22
- package/dist/cli.js +2 -1
- package/dist/template/.github/workflows/ci.yml +19 -14
- package/dist/template/CLAUDE.md +3 -3
- package/dist/template/app/components/totp-setup.vue +18 -13
- package/dist/template/app/composables/use-account.ts +7 -5
- package/dist/template/app/composables/use-auth.ts +11 -7
- package/dist/template/app/pages/account.vue +2 -1
- package/dist/template/nuxt.config.ts +5 -2
- package/dist/template/package.json +3 -2
- package/dist/template/public/_headers +6 -0
- package/dist/template/server/api/account/index.delete.ts +1 -1
- package/dist/template/server/api/auth/logout-everywhere.post.ts +1 -1
- package/dist/template/server/api/auth/logout.post.ts +3 -11
- package/dist/template/server/api/auth/register.post.ts +11 -3
- package/dist/template/server/api/auth/verify/send.post.ts +11 -4
- package/dist/template/server/app/identity/lockout.ts +10 -5
- package/dist/template/server/app/identity/service.ts +50 -16
- package/dist/template/server/app/identity/sessions.ts +2 -1
- package/dist/template/server/app/identity/totp.test.ts +1 -0
- package/dist/template/server/app/identity/totp.ts +16 -6
- package/dist/template/server/app/identity/verification.ts +29 -7
- package/dist/template/server/core/app-layer.ts +3 -2
- package/dist/template/server/core/db/atomic-d1.ts +12 -6
- package/dist/template/server/core/db/atomic.ts +36 -25
- package/dist/template/server/core/db/migrations.ts +11 -0
- package/dist/template/server/core/db/migrator.ts +0 -10
- package/dist/template/server/core/db/session-d1.ts +56 -0
- package/dist/template/server/core/db/session.test.ts +97 -0
- package/dist/template/server/core/db/session.ts +171 -0
- package/dist/template/server/core/http/handle.ts +13 -3
- package/dist/template/server/core/http/session.ts +49 -1
- package/dist/template/server/core/platform/app-config.ts +2 -0
- package/dist/template/server/core/platform/database.ts +39 -22
- package/dist/template/server/middleware/01-user-session.ts +11 -2
- package/dist/template/server/plugins/page-csp.ts +1 -1
- package/dist/template/server/plugins/sessions.ts +16 -4
- package/dist/template/server/test/kit.ts +4 -0
- package/dist/template/shared/utils/auth.ts +1 -0
- package/dist/template/wrangler.json +3 -0
- package/package.json +1 -1
- /package/dist/template/app/components/{qr-code.vue → qr-code.client.vue} +0 -0
|
@@ -5,6 +5,7 @@ import { Cause, Data, Effect, Exit, Schema } from 'effect'
|
|
|
5
5
|
import { createError, defineHandler, deleteCookie, getCookie, setCookie, setResponseStatus } from 'nuxt/server'
|
|
6
6
|
|
|
7
7
|
import type { AppServices } from '#server/core/app-layer'
|
|
8
|
+
import type { SessionConstraint } from '#server/core/db/session'
|
|
8
9
|
import type { LimitName } from '#server/core/platform/rate-limiter'
|
|
9
10
|
import type { ServiceNotConfigured, UpstreamFailure } from '#server/utils/errors'
|
|
10
11
|
import type { Conflict, NotFound, RateLimited, TooLarge, Unprocessable } from '#shared/domain/errors'
|
|
@@ -20,7 +21,7 @@ import { readKey } from '#shared/utils/unknown'
|
|
|
20
21
|
|
|
21
22
|
import { runtime } from './runtime'
|
|
22
23
|
import { UNSAFE_METHODS, isSameOriginRequest, isWithheld, limitKeyOf, publicFailure } from './security'
|
|
23
|
-
import { UserActor, requestUser } from './session'
|
|
24
|
+
import { UserActor, requestUser, withRequestDbSession } from './session'
|
|
24
25
|
|
|
25
26
|
export type ApiFailure = NotFound | Conflict | Unprocessable | TooLarge | Unauthorized | Forbidden | RateLimited | ServiceNotConfigured | UpstreamFailure
|
|
26
27
|
|
|
@@ -63,6 +64,8 @@ export interface RouteSchemas {
|
|
|
63
64
|
readonly response?: AnySchema
|
|
64
65
|
readonly limit?: LimitName
|
|
65
66
|
readonly captcha?: boolean
|
|
67
|
+
/** D1 read-replication session constraint when `d1Sessions` is enabled (`false` to bypass). */
|
|
68
|
+
readonly dbSession?: SessionConstraint | false
|
|
66
69
|
}
|
|
67
70
|
|
|
68
71
|
type Part<K extends string, S> = S extends AnySchema ? { readonly [P in K]: S['Type'] } : unknown
|
|
@@ -112,8 +115,11 @@ const runEffect = async <A>(
|
|
|
112
115
|
event: RequestEvent,
|
|
113
116
|
program: Effect.Effect<A, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
|
|
114
117
|
audience: Audience,
|
|
118
|
+
dbSession?: SessionConstraint | false,
|
|
115
119
|
): Promise<A> => {
|
|
116
|
-
const exit = await runtime.runPromiseExit(
|
|
120
|
+
const exit = await runtime.runPromiseExit(
|
|
121
|
+
withRequestDbSession(event, program, dbSession).pipe(Effect.annotateLogs({ method: event.req.method, path: logPath(event.req.url) })),
|
|
122
|
+
)
|
|
117
123
|
|
|
118
124
|
if (Exit.isSuccess(exit)) return exit.value
|
|
119
125
|
|
|
@@ -139,8 +145,9 @@ export const respond = async <D extends RouteSchemas>(
|
|
|
139
145
|
event: RequestEvent,
|
|
140
146
|
program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
|
|
141
147
|
audience: Audience,
|
|
148
|
+
dbSession?: SessionConstraint | false,
|
|
142
149
|
): Promise<OutputOf<D>> => {
|
|
143
|
-
const value = await runEffect(event, program, audience)
|
|
150
|
+
const value = await runEffect(event, program, audience, dbSession)
|
|
144
151
|
// Encoded by the route's response schema.
|
|
145
152
|
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
146
153
|
return value as OutputOf<D>
|
|
@@ -165,6 +172,7 @@ export const handlePublic = <const D extends RouteSchemas>(
|
|
|
165
172
|
return encode ? yield* encode(out) : out
|
|
166
173
|
}),
|
|
167
174
|
'public',
|
|
175
|
+
schemas.dbSession,
|
|
168
176
|
)
|
|
169
177
|
if (!schemas.response) setResponseStatus(event, 204)
|
|
170
178
|
return value
|
|
@@ -206,6 +214,7 @@ export const handleAuthed = <const D extends RouteSchemas>(
|
|
|
206
214
|
return encode ? yield* encode(out) : out
|
|
207
215
|
}),
|
|
208
216
|
'authed',
|
|
217
|
+
schemas.dbSession,
|
|
209
218
|
)
|
|
210
219
|
if (!schemas.response) setResponseStatus(event, 204)
|
|
211
220
|
return value
|
|
@@ -242,6 +251,7 @@ export const handleAdmin = <const D extends RouteSchemas>(
|
|
|
242
251
|
return encode ? yield* encode(out) : out
|
|
243
252
|
}),
|
|
244
253
|
'authed',
|
|
254
|
+
schemas.dbSession,
|
|
245
255
|
)
|
|
246
256
|
if (!schemas.response) setResponseStatus(event, 204)
|
|
247
257
|
return value
|
|
@@ -1,10 +1,54 @@
|
|
|
1
1
|
import type { RequestEvent } from 'nuxt/server'
|
|
2
2
|
|
|
3
3
|
import { Context, Effect } from 'effect'
|
|
4
|
+
import { getCookie, setCookie } from 'nuxt/server'
|
|
4
5
|
|
|
6
|
+
import type { SessionConstraint } from '#server/core/db/session'
|
|
7
|
+
|
|
8
|
+
import { isLocalHost } from '#server/app/admin/auth'
|
|
5
9
|
import { Sessions } from '#server/app/identity/sessions'
|
|
10
|
+
import { DbSession } from '#server/core/db/session'
|
|
6
11
|
import { readKey } from '#shared/utils/unknown'
|
|
7
12
|
|
|
13
|
+
export const D1_BOOKMARK_COOKIE = 'app_d1_bm'
|
|
14
|
+
export const D1_BOOKMARK_HEADER = 'x-d1-bookmark'
|
|
15
|
+
const D1_BOOKMARK_MAX_AGE_SECONDS = 60
|
|
16
|
+
|
|
17
|
+
const requestBookmarks = new WeakMap<RequestEvent, string>()
|
|
18
|
+
const revokedEvents = new WeakSet<RequestEvent>()
|
|
19
|
+
|
|
20
|
+
export const isSessionRevokedOnEvent = (event: RequestEvent): boolean => revokedEvents.has(event)
|
|
21
|
+
|
|
22
|
+
/** Wraps an Effect in a request-scoped D1 read-replication session when `d1Sessions` is enabled; zero-cost passthrough otherwise. */
|
|
23
|
+
export const withRequestDbSession = <A, E, R>(
|
|
24
|
+
event: RequestEvent,
|
|
25
|
+
program: Effect.Effect<A, E, R>,
|
|
26
|
+
policy?: SessionConstraint | false,
|
|
27
|
+
): Effect.Effect<A, E, R | DbSession> => {
|
|
28
|
+
if (policy === false) return program
|
|
29
|
+
return DbSession.use((sessions) => {
|
|
30
|
+
if (!sessions.enabled) return program
|
|
31
|
+
const incoming = requestBookmarks.get(event) ?? event.req.headers.get(D1_BOOKMARK_HEADER) ?? getCookie(event, D1_BOOKMARK_COOKIE) ?? undefined
|
|
32
|
+
return sessions.withSession(program, {
|
|
33
|
+
bookmark: incoming,
|
|
34
|
+
constraint: policy,
|
|
35
|
+
onBookmark: (next) => {
|
|
36
|
+
requestBookmarks.set(event, next)
|
|
37
|
+
event.res.headers.set(D1_BOOKMARK_HEADER, next)
|
|
38
|
+
if (next !== incoming) {
|
|
39
|
+
setCookie(event, D1_BOOKMARK_COOKIE, next, {
|
|
40
|
+
httpOnly: true,
|
|
41
|
+
secure: !isLocalHost(event.req.url),
|
|
42
|
+
sameSite: 'lax',
|
|
43
|
+
path: '/',
|
|
44
|
+
maxAge: D1_BOOKMARK_MAX_AGE_SECONDS,
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
|
|
8
52
|
interface WaitUntilHost {
|
|
9
53
|
readonly waitUntil: (promise: Promise<unknown>) => void
|
|
10
54
|
}
|
|
@@ -85,4 +129,8 @@ export const establishUserSession = (
|
|
|
85
129
|
export const updateUserSessionMetadata = (event: RequestEvent, user: { readonly username: string; readonly emailStatus: 'unverified' | 'verified' }) =>
|
|
86
130
|
Effect.promise(() => setUserSession(event, { user: { username: user.username, verified: user.emailStatus === 'verified' } }))
|
|
87
131
|
|
|
88
|
-
export const endUserSession = (event: RequestEvent
|
|
132
|
+
export const endUserSession = (event: RequestEvent, options?: { readonly alreadyRevoked?: boolean }) =>
|
|
133
|
+
Effect.promise(() => {
|
|
134
|
+
if (options?.alreadyRevoked) revokedEvents.add(event)
|
|
135
|
+
return clearUserSession(event)
|
|
136
|
+
})
|
|
@@ -20,6 +20,7 @@ export interface Settings {
|
|
|
20
20
|
readonly turnstileSecret: Redacted.Redacted
|
|
21
21
|
readonly turnstileRequired: boolean
|
|
22
22
|
readonly rateLimitScale: number
|
|
23
|
+
readonly d1Sessions: boolean
|
|
23
24
|
readonly adminEmails: string
|
|
24
25
|
readonly features: FeatureFlags
|
|
25
26
|
}
|
|
@@ -42,6 +43,7 @@ export class AppConfig extends Context.Service<AppConfig, Settings>()('app/platf
|
|
|
42
43
|
turnstileSecret: Redacted.make(config.turnstileSecret),
|
|
43
44
|
turnstileRequired: config.turnstileRequired,
|
|
44
45
|
rateLimitScale: config.rateLimitScale,
|
|
46
|
+
d1Sessions: config.d1Sessions,
|
|
45
47
|
adminEmails: config.adminEmails,
|
|
46
48
|
features: {
|
|
47
49
|
totp: config.public.features.totp,
|
|
@@ -3,6 +3,8 @@ import type { Database as Db0 } from 'db0'
|
|
|
3
3
|
import { Context, Effect, Layer, Schedule, Schema } from 'effect'
|
|
4
4
|
import { useDatabase } from 'nitro/database'
|
|
5
5
|
|
|
6
|
+
import { CurrentDbSession } from '#server/core/db/session'
|
|
7
|
+
|
|
6
8
|
export class DatabaseError extends Schema.TaggedError<DatabaseError, { readonly brand: unique symbol }>()('DatabaseError', {
|
|
7
9
|
message: Schema.String,
|
|
8
10
|
sql: Schema.String,
|
|
@@ -38,25 +40,35 @@ export class Database extends Context.Service<
|
|
|
38
40
|
const failure = (sql: string) => (cause: unknown) => new DatabaseError({ sql, message: cause instanceof Error ? cause.message : String(cause) })
|
|
39
41
|
|
|
40
42
|
const rows = (sql: string, params: ReadonlyArray<Param>) => {
|
|
41
|
-
const query = Effect.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
43
|
+
const query = Effect.gen(function* () {
|
|
44
|
+
const session = yield* CurrentDbSession
|
|
45
|
+
return yield* Effect.tryPromise({
|
|
46
|
+
try: () =>
|
|
47
|
+
session
|
|
48
|
+
? session.all(sql, params)
|
|
49
|
+
: db
|
|
50
|
+
.prepare(sql)
|
|
51
|
+
.bind(...params)
|
|
52
|
+
.all(),
|
|
53
|
+
catch: failure(sql),
|
|
54
|
+
})
|
|
48
55
|
})
|
|
49
56
|
return isReadQuery(sql) ? query.pipe(Effect.retry({ schedule: READ_RETRY, times: 2, while: isTransient })) : query
|
|
50
57
|
}
|
|
51
58
|
|
|
52
59
|
const row = (sql: string, params: ReadonlyArray<Param>) => {
|
|
53
|
-
const query = Effect.
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
+
const query = Effect.gen(function* () {
|
|
61
|
+
const session = yield* CurrentDbSession
|
|
62
|
+
return yield* Effect.tryPromise({
|
|
63
|
+
try: () =>
|
|
64
|
+
session
|
|
65
|
+
? session.first(sql, params)
|
|
66
|
+
: db
|
|
67
|
+
.prepare(sql)
|
|
68
|
+
.bind(...params)
|
|
69
|
+
.get(),
|
|
70
|
+
catch: failure(sql),
|
|
71
|
+
})
|
|
60
72
|
})
|
|
61
73
|
return isReadQuery(sql) ? query.pipe(Effect.retry({ schedule: READ_RETRY, times: 2, while: isTransient })) : query
|
|
62
74
|
}
|
|
@@ -78,15 +90,20 @@ export class Database extends Context.Service<
|
|
|
78
90
|
Effect.withSpan('Database.first'),
|
|
79
91
|
)
|
|
80
92
|
|
|
81
|
-
const run = (sql: string, params: ReadonlyArray<Param> = [])
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
93
|
+
const run = Effect.fn('Database.run')(function* (sql: string, params: ReadonlyArray<Param> = []) {
|
|
94
|
+
const session = yield* CurrentDbSession
|
|
95
|
+
yield* Effect.tryPromise({
|
|
96
|
+
try: async () => {
|
|
97
|
+
if (session) await session.run(sql, params)
|
|
98
|
+
else
|
|
99
|
+
await db
|
|
100
|
+
.prepare(sql)
|
|
101
|
+
.bind(...params)
|
|
102
|
+
.run()
|
|
103
|
+
},
|
|
88
104
|
catch: failure(sql),
|
|
89
|
-
})
|
|
105
|
+
})
|
|
106
|
+
})
|
|
90
107
|
|
|
91
108
|
return Database.of({ all, first, run })
|
|
92
109
|
}
|
|
@@ -2,11 +2,13 @@ import { defineHandler, deleteCookie, getRequestURL, useRuntimeConfig } from 'nu
|
|
|
2
2
|
|
|
3
3
|
import { Sessions } from '#server/app/identity/sessions'
|
|
4
4
|
import { runtime } from '#server/core/http/runtime'
|
|
5
|
-
import { setRequestUser, waitUntilOf } from '#server/core/http/session'
|
|
5
|
+
import { setRequestUser, waitUntilOf, withRequestDbSession } from '#server/core/http/session'
|
|
6
6
|
|
|
7
7
|
const PUBLIC_ONLY_PATHS = new Set([
|
|
8
|
+
'/api/_auth/session',
|
|
8
9
|
'/api/auth/login',
|
|
9
10
|
'/api/auth/login/totp',
|
|
11
|
+
'/api/auth/logout',
|
|
10
12
|
'/api/auth/register',
|
|
11
13
|
'/api/auth/reset',
|
|
12
14
|
'/api/auth/reset/request',
|
|
@@ -25,7 +27,14 @@ export default defineHandler(async (event) => {
|
|
|
25
27
|
const session = await getUserSession(event)
|
|
26
28
|
const sessionId = session.secure?.sessionId
|
|
27
29
|
const waitUntil = waitUntilOf(event)
|
|
28
|
-
const user = sessionId
|
|
30
|
+
const user = sessionId
|
|
31
|
+
? await runtime.runPromise(
|
|
32
|
+
withRequestDbSession(
|
|
33
|
+
event,
|
|
34
|
+
Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined)),
|
|
35
|
+
),
|
|
36
|
+
)
|
|
37
|
+
: undefined
|
|
29
38
|
|
|
30
39
|
if (user && sessionId) {
|
|
31
40
|
setRequestUser(event, user, sessionId)
|
|
@@ -15,7 +15,7 @@ const stampSlots = (slots: string[], nonce: string) => {
|
|
|
15
15
|
* Skipped in dev so Vite HMR works.
|
|
16
16
|
*/
|
|
17
17
|
export default definePlugin(() => {
|
|
18
|
-
if (import.meta.dev) return
|
|
18
|
+
if (import.meta.dev || import.meta.prerender) return
|
|
19
19
|
|
|
20
20
|
const nonces = new WeakMap<RequestEvent, string>()
|
|
21
21
|
const hooks = useServerHooks()
|
|
@@ -3,7 +3,7 @@ import { createError } from 'nuxt/server'
|
|
|
3
3
|
|
|
4
4
|
import { Sessions } from '#server/app/identity/sessions'
|
|
5
5
|
import { runtime } from '#server/core/http/runtime'
|
|
6
|
-
import { waitUntilOf } from '#server/core/http/session'
|
|
6
|
+
import { isSessionRevokedOnEvent, waitUntilOf, withRequestDbSession } from '#server/core/http/session'
|
|
7
7
|
|
|
8
8
|
export default definePlugin(() => {
|
|
9
9
|
sessionHooks.hook('fetch', async (session, event) => {
|
|
@@ -11,13 +11,25 @@ export default definePlugin(() => {
|
|
|
11
11
|
if (!sessionId) return
|
|
12
12
|
|
|
13
13
|
const waitUntil = waitUntilOf(event)
|
|
14
|
-
const user = await runtime.runPromise(
|
|
14
|
+
const user = await runtime.runPromise(
|
|
15
|
+
withRequestDbSession(
|
|
16
|
+
event,
|
|
17
|
+
Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined)),
|
|
18
|
+
),
|
|
19
|
+
)
|
|
15
20
|
if (!user) throw createError({ status: 401, message: 'Please sign in again.' })
|
|
16
21
|
session.user = { username: user.username, verified: user.emailStatus === 'verified' }
|
|
17
22
|
})
|
|
18
23
|
|
|
19
|
-
sessionHooks.hook('clear', async (session) => {
|
|
24
|
+
sessionHooks.hook('clear', async (session, event) => {
|
|
25
|
+
if (isSessionRevokedOnEvent(event)) return
|
|
20
26
|
const sessionId = session.secure?.sessionId
|
|
21
|
-
if (sessionId)
|
|
27
|
+
if (sessionId)
|
|
28
|
+
await runtime.runPromise(
|
|
29
|
+
withRequestDbSession(
|
|
30
|
+
event,
|
|
31
|
+
Sessions.use((sessions) => sessions.end(sessionId)),
|
|
32
|
+
),
|
|
33
|
+
)
|
|
22
34
|
})
|
|
23
35
|
})
|
|
@@ -9,6 +9,7 @@ import type { Mail } from '#server/core/platform/mailer'
|
|
|
9
9
|
import { Features } from '#server/app/features'
|
|
10
10
|
import { AtomicBatch } from '#server/core/db/atomic'
|
|
11
11
|
import { migrations } from '#server/core/db/migrations'
|
|
12
|
+
import { DbSession } from '#server/core/db/session'
|
|
12
13
|
import { AppConfig } from '#server/core/platform/app-config'
|
|
13
14
|
import { Database } from '#server/core/platform/database'
|
|
14
15
|
import { IdGenerator } from '#server/core/platform/id-generator'
|
|
@@ -34,6 +35,7 @@ export const testConfig = (overrides: Partial<Omit<Settings, 'features'>> & { re
|
|
|
34
35
|
turnstileSecret: Redacted.make(''),
|
|
35
36
|
turnstileRequired: false,
|
|
36
37
|
rateLimitScale: 1,
|
|
38
|
+
d1Sessions: false,
|
|
37
39
|
adminEmails: 'admin@starter.test',
|
|
38
40
|
...overrides,
|
|
39
41
|
features: {
|
|
@@ -53,6 +55,7 @@ export const makeTestLayer = async (
|
|
|
53
55
|
readonly turnstile?: Layer.Layer<Turnstile>
|
|
54
56
|
readonly mailer?: Layer.Layer<Mailer>
|
|
55
57
|
readonly limiter?: Layer.Layer<RateLimiter>
|
|
58
|
+
readonly dbSession?: Layer.Layer<DbSession>
|
|
56
59
|
} = {},
|
|
57
60
|
) => {
|
|
58
61
|
const db = createDatabase(nodeSqlite({ name: ':memory:' }))
|
|
@@ -64,6 +67,7 @@ export const makeTestLayer = async (
|
|
|
64
67
|
const platform = Layer.mergeAll(
|
|
65
68
|
Database.layerFor(db),
|
|
66
69
|
AtomicBatch.layerFor(db),
|
|
70
|
+
options.dbSession ?? DbSession.disabled,
|
|
67
71
|
IdGenerator.sequential(),
|
|
68
72
|
Tokens.layer,
|
|
69
73
|
Kv.memory(),
|
|
@@ -60,6 +60,7 @@ export const MeView = Schema.Struct({
|
|
|
60
60
|
emailStatus: EmailStatus,
|
|
61
61
|
hasPassword: Schema.Boolean,
|
|
62
62
|
totpStatus: TotpStatus,
|
|
63
|
+
totpRecoveryCodesLeft: Schema.Int,
|
|
63
64
|
pendingEmailChange: Schema.NullOr(PendingEmailChangeView),
|
|
64
65
|
emailChangedAt: Schema.NullOr(Schema.String),
|
|
65
66
|
})
|
package/package.json
CHANGED
|
File without changes
|