Skip to content

Commit

Permalink
feat: add secretKeyPath for reading key from fs at build-time (#174)
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickMi committed Apr 3, 2023
1 parent c906c6d commit aef64b2
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
1 change: 1 addition & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ module.exports = {
'no-unused-vars': 'off',
'no-redeclare': 'off',
'no-undef': 'off',
'no-empty': 'off',
},
}
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,16 @@
runtimeConfig: {
turnstile: {
secretKey: process.env.NUXT_TURNSTILE_SECRET_KEY || '',
// This can be overridden at runtime via the NUXT_TURNSTILE_SECRET_KEY
// environment variable.
secretKey: '',
},
},
})
```

Alternatively, you may set `turnstile.secretKeyPath` to a path to a file containing the secret key. This will be read at build-time and will override any other explicit `secretKey` you have set.

**Tip**: At runtime you can override site and secret keys with the `NUXT_TURNSTILE_SECRET_KEY` and `NUXT_PUBLIC_TURNSTILE_SITE_KEY` environment variables.

## Usage
Expand Down
15 changes: 14 additions & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { fileURLToPath } from 'node:url'
import fs from 'node:fs'
import { defineNuxtModule, addComponentsDir, addPlugin, addServerHandler } from '@nuxt/kit'
import { join } from 'pathe'
import { join, resolve } from 'pathe'
import defu from 'defu'

export interface ModuleOptions {
/** It is recommended you set the secret key via `runtimeConfig.turnstile.secretKey` or NUXT_TURNSTILE_SECRETKEY */
secretKey?: string
/** Path to a file containing the secret key. */
secretKeyPath?: string
/** Your Turnstile site key */
siteKey?: string
/**
Expand All @@ -32,6 +35,16 @@ export default defineNuxtModule<ModuleOptions>({
return
}

if (options.secretKeyPath) {
try {
options.secretKey = fs.readFileSync(resolve(nuxt.options.rootDir, options.secretKeyPath), 'utf-8')
} catch {}

if (!options.secretKey) {
console.warn(`No secret key present in \`${options.secretKeyPath}\`.`)
}
}

const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.build.transpile.push(runtimeDir)

Expand Down

0 comments on commit aef64b2

Please sign in to comment.