@humanonlyweb/create-nuxtflare 0.2.0 → 0.2.1
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/dist/cli.js +1 -1
- package/dist/template/server/app/identity/service.ts +34 -30
- package/dist/template/server/app/identity/sessions.ts +19 -28
- package/dist/template/server/app/identity/totp.ts +12 -4
- package/dist/template/server/core/db/atomic.ts +9 -11
- package/dist/template/server/core/http/handle.ts +4 -9
- package/dist/template/server/core/platform/seal.ts +13 -16
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -6,7 +6,7 @@ import { basename as basename2, resolve as resolve2 } from "node:path";
|
|
|
6
6
|
// package.json
|
|
7
7
|
var package_default = {
|
|
8
8
|
name: "@humanonlyweb/create-nuxtflare",
|
|
9
|
-
version: "0.2.
|
|
9
|
+
version: "0.2.1",
|
|
10
10
|
description: "Scaffold a Nuxt 5 + Cloudflare Workers + D1 + Effect v4 app with explicit auth, TOTP 2FA, and admin.",
|
|
11
11
|
license: "MIT",
|
|
12
12
|
repository: {
|
|
@@ -383,6 +383,30 @@ export class Identity extends Context.Service<
|
|
|
383
383
|
return toAuthUser(updated)
|
|
384
384
|
})
|
|
385
385
|
|
|
386
|
+
const requireReauth = (
|
|
387
|
+
user: typeof LoginUserRow.Type,
|
|
388
|
+
input: { readonly password?: string | undefined; readonly code?: string | undefined },
|
|
389
|
+
messages: { readonly password: string; readonly code: string },
|
|
390
|
+
) =>
|
|
391
|
+
Effect.gen(function* () {
|
|
392
|
+
if (user.password_hash) {
|
|
393
|
+
const subject = `user:${user.id}`
|
|
394
|
+
yield* lockout.assertUnlocked(subject)
|
|
395
|
+
if (!input.password || !(yield* hasher.verify(user.password_hash, input.password))) {
|
|
396
|
+
yield* lockout.recordFailure(subject)
|
|
397
|
+
return yield* new Unauthorized({ message: messages.password })
|
|
398
|
+
}
|
|
399
|
+
yield* lockout.clear(subject)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const totpState = decodeTotpState(user)
|
|
403
|
+
if (config.features.totp && totpState._tag === 'Enabled') {
|
|
404
|
+
if (!input.code) return yield* new Unauthorized({ message: messages.code })
|
|
405
|
+
const ok = yield* totp.verifySecondFactor(user.id, input.code)
|
|
406
|
+
if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
|
|
407
|
+
}
|
|
408
|
+
})
|
|
409
|
+
|
|
386
410
|
const setPassword = Effect.fn('Identity.setPassword')(function* (
|
|
387
411
|
userId: string,
|
|
388
412
|
input: {
|
|
@@ -402,20 +426,11 @@ export class Identity extends Context.Service<
|
|
|
402
426
|
if (!user) return yield* new NotFound({ resource: 'User', id: userId })
|
|
403
427
|
|
|
404
428
|
if (user.password_hash) {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
}
|
|
411
|
-
yield* lockout.clear(subject)
|
|
412
|
-
|
|
413
|
-
const totpState = decodeTotpState(user)
|
|
414
|
-
if (config.features.totp && totpState._tag === 'Enabled') {
|
|
415
|
-
if (!input.code) return yield* new Unauthorized({ message: 'Enter your verification code to change your password.' })
|
|
416
|
-
const ok = yield* totp.verifySecondFactor(user.id, input.code)
|
|
417
|
-
if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
|
|
418
|
-
}
|
|
429
|
+
yield* requireReauth(
|
|
430
|
+
user,
|
|
431
|
+
{ password: input.currentPassword, code: input.code },
|
|
432
|
+
{ password: 'The current password is not right.', code: 'Enter your verification code to change your password.' },
|
|
433
|
+
)
|
|
419
434
|
|
|
420
435
|
const nextHash = yield* hasher.hash(input.newPassword)
|
|
421
436
|
yield* atomic
|
|
@@ -467,22 +482,11 @@ export class Identity extends Context.Service<
|
|
|
467
482
|
return yield* new Unprocessable({ message: `Type ${user.username} to confirm deletion.` })
|
|
468
483
|
}
|
|
469
484
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
return yield* new Unauthorized({ message: 'Enter your current password to delete your account.' })
|
|
476
|
-
}
|
|
477
|
-
yield* lockout.clear(subject)
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
const totpState = decodeTotpState(user)
|
|
481
|
-
if (config.features.totp && totpState._tag === 'Enabled') {
|
|
482
|
-
if (!input.code) return yield* new Unauthorized({ message: 'Enter your verification code to delete your account.' })
|
|
483
|
-
const ok = yield* totp.verifySecondFactor(user.id, input.code)
|
|
484
|
-
if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
|
|
485
|
-
}
|
|
485
|
+
yield* requireReauth(
|
|
486
|
+
user,
|
|
487
|
+
{ password: input.password, code: input.code },
|
|
488
|
+
{ password: 'Enter your current password to delete your account.', code: 'Enter your verification code to delete your account.' },
|
|
489
|
+
)
|
|
486
490
|
|
|
487
491
|
yield* sessions.forget(userId)
|
|
488
492
|
yield* db.run(`DELETE FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Context, DateTime, Effect, Layer, Schema } from 'effect'
|
|
1
|
+
import { Cache, Context, DateTime, Effect, Layer, Schema } from 'effect'
|
|
2
2
|
|
|
3
3
|
import type { EmailStatus } from '#shared/utils/auth'
|
|
4
4
|
|
|
@@ -38,7 +38,7 @@ export interface SessionUser {
|
|
|
38
38
|
readonly emailStatus: EmailStatus
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
const
|
|
41
|
+
const REMEMBER_TTL = '3 seconds'
|
|
42
42
|
const REMEMBER_MAX = 1000
|
|
43
43
|
|
|
44
44
|
export interface VerifySessionOptions {
|
|
@@ -62,24 +62,18 @@ export class Sessions extends Context.Service<
|
|
|
62
62
|
const db = yield* Database
|
|
63
63
|
const atomic = yield* AtomicBatch
|
|
64
64
|
const ids = yield* IdGenerator
|
|
65
|
-
const remembered =
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
while (remembered.size >= REMEMBER_MAX) {
|
|
76
|
-
const oldest = remembered.keys().next().value
|
|
77
|
-
if (oldest === undefined) break
|
|
78
|
-
remembered.delete(oldest)
|
|
65
|
+
const remembered = yield* Cache.make<string, SessionUser>({
|
|
66
|
+
capacity: REMEMBER_MAX,
|
|
67
|
+
timeToLive: REMEMBER_TTL,
|
|
68
|
+
lookup: () => Effect.die(new Error('Session cache is populated explicitly via Cache.set.')),
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const forgetUser = (userId: string) =>
|
|
72
|
+
Effect.gen(function* () {
|
|
73
|
+
for (const [id, user] of yield* Cache.entries(remembered)) {
|
|
74
|
+
if (user.id === userId) yield* Cache.invalidate(remembered, id)
|
|
79
75
|
}
|
|
80
|
-
}
|
|
81
|
-
remembered.set(sessionId, { user, until: nowMs + REMEMBER_MS })
|
|
82
|
-
}
|
|
76
|
+
})
|
|
83
77
|
|
|
84
78
|
return Sessions.of({
|
|
85
79
|
start: (userId, device = '') =>
|
|
@@ -102,8 +96,8 @@ export class Sessions extends Context.Service<
|
|
|
102
96
|
|
|
103
97
|
verify: (sessionId, options) =>
|
|
104
98
|
Effect.gen(function* () {
|
|
105
|
-
const known =
|
|
106
|
-
if (known
|
|
99
|
+
const known = yield* Cache.getOption(remembered, sessionId)
|
|
100
|
+
if (known._tag === 'Some') return known.value
|
|
107
101
|
|
|
108
102
|
const now = yield* DateTime.now
|
|
109
103
|
const nowStr = DateTime.formatIso(now)
|
|
@@ -141,19 +135,16 @@ export class Sessions extends Context.Service<
|
|
|
141
135
|
}
|
|
142
136
|
|
|
143
137
|
const user: SessionUser = { id: row.id, username: row.username, emailStatus: row.email_status }
|
|
144
|
-
|
|
138
|
+
yield* Cache.set(remembered, sessionId, user)
|
|
145
139
|
return user
|
|
146
140
|
}),
|
|
147
141
|
|
|
148
142
|
end: (sessionId) =>
|
|
149
|
-
Effect.
|
|
150
|
-
Effect.flatMap(() => db.run(`DELETE FROM sessions WHERE id = ?`, [sessionId]).pipe(Effect.orDie)),
|
|
151
|
-
),
|
|
143
|
+
Cache.invalidate(remembered, sessionId).pipe(Effect.andThen(db.run(`DELETE FROM sessions WHERE id = ?`, [sessionId]).pipe(Effect.orDie))),
|
|
152
144
|
|
|
153
|
-
endAll: (userId) =>
|
|
154
|
-
Effect.sync(() => forgetUser(userId)).pipe(Effect.flatMap(() => db.run(`DELETE FROM sessions WHERE user_id = ?`, [userId]).pipe(Effect.orDie))),
|
|
145
|
+
endAll: (userId) => forgetUser(userId).pipe(Effect.andThen(db.run(`DELETE FROM sessions WHERE user_id = ?`, [userId]).pipe(Effect.orDie))),
|
|
155
146
|
|
|
156
|
-
forget:
|
|
147
|
+
forget: forgetUser,
|
|
157
148
|
|
|
158
149
|
recent: (userId, currentId) =>
|
|
159
150
|
Effect.gen(function* () {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Context, Effect, Layer, Redacted, Schema } from 'effect'
|
|
2
|
-
import { Mac, SecureRandom } from 'effect/crypto'
|
|
2
|
+
import { Kdf, Mac, SecureRandom } from 'effect/crypto'
|
|
3
3
|
import { Base64Url, Hex } from 'effect/encoding'
|
|
4
4
|
|
|
5
5
|
import type { RateLimited } from '#shared/domain/errors'
|
|
@@ -93,13 +93,21 @@ export class Totp extends Context.Service<
|
|
|
93
93
|
const lockout = yield* LoginLockout
|
|
94
94
|
const random = yield* SecureRandom.SecureRandom
|
|
95
95
|
const mac = yield* Mac.Mac
|
|
96
|
+
const kdf = yield* Kdf.Kdf
|
|
96
97
|
|
|
97
98
|
const rawAppSecret = Redacted.value(config.appSecret)
|
|
98
99
|
if (rawAppSecret.length < 32) {
|
|
99
100
|
return yield* Effect.die(new Error('NUXT_APP_SECRET must be at least 32 characters (generate with `openssl rand -hex 32`).'))
|
|
100
101
|
}
|
|
101
|
-
const
|
|
102
|
-
|
|
102
|
+
const challengeKey = Hex.encode(
|
|
103
|
+
yield* kdf
|
|
104
|
+
.derive(Kdf.hkdfSha256, encoder.encode(rawAppSecret), {
|
|
105
|
+
salt: encoder.encode('nuxtflare:v1'),
|
|
106
|
+
info: encoder.encode(CHALLENGE_CONTEXT),
|
|
107
|
+
length: 32,
|
|
108
|
+
})
|
|
109
|
+
.pipe(Effect.orDie),
|
|
110
|
+
)
|
|
103
111
|
|
|
104
112
|
const assertFeatureOn = () => (config.features.totp ? Effect.void : Effect.fail(new Forbidden({ message: 'Two-factor authentication is disabled.' })))
|
|
105
113
|
|
|
@@ -358,5 +366,5 @@ export class Totp extends Context.Service<
|
|
|
358
366
|
verifySecondFactor,
|
|
359
367
|
})
|
|
360
368
|
}),
|
|
361
|
-
).pipe(Layer.provide(Layer.mergeAll(SecureRandom.layerWebCrypto, Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)))))
|
|
369
|
+
).pipe(Layer.provide(Layer.mergeAll(SecureRandom.layerWebCrypto, Kdf.layerWebCrypto, Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)))))
|
|
362
370
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Database as Db0 } from 'db0'
|
|
2
2
|
|
|
3
|
-
import { Context, Effect, Layer, Schema } from 'effect'
|
|
3
|
+
import { Context, Effect, Layer, Schema, Semaphore } from 'effect'
|
|
4
4
|
|
|
5
5
|
import { DatabaseError } from '#server/core/platform/database'
|
|
6
6
|
import { readKey } from '#shared/utils/unknown'
|
|
@@ -50,11 +50,11 @@ export class AtomicBatch extends Context.Service<
|
|
|
50
50
|
AtomicBatch.of({ run, runGuarded: makeRunGuarded(run) })
|
|
51
51
|
|
|
52
52
|
static readonly layerFor = (db: Db0) => {
|
|
53
|
-
|
|
53
|
+
const lock = Semaphore.makeUnsafe(1)
|
|
54
54
|
const run = (statements: ReadonlyArray<Statement>) =>
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
lock.withPermit(
|
|
56
|
+
Effect.tryPromise({
|
|
57
|
+
try: async () => {
|
|
58
58
|
await db.exec('BEGIN')
|
|
59
59
|
try {
|
|
60
60
|
const applied: Applied[] = []
|
|
@@ -74,12 +74,10 @@ export class AtomicBatch extends Context.Service<
|
|
|
74
74
|
await db.exec('ROLLBACK')
|
|
75
75
|
throw error
|
|
76
76
|
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
catch: failure,
|
|
82
|
-
})
|
|
77
|
+
},
|
|
78
|
+
catch: failure,
|
|
79
|
+
}),
|
|
80
|
+
)
|
|
83
81
|
|
|
84
82
|
return Layer.succeed(AtomicBatch, AtomicBatch.make(run))
|
|
85
83
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { EventHandler, RequestEvent } from 'nuxt/server'
|
|
2
2
|
|
|
3
3
|
import { getAccessIdentity } from '@humanonlyweb/cf-access'
|
|
4
|
-
import { Cause, Effect, Exit, Schema } from 'effect'
|
|
4
|
+
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'
|
|
@@ -100,17 +100,12 @@ export const guards = (schemas: RouteSchemas, event: RequestEvent) =>
|
|
|
100
100
|
if (schemas.captcha) yield* Turnstile.use((turnstile) => turnstile.verify(event.req.headers.get('x-turnstile-token') ?? undefined, ip))
|
|
101
101
|
})
|
|
102
102
|
|
|
103
|
-
class RequestValidationError {
|
|
104
|
-
readonly _tag = 'RequestValidationError'
|
|
105
|
-
constructor(readonly httpError: unknown) {}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
const isValidationError = (value: unknown): value is RequestValidationError => value instanceof RequestValidationError
|
|
103
|
+
class RequestValidationError extends Data.TaggedError('RequestValidationError')<{ readonly httpError: unknown }> {}
|
|
109
104
|
|
|
110
105
|
const parseInput = (event: RequestEvent, validate: ReturnType<typeof compile>['validate']) =>
|
|
111
106
|
Effect.tryPromise({
|
|
112
107
|
try: () => validateRequest(event, validate),
|
|
113
|
-
catch: (httpError) => new RequestValidationError(httpError),
|
|
108
|
+
catch: (httpError) => new RequestValidationError({ httpError }),
|
|
114
109
|
})
|
|
115
110
|
|
|
116
111
|
const runEffect = async <A>(
|
|
@@ -124,7 +119,7 @@ const runEffect = async <A>(
|
|
|
124
119
|
|
|
125
120
|
const failure = Cause.findError(exit.cause)
|
|
126
121
|
if (failure._tag === 'Success') {
|
|
127
|
-
if (
|
|
122
|
+
if (failure.success._tag === 'RequestValidationError') throw failure.success.httpError
|
|
128
123
|
if (isApiFailure(failure.success)) {
|
|
129
124
|
if (failure.success._tag === 'RateLimited' && failure.success.retryAfterSeconds !== undefined) {
|
|
130
125
|
event.res.headers.set('retry-after', String(failure.success.retryAfterSeconds))
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Context, Effect, Layer, Schema } from 'effect'
|
|
1
|
+
import { Cache, Context, Duration, Effect, Exit, Layer, Schema } from 'effect'
|
|
2
2
|
import { Aead, Digest, SecureRandom } from 'effect/crypto'
|
|
3
3
|
import { Hex } from 'effect/encoding'
|
|
4
4
|
|
|
@@ -25,23 +25,20 @@ export class Seal extends Context.Service<
|
|
|
25
25
|
const aead = yield* Aead.Aead
|
|
26
26
|
const random = yield* SecureRandom.SecureRandom
|
|
27
27
|
const digest = yield* Digest.Digest
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
importedKeys.set(keyHex, key)
|
|
39
|
-
return key
|
|
40
|
-
})
|
|
28
|
+
const keys = yield* Cache.makeWith(
|
|
29
|
+
(keyHex: string) =>
|
|
30
|
+
Effect.gen(function* () {
|
|
31
|
+
const decoded = Hex.decode(keyHex)
|
|
32
|
+
if (decoded._tag === 'Failure' || decoded.success.length !== Aead.aes256Gcm.keyLength)
|
|
33
|
+
return yield* new SealError({ message: 'Encryption key must be 64 hex characters (32 bytes).' })
|
|
34
|
+
return yield* Aead.key(Aead.aes256Gcm, decoded.success).pipe(Effect.mapError(() => new SealError({ message: 'Encryption key was refused.' })))
|
|
35
|
+
}),
|
|
36
|
+
{ capacity: 16, timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero) },
|
|
37
|
+
)
|
|
41
38
|
|
|
42
39
|
const seal = (plain: Uint8Array, keyHex: string, context: string) =>
|
|
43
40
|
Effect.gen(function* () {
|
|
44
|
-
const key = yield*
|
|
41
|
+
const key = yield* Cache.get(keys, keyHex)
|
|
45
42
|
const nonce = yield* random.randomBytes(NONCE_BYTES)
|
|
46
43
|
const body = yield* aead
|
|
47
44
|
.encrypt(key, plain, { nonce, aad: encoder.encode(context) })
|
|
@@ -56,7 +53,7 @@ export class Seal extends Context.Service<
|
|
|
56
53
|
const open = (sealed: Uint8Array, keyHex: string, context: string) =>
|
|
57
54
|
Effect.gen(function* () {
|
|
58
55
|
if (sealed.length < MIN_SEALED_BYTES || sealed[0] !== VERSION) return yield* new SealError({ message: 'Unknown sealed format.' })
|
|
59
|
-
const key = yield*
|
|
56
|
+
const key = yield* Cache.get(keys, keyHex)
|
|
60
57
|
return yield* aead
|
|
61
58
|
.decrypt(key, sealed.slice(1 + NONCE_BYTES), { nonce: sealed.slice(1, 1 + NONCE_BYTES), aad: encoder.encode(context) })
|
|
62
59
|
.pipe(Effect.mapError(() => new SealError({ message: 'Cannot be opened: wrong key, wrong context, or damaged.' })))
|
package/package.json
CHANGED