Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Password salting support #150

Merged
merged 8 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## SERVER:
# Set log verbosity [2]:integer
# 0=error <- 1=warn <- 2=info <- 3=debug
# (0=error <- 1=warn <- 2=info <- 3=debug)
#LOGLEVEL=2

# Port for the server [4000]:integer
Expand All @@ -13,6 +13,10 @@
# Is website served over HTTPS? [true]:boolean
#TLS=true

# Secret for hashing passwords []:string
# (Generate a unique secure secret: echo $(openssl rand -base64 32))
#HASH_SECRET=

## DOCUMENTATION:
# Enable documentation? [false]:boolean
#DOCS_ENABLED=false
Expand Down
22 changes: 18 additions & 4 deletions src/document/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
import { env } from '../server.ts';

const cipherAlgorithm = 'aes-256-gcm';
const hashAlgorithm = 'blake2b256';
const ivLength = 12;
const saltLength = 24;

export const crypto = {
encrypt: (data: Uint8Array, password: string): Uint8Array => {
Expand All @@ -26,19 +28,31 @@ export const crypto = {
},

hash: (password: string, encoding: 'base64' | 'binary' = 'base64'): string | Uint8Array => {
const hasher = new Bun.CryptoHasher(hashAlgorithm).update(password);
const salt = randomBytes(saltLength);

return crypto.hash_salted(password, salt, encoding);
},

hash_salted: (password: string, salt: Buffer, encoding: 'base64' | 'binary' = 'base64'): string | Uint8Array => {
const hasher = new Bun.CryptoHasher(hashAlgorithm).update(
Buffer.concat([Buffer.from(env.hashSecret as string), Buffer.from(password), salt])
);

const hash = Buffer.concat([salt, hasher.digest()]);

switch (encoding) {
case 'base64': {
return hasher.digest('base64');
return hash.toString('base64');
}
default: {
return hasher.digest() as Uint8Array;
return hash as Uint8Array;
}
}
},

compare: (password: string, hash: string, encoding: 'base64' | 'binary' = 'base64'): boolean => {
return crypto.hash(password, encoding) === hash;
const salt = Buffer.from(hash, 'base64').slice(0, saltLength);

return crypto.hash_salted(password, salt, encoding) === hash;
}
} as const;
11 changes: 11 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const env = {
port: envvar('PORT').default(4000).asPortNumber(),
logLevel: envvar('LOGLEVEL').default(2).asIntPositive(),
tls: envvar('TLS').asBoolStrict() ?? true,
hashSecret: envvar('HASH_SECRET').asString(),
documentMaxSize: envvar('DOCUMENT_MAXSIZE').default(1024).asIntPositive(),
docsEnabled: envvar('DOCS_ENABLED').asBoolStrict() ?? false,
debugDB: envvar('DEBUG_DB').asBoolStrict() ?? false,
Expand All @@ -33,6 +34,16 @@ export const db = database.open();
const instance = new OpenAPIHono().basePath(config.apiPath);

export const server = (): typeof instance => {
logger.set(env.logLevel);

// Check env
if (!env.hashSecret) {
logger.error('"HASH_SECRET" value not specified, can\'t continue...');
logger.warn('Update your "HASH_SECRET" environment value, see more at:');
logger.warn('https://github.com/jspaste/backend/raw/stable/.env.example');
process.exit(1);
}

instance.use('*', cors());

instance.onError((err) => {
Expand Down