Environment Variable Validation (#122)

* Update: env validation and discord token validation

* Add: IPv4 Address Validation

* Update: version increment
This commit is contained in:
Kevin Dang
2024-10-05 19:29:01 -07:00
committed by GitHub
parent 6a9ee2d6d0
commit 947ff89958
4 changed files with 23 additions and 6 deletions

View File

@@ -7,7 +7,7 @@ services:
build: ./ # find docker file in designated path
container_name: discord
restart: always # rebuild container always
image: kevinthedang/discord-ollama:0.6.0
image: kevinthedang/discord-ollama:0.6.1
environment:
CLIENT_TOKEN: ${CLIENT_TOKEN}
MODEL: ${MODEL}

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "discord-ollama",
"version": "0.6.0",
"version": "0.6.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "discord-ollama",
"version": "0.6.0",
"version": "0.6.1",
"license": "ISC",
"dependencies": {
"discord.js": "^14.15.3",

View File

@@ -1,6 +1,6 @@
{
"name": "discord-ollama",
"version": "0.6.0",
"version": "0.6.1",
"description": "Ollama Integration into discord",
"main": "build/index.js",
"exports": "./build/index.js",

View File

@@ -3,16 +3,33 @@ import { config } from 'dotenv'
// resolve config file
const envFilePath = resolve(process.cwd(), '.env')
const ipValidate: RegExp = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/
// set current environment variable file
config({ path: envFilePath })
// Getter for environment variables
/**
* Method to validate if environment variables found in file utils/env.ts
*
* @param name Name of the environment variable in .env
* @param fallback fallback value to set if environment variable is not set (used manually in src/keys.ts)
* @returns environment variable value
*/
export function getEnvVar(name: string, fallback?: string): string {
const value = process.env[name] ?? fallback
if (value == undefined)
if (!value)
throw new Error(`Environment variable ${name} is not set.`)
// validate User-Generated Discord Application Tokens
if (name === "CLIENT_TOKEN")
if (value.length < 72) throw new Error(`The "CLIENT_TOKEN" provided is not of at least length 72.
This is probably an invalid token unless Discord updated their token policy. Please provide a valid token.`)
// validate IPv4 address found in environment variables
if (name.endsWith("_IP") || name.endsWith("_ADDRESS"))
if (!ipValidate.test(value))
throw new Error(`Environment variable ${name} does not follow IPv4 formatting.`)
// return env variable
return value
}