@humanonlyweb/create-nuxtflare 0.2.0 → 0.2.2

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.
@@ -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 challengeMacKey = yield* Mac.key(Mac.hmacSha256, encoder.encode(rawAppSecret)).pipe(Effect.orDie)
102
- const challengeKey = Hex.encode(yield* mac.sign(challengeMacKey, encoder.encode(CHALLENGE_CONTEXT)).pipe(Effect.orDie))
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
- let queue: Promise<unknown> = Promise.resolve()
53
+ const lock = Semaphore.makeUnsafe(1)
54
54
  const run = (statements: ReadonlyArray<Statement>) =>
55
- Effect.tryPromise({
56
- try: () => {
57
- const job = queue.then(async () => {
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
- queue = job.catch(() => undefined)
79
- return job
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 (isValidationError(failure.success)) throw failure.success.httpError
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 importedKeys = new Map<string, Aead.Key<typeof Aead.aes256Gcm>>()
29
-
30
- const keyOf = (keyHex: string) =>
31
- Effect.gen(function* () {
32
- const cached = importedKeys.get(keyHex)
33
- if (cached) return cached
34
- const decoded = Hex.decode(keyHex)
35
- if (decoded._tag === 'Failure' || decoded.success.length !== Aead.aes256Gcm.keyLength)
36
- return yield* new SealError({ message: 'Encryption key must be 64 hex characters (32 bytes).' })
37
- const key = yield* Aead.key(Aead.aes256Gcm, decoded.success).pipe(Effect.mapError(() => new SealError({ message: 'Encryption key was refused.' })))
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* keyOf(keyHex)
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* keyOf(keyHex)
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.' })))
@@ -35,6 +35,10 @@ export const SecondFactorCodeField = Schema.Trim.check(
35
35
 
36
36
  export const TotpSixDigitField = Schema.Trim.check(Schema.isPattern(/^\d{6}$/, { message: 'Enter the 6-digit code from your authenticator app.' }))
37
37
 
38
+ const passwordsMatch = Schema.makeFilter((value: { readonly password: string; readonly confirm: string }) =>
39
+ value.password === value.confirm ? undefined : { path: ['confirm'], issue: 'Passwords do not match.' },
40
+ )
41
+
38
42
  export const LoginFormSchema = Schema.toStandardSchemaV1(
39
43
  formStruct({
40
44
  identity: required(254, 'Enter your email or username.'),
@@ -42,18 +46,35 @@ export const LoginFormSchema = Schema.toStandardSchemaV1(
42
46
  }),
43
47
  )
44
48
 
49
+ export const TotpCodeFormSchema = Schema.toStandardSchemaV1(formStruct({ code: SecondFactorCodeField }))
50
+
45
51
  export const RegisterFormSchema = Schema.toStandardSchemaV1(
46
52
  formStruct({
47
53
  username: UsernameField,
48
54
  email: EmailField,
49
55
  password: PasswordField,
50
56
  confirm: Schema.String,
51
- }),
57
+ }).check(passwordsMatch),
52
58
  )
53
59
 
54
60
  export const ForgotPasswordFormSchema = Schema.toStandardSchemaV1(formStruct({ email: EmailField }))
55
- export const ResetPasswordFormSchema = Schema.toStandardSchemaV1(formStruct({ password: PasswordField, confirm: Schema.String }))
56
- export const ChangeEmailFormSchema = Schema.toStandardSchemaV1(formStruct({ email: EmailField, password: NonEmptyPasswordField }))
61
+
62
+ export const ResetPasswordFormSchema = Schema.toStandardSchemaV1(formStruct({ password: PasswordField, confirm: Schema.String }).check(passwordsMatch))
63
+
64
+ export const ChangeEmailFormSchema = Schema.toStandardSchemaV1(formStruct({ email: EmailField, password: NonEmptyPasswordField, code: Schema.String }))
65
+
57
66
  export const ProfileFormSchema = Schema.toStandardSchemaV1(formStruct({ username: UsernameField }))
58
67
 
68
+ export const SetPasswordFormSchema = Schema.toStandardSchemaV1(formStruct({ currentPassword: Schema.String, newPassword: PasswordField, code: Schema.String }))
69
+
70
+ export const DeleteAccountFormSchema = Schema.toStandardSchemaV1(
71
+ formStruct({
72
+ confirm: required(64, 'Type your username to confirm.'),
73
+ password: Schema.String,
74
+ code: Schema.String,
75
+ }),
76
+ )
77
+
78
+ export const AdminLoginFormSchema = Schema.toStandardSchemaV1(formStruct({ email: EmailField, password: NonEmptyPasswordField }))
79
+
59
80
  export const matchesConfirm = (typed: string, expected: string) => typed.trim().toLowerCase() === expected.toLowerCase()
package/package.json CHANGED
@@ -1,29 +1,25 @@
1
1
  {
2
2
  "name": "@humanonlyweb/create-nuxtflare",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Scaffold a Nuxt 5 + Cloudflare Workers + D1 + Effect v4 app with explicit auth, TOTP 2FA, and admin.",
5
- "license": "MIT",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/humanonlyweb/nuxtflare.git"
9
- },
10
- "homepage": "https://github.com/humanonlyweb/nuxtflare#readme",
11
- "bugs": {
12
- "url": "https://github.com/humanonlyweb/nuxtflare/issues"
13
- },
14
5
  "keywords": [
15
- "nuxt",
16
- "nuxt5",
17
6
  "cloudflare",
18
7
  "cloudflare-workers",
8
+ "create",
19
9
  "d1",
20
10
  "effect",
21
- "starter",
22
- "create"
11
+ "nuxt",
12
+ "nuxt5",
13
+ "starter"
23
14
  ],
24
- "type": "module",
25
- "publishConfig": {
26
- "access": "public"
15
+ "homepage": "https://github.com/humanonlyweb/nuxtflare#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/humanonlyweb/nuxtflare/issues"
18
+ },
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/humanonlyweb/nuxtflare.git"
27
23
  },
28
24
  "bin": {
29
25
  "create-nuxtflare": "./dist/cli.js",
@@ -32,6 +28,10 @@
32
28
  "files": [
33
29
  "dist"
34
30
  ],
31
+ "type": "module",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
35
  "scripts": {
36
36
  "build": "bun scripts/build.ts",
37
37
  "test": "bun test src/scaffold.test.ts",