@cslug/core 0.8.0 → 0.10.0

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.
package/docs/api.md CHANGED
@@ -172,6 +172,23 @@ the app binds `role` (`CSLUG_ROLE`: `web`, `worker`, `scheduler`) on every line.
172
172
  | safe serialisation | bigint → string, Date → ISO, `toJSON()` (Money), errors with `code`/`status`/`cause`/`stack`, cycles cut |
173
173
  | `Logger.null()` | Writes nothing |
174
174
 
175
+ ## Encryption and signatures (`Encrypter`)
176
+
177
+ Bound from `config('app.key')` and `config('app.previousKeys')` (`APP_PREVIOUS_KEYS`, comma-separated). Encrypted
178
+ columns, signed URLs, magic links and two-factor secrets use it.
179
+
180
+ | | |
181
+ |---|---|
182
+ | `encrypt(plain)` / `decrypt(stored)` | AES-256-GCM, `v1.<iv>.<tag>.<data>`; decrypts with the current key or a previous one; `crypto.decrypt_failed` |
183
+ | `needsReencrypt(stored)` | Made with a previous key (`cslug db:reencrypt` re-encrypts those columns) |
184
+ | `sign(data)` / `verify(data, signature)` | HMAC-SHA256 base64url; signs with the current key, verifies with any (constant time) |
185
+ | `configured` | `APP_KEY` is set |
186
+ | `Encrypter.random(bytes?)` | Random base64url |
187
+ | `safeEqual(a, b)`, `hmac(key, data)`, `parseKeys(value)` | Helpers |
188
+
189
+ Rotating the key: `cslug key:rotate --write` (new `APP_KEY`, the old one first in `APP_PREVIOUS_KEYS`), deploy,
190
+ `cslug db:reencrypt`, and once links signed before have expired, drop the old key.
191
+
175
192
  ## Tracing and metrics (`Tracer`, `Metrics`)
176
193
 
177
194
  Contracts with no-op implementations bound by default; `@cslug/telemetry` binds ones that record and export. http,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/core",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Application, container and @inject, providers, config, events, logger, errors, context, Clock, Money, i18n, contracts.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -28,6 +28,6 @@
28
28
  "bun": ">=1.3.14"
29
29
  },
30
30
  "peerDependencies": {
31
- "@cslug/validation": "0.8.0"
31
+ "@cslug/validation": "0.10.0"
32
32
  }
33
33
  }
@@ -14,6 +14,7 @@ import {
14
14
  RateLimiter,
15
15
  SessionStore,
16
16
  } from './contracts'
17
+ import { Encrypter, parseKeys } from './encrypter'
17
18
  import { ProviderError } from './errors'
18
19
  import { EventBus } from './events'
19
20
  import { type I18nConfig, Translator } from './i18n'
@@ -60,6 +61,14 @@ export class Application extends Container {
60
61
  Translator.fromDirectory(`${this.rootDir}/resources/lang`, (this.config('i18n') as I18nConfig | undefined) ?? {}),
61
62
  )
62
63
  // in-memory drivers; @cslug/redis replaces them
64
+ this.singleton(
65
+ Encrypter,
66
+ () =>
67
+ new Encrypter(
68
+ this.config<string | undefined>('app.key'),
69
+ parseKeys(this.config<string | string[] | undefined>('app.previousKeys')),
70
+ ),
71
+ )
63
72
  this.singleton(Cache, () => new MemoryCache())
64
73
  // no-op until @cslug/telemetry binds real ones
65
74
  this.singleton(Tracer, () => new NoopTracer())
@@ -0,0 +1,108 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
2
+ import { CslugError } from './errors'
3
+
4
+ /** Compare two secrets in constant time (for their length): tokens, signatures, hashes. */
5
+ export function safeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean {
6
+ const x = typeof a === 'string' ? Buffer.from(a) : a
7
+ const y = typeof b === 'string' ? Buffer.from(b) : b
8
+ return x.length === y.length && timingSafeEqual(x, y)
9
+ }
10
+
11
+ /** HMAC-SHA256 of `data` with `key`, base64url. */
12
+ export function hmac(key: string, data: string): string {
13
+ return createHmac('sha256', key).update(data).digest('base64url')
14
+ }
15
+
16
+ /** `APP_PREVIOUS_KEYS` (comma-separated) or a list, cleaned. */
17
+ export function parseKeys(value: string | readonly string[] | undefined): string[] {
18
+ const list = typeof value === 'string' ? value.split(',') : (value ?? [])
19
+ return list.map((k) => k.trim()).filter(Boolean)
20
+ }
21
+
22
+ /**
23
+ * Encryption and signatures with the app key, and key rotation. New values use `APP_KEY`; values made with a key
24
+ * listed in `APP_PREVIOUS_KEYS` still decrypt and verify, so the key can change without logging everyone out or
25
+ * losing encrypted columns (`cslug key:rotate` explains the steps). Used by encrypted columns, signed URLs, magic
26
+ * links and two-factor secrets.
27
+ */
28
+ export class Encrypter {
29
+ private readonly keys: string[]
30
+ private readonly aesKeys: Buffer[]
31
+
32
+ constructor(current: string | undefined, previous: readonly string[] = []) {
33
+ this.keys = [current, ...previous].filter((k): k is string => !!k)
34
+ if (!current) this.keys = [] // no current key: nothing new can be made, nothing is trusted
35
+ this.aesKeys = this.keys.map((k) => createHash('sha256').update(k).digest())
36
+ }
37
+
38
+ /** True when `APP_KEY` is set. */
39
+ get configured(): boolean {
40
+ return this.keys.length > 0
41
+ }
42
+
43
+ private require(): void {
44
+ if (!this.configured)
45
+ throw new CslugError('crypto.no_key', 'APP_KEY is not set (config app.key). Run `cslug key:generate`.')
46
+ }
47
+
48
+ /** AES-256-GCM with a random IV: `v1.<iv>.<tag>.<ciphertext>` (base64url), with the current key. */
49
+ encrypt(plain: string): string {
50
+ this.require()
51
+ const iv = randomBytes(12)
52
+ const cipher = createCipheriv('aes-256-gcm', this.aesKeys[0] as Buffer, iv)
53
+ const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()])
54
+ return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), data.toString('base64url')].join(
55
+ '.',
56
+ )
57
+ }
58
+
59
+ /** Reverse of `encrypt()`, with the current key or a previous one; `crypto.decrypt_failed` otherwise. */
60
+ decrypt(stored: string): string {
61
+ return this.open(stored).plain
62
+ }
63
+
64
+ /** Whether a value was encrypted with a previous key (re-encrypt it with `encrypt(decrypt(value))`). */
65
+ needsReencrypt(stored: string): boolean {
66
+ return this.open(stored).keyIndex > 0
67
+ }
68
+
69
+ private open(stored: string): { plain: string; keyIndex: number } {
70
+ this.require()
71
+ const [version, iv, tag, data] = stored.split('.')
72
+ if (version !== 'v1' || !iv || !tag || data === undefined)
73
+ throw new CslugError('crypto.decrypt_failed', 'Not an encrypted value')
74
+ for (const [keyIndex, key] of this.aesKeys.entries()) {
75
+ try {
76
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64url'))
77
+ decipher.setAuthTag(Buffer.from(tag, 'base64url'))
78
+ const plain = Buffer.concat([decipher.update(Buffer.from(data, 'base64url')), decipher.final()]).toString(
79
+ 'utf8',
80
+ )
81
+ return { plain, keyIndex }
82
+ } catch {}
83
+ }
84
+ throw new CslugError(
85
+ 'crypto.decrypt_failed',
86
+ 'Could not decrypt a value (a key that is neither APP_KEY nor in APP_PREVIOUS_KEYS, or the value was altered)',
87
+ )
88
+ }
89
+
90
+ /** HMAC-SHA256 (base64url) of `data` with the current key. Prefix `data` with a purpose (`magic:`, a URL). */
91
+ sign(data: string): string {
92
+ this.require()
93
+ return hmac(this.keys[0] as string, data)
94
+ }
95
+
96
+ /** Whether `signature` is `sign(data)` with the current key or a previous one (constant time). */
97
+ verify(data: string, signature: string): boolean {
98
+ if (!this.configured || !signature) return false
99
+ let ok = false
100
+ for (const key of this.keys) ok = safeEqual(hmac(key, data), signature) || ok
101
+ return ok
102
+ }
103
+
104
+ /** Random bytes, base64url (tokens, secrets). */
105
+ static random(bytes = 32): string {
106
+ return randomBytes(bytes).toString('base64url')
107
+ }
108
+ }
package/src/index.ts CHANGED
@@ -63,6 +63,7 @@ export {
63
63
  SessionStore,
64
64
  } from './contracts'
65
65
  export { type Duration, parseDuration } from './duration'
66
+ export { Encrypter, hmac, parseKeys, safeEqual } from './encrypter'
66
67
  export {
67
68
  AppError,
68
69
  BadRequestError,