-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_driver.ts
More file actions
71 lines (61 loc) · 1.83 KB
/
Copy pathbase_driver.ts
File metadata and controls
71 lines (61 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* @boringnode/encryption
*
* @license MIT
* @copyright Boring Node
*/
import { createHash } from 'node:crypto'
import * as errors from '../exceptions.ts'
import type { BaseConfig, CypherText } from '../types/main.ts'
import { type Secret } from '@poppinss/utils'
export abstract class BaseDriver {
/**
* The key for encrypting values. It is derived
* from the user provided secret.
*/
cryptoKey: Buffer
/**
* Use `dot` as a separator for joining encrypted value, iv and the
* hmac hash. The idea is borrowed from JWTs.
*/
separator = '.'
protected constructor(config: BaseConfig) {
const key = this.#validateAndGetSecret(config.key)
this.cryptoKey = createHash('sha256').update(key).digest()
}
/**
* Validates the app secret and returns it back as a string
*/
#validateAndGetSecret(secret: string | Secret<string>): string {
if (!secret) {
throw new errors.E_MISSING_ENCRYPTER_KEY()
}
const revealedSecret = typeof secret === 'string' ? secret : secret.release()
if (revealedSecret.length < 16) {
throw new errors.E_INSECURE_ENCRYPTER_KEY()
}
return revealedSecret
}
protected computeReturns(values: string[]) {
return values.join(this.separator) as CypherText
}
/**
* Encrypt a given piece of value using the app secret. A wide range of
* data types are supported.
*
* - String
* - Arrays
* - Objects
* - Booleans
* - Numbers
* - Dates
*
* You can optionally define a purpose for which the value was encrypted and
* mentioning a different purpose/no purpose during decrypt will fail.
*/
abstract encrypt(payload: any, expiresIn?: string | number, purpose?: string): CypherText
/**
* Decrypt value and verify it against a purpose
*/
abstract decrypt<T extends any>(value: string, purpose?: string): T | null
}