@raiton/vault 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,339 @@
1
+ import {randomUUID} from "node:crypto"
2
+ import type {
3
+ DestroyKeyInput,
4
+ GeneratedKey,
5
+ GenerateKeyInput,
6
+ KeyAlgorithm,
7
+ KeyFilter,
8
+ KeyUsage,
9
+ KeyVersion,
10
+ KmsProvider,
11
+ RotateKeyInput,
12
+ RotationPolicy,
13
+ VaultAdapter,
14
+ VaultConfig,
15
+ VaultEventContext,
16
+ VaultKey,
17
+ } from "../types.ts"
18
+ import {VAULT_ERRORS, VaultError} from "../errors.ts"
19
+ import {AuditService} from "./audit.ts"
20
+
21
+ export type VaultEventSink = (
22
+ name: string,
23
+ payload: Record<string, unknown>,
24
+ context?: VaultEventContext,
25
+ ) => Promise<void>
26
+
27
+ export interface KeyServiceOptions {
28
+ now?: () => number
29
+ emit?: VaultEventSink
30
+ }
31
+
32
+ const ENCRYPT_USAGES: KeyUsage[] = ["encrypt", "wrap"]
33
+ const DECRYPT_USAGES: KeyUsage[] = ["encrypt", "wrap", "decrypt", "unwrap"]
34
+ const SIGN_USAGES: KeyUsage[] = ["sign", "verify"]
35
+
36
+ export class KeyService {
37
+ private readonly now: () => number
38
+ private readonly emit: VaultEventSink
39
+
40
+ constructor(
41
+ private readonly adapter: VaultAdapter,
42
+ private readonly kms: KmsProvider,
43
+ private readonly config: VaultConfig,
44
+ private readonly audit: AuditService,
45
+ options: KeyServiceOptions = {},
46
+ ) {
47
+ this.now = options.now ?? (() => Date.now())
48
+ this.emit = options.emit ?? (async () => {})
49
+ }
50
+
51
+ async generate(input: GenerateKeyInput): Promise<GeneratedKey> {
52
+ this.assertCapability("keys")
53
+ const alias = String(input.alias ?? "").trim()
54
+ if (!alias) throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {field: "alias"})
55
+
56
+ const existing = await this.adapter.findKeyByAlias(alias, input.tenantId)
57
+ if (existing) throw new VaultError(VAULT_ERRORS.KEY_ALIAS_CONFLICT, {alias, tenantId: input.tenantId})
58
+
59
+ const usage = input.usage ?? "encrypt"
60
+ const algorithm = input.algorithm ?? this.defaultAlgorithm(usage)
61
+ const timestamp = new Date(this.now()).toISOString()
62
+ const keyId = randomUUID()
63
+ const rotation = this.resolveRotation(input.rotation)
64
+
65
+ const material = await this.kms.generate({
66
+ keyId,
67
+ version: 1,
68
+ algorithm,
69
+ tenantId: input.tenantId,
70
+ })
71
+
72
+ const key: VaultKey = {
73
+ id: keyId,
74
+ tenantId: input.tenantId,
75
+ alias,
76
+ usage,
77
+ algorithm,
78
+ status: "active",
79
+ currentVersion: 1,
80
+ rotation,
81
+ ownerId: input.ownerId ?? input.actor?.actorId,
82
+ metadata: input.metadata,
83
+ createdAt: timestamp,
84
+ updatedAt: timestamp,
85
+ }
86
+ const version: KeyVersion = {
87
+ id: randomUUID(),
88
+ keyId,
89
+ version: 1,
90
+ materialRef: material.ref,
91
+ algorithm,
92
+ status: "active",
93
+ createdAt: timestamp,
94
+ activatedAt: timestamp,
95
+ }
96
+
97
+ await this.adapter.createKey(key)
98
+ await this.adapter.createKeyVersion(version)
99
+
100
+ const actor = this.actorOf(input, key)
101
+ await this.audit.record({
102
+ action: "key.generate",
103
+ outcome: "success",
104
+ resourceType: "key",
105
+ resourceId: key.id,
106
+ keyId: key.id,
107
+ keyVersion: version.version,
108
+ actor,
109
+ context: {alias, usage, algorithm},
110
+ })
111
+ await this.emit("VaultKeyCreated", {
112
+ keyId: key.id,
113
+ alias: key.alias,
114
+ usage: key.usage,
115
+ algorithm: key.algorithm,
116
+ version: version.version,
117
+ }, actor)
118
+
119
+ return {key, version}
120
+ }
121
+
122
+ async rotate(input: RotateKeyInput): Promise<GeneratedKey> {
123
+ this.assertCapability("keys")
124
+ const key = await this.resolve(input.key, input.tenantId)
125
+ if (key.status === "destroyed") throw new VaultError(VAULT_ERRORS.KEY_DESTROYED, {keyId: key.id})
126
+ if (key.status === "retired") throw new VaultError(VAULT_ERRORS.KEY_RETIRED, {keyId: key.id})
127
+
128
+ const previous = await this.activeVersion(key)
129
+ const nextVersion = key.currentVersion + 1
130
+ const timestamp = new Date(this.now()).toISOString()
131
+ const material = await this.kms.generate({
132
+ keyId: key.id,
133
+ version: nextVersion,
134
+ algorithm: key.algorithm,
135
+ tenantId: key.tenantId,
136
+ })
137
+
138
+ const version: KeyVersion = {
139
+ id: randomUUID(),
140
+ keyId: key.id,
141
+ version: nextVersion,
142
+ materialRef: material.ref,
143
+ algorithm: key.algorithm,
144
+ status: "active",
145
+ createdAt: timestamp,
146
+ activatedAt: timestamp,
147
+ }
148
+
149
+ previous.status = "deprecated"
150
+ previous.deprecatedAt = timestamp
151
+ await this.adapter.updateKeyVersion(previous)
152
+ await this.adapter.createKeyVersion(version)
153
+
154
+ key.currentVersion = nextVersion
155
+ key.status = "active"
156
+ key.updatedAt = timestamp
157
+ await this.adapter.updateKey(key)
158
+
159
+ const actor = this.actorOf(input, key)
160
+ await this.audit.record({
161
+ action: "key.rotate",
162
+ outcome: "success",
163
+ resourceType: "key",
164
+ resourceId: key.id,
165
+ keyId: key.id,
166
+ keyVersion: nextVersion,
167
+ actor,
168
+ context: {fromVersion: previous.version, toVersion: nextVersion, reason: input.reason},
169
+ })
170
+ await this.emit("VaultKeyRotated", {
171
+ keyId: key.id,
172
+ alias: key.alias,
173
+ fromVersion: previous.version,
174
+ toVersion: nextVersion,
175
+ }, actor)
176
+
177
+ return {key, version}
178
+ }
179
+
180
+ async destroy(input: DestroyKeyInput): Promise<VaultKey> {
181
+ this.assertCapability("keys")
182
+ const key = await this.resolve(input.key, input.tenantId)
183
+ if (key.status === "destroyed") return key
184
+
185
+ const versions = await this.adapter.listKeyVersions(key.id)
186
+ const timestamp = new Date(this.now()).toISOString()
187
+ for (const version of versions) {
188
+ if (version.status === "destroyed") continue
189
+ await this.kms.destroy(version.materialRef)
190
+ version.status = "destroyed"
191
+ version.destroyedAt = timestamp
192
+ await this.adapter.updateKeyVersion(version)
193
+ }
194
+
195
+ key.status = "destroyed"
196
+ key.updatedAt = timestamp
197
+ await this.adapter.updateKey(key)
198
+
199
+ const actor = this.actorOf(input, key)
200
+ await this.audit.record({
201
+ action: "key.destroy",
202
+ outcome: "success",
203
+ resourceType: "key",
204
+ resourceId: key.id,
205
+ keyId: key.id,
206
+ actor,
207
+ context: {versions: versions.map(version => version.version), reason: input.reason},
208
+ })
209
+ await this.emit("VaultKeyDestroyed", {
210
+ keyId: key.id,
211
+ alias: key.alias,
212
+ versions: versions.map(version => version.version),
213
+ }, actor)
214
+
215
+ return key
216
+ }
217
+
218
+ async resolve(reference: string, tenantId?: string): Promise<VaultKey> {
219
+ const byId = await this.adapter.getKey(reference)
220
+ const key = byId ?? await this.adapter.findKeyByAlias(reference, tenantId)
221
+ if (!key) throw new VaultError(VAULT_ERRORS.KEY_NOT_FOUND, {reference})
222
+ if (key.tenantId !== undefined && tenantId !== undefined && key.tenantId !== tenantId) {
223
+ throw new VaultError(VAULT_ERRORS.TENANT_FORBIDDEN, {resource: "key"})
224
+ }
225
+ if (key.status === "destroyed") throw new VaultError(VAULT_ERRORS.KEY_DESTROYED, {keyId: key.id})
226
+ if (key.status === "retired") throw new VaultError(VAULT_ERRORS.KEY_RETIRED, {keyId: key.id})
227
+ return key
228
+ }
229
+
230
+ async get(reference: string, tenantId?: string): Promise<VaultKey> {
231
+ return this.resolve(reference, tenantId)
232
+ }
233
+
234
+ async list(filter: KeyFilter = {}): Promise<VaultKey[]> {
235
+ this.assertCapability("keys")
236
+ return this.adapter.listKeys(filter)
237
+ }
238
+
239
+ async activeVersion(key: VaultKey): Promise<KeyVersion> {
240
+ const version = await this.adapter.getKeyVersion(key.id, key.currentVersion)
241
+ if (!version) {
242
+ throw new VaultError(VAULT_ERRORS.KEY_VERSION_NOT_FOUND, {
243
+ keyId: key.id,
244
+ version: key.currentVersion,
245
+ })
246
+ }
247
+ if (version.status === "destroyed") {
248
+ throw new VaultError(VAULT_ERRORS.KEY_DESTROYED, {keyId: key.id, version: version.version})
249
+ }
250
+ return version
251
+ }
252
+
253
+ async version(key: VaultKey, version: number): Promise<KeyVersion> {
254
+ const record = await this.adapter.getKeyVersion(key.id, version)
255
+ if (!record) {
256
+ throw new VaultError(VAULT_ERRORS.KEY_VERSION_NOT_FOUND, {keyId: key.id, version})
257
+ }
258
+ if (record.status === "destroyed") {
259
+ throw new VaultError(VAULT_ERRORS.KEY_DESTROYED, {keyId: key.id, version})
260
+ }
261
+ return record
262
+ }
263
+
264
+ async listVersions(key: VaultKey): Promise<KeyVersion[]> {
265
+ return this.adapter.listKeyVersions(key.id)
266
+ }
267
+
268
+ assertUsage(key: VaultKey, action: "encrypt" | "decrypt" | "sign" | "verify"): void {
269
+ const allowed = action === "encrypt"
270
+ ? ENCRYPT_USAGES
271
+ : action === "decrypt"
272
+ ? DECRYPT_USAGES
273
+ : action === "sign"
274
+ ? SIGN_USAGES
275
+ : SIGN_USAGES
276
+ if (!allowed.includes(key.usage)) {
277
+ throw new VaultError(VAULT_ERRORS.KEY_USAGE_INVALID, {
278
+ keyId: key.id,
279
+ usage: key.usage,
280
+ action,
281
+ })
282
+ }
283
+ }
284
+
285
+ async recordUse(
286
+ key: VaultKey,
287
+ version: KeyVersion,
288
+ action: "encrypt" | "decrypt" | "sign" | "verify",
289
+ outcome: "success" | "failure" | "denied",
290
+ actor?: VaultEventContext,
291
+ context?: Record<string, unknown>,
292
+ ): Promise<void> {
293
+ await this.audit.record({
294
+ action: `key.use.${action}`,
295
+ outcome,
296
+ resourceType: "key",
297
+ resourceId: key.id,
298
+ keyId: key.id,
299
+ keyVersion: version.version,
300
+ actor: {...actor, tenantId: actor?.tenantId ?? key.tenantId},
301
+ context,
302
+ })
303
+ await this.emit("VaultKeyUsed", {
304
+ keyId: key.id,
305
+ alias: key.alias,
306
+ version: version.version,
307
+ action,
308
+ outcome,
309
+ }, {...actor, tenantId: actor?.tenantId ?? key.tenantId})
310
+ }
311
+
312
+ private assertCapability(capability: "keys" | "envelope"): void {
313
+ if (!this.config.capabilities.includes(capability)) {
314
+ throw new VaultError(VAULT_ERRORS.CAPABILITY_DISABLED, {capability})
315
+ }
316
+ }
317
+
318
+ private defaultAlgorithm(usage: KeyUsage): KeyAlgorithm {
319
+ return usage === "sign" || usage === "verify" ? "ed25519" : this.config.keys.defaultAlgorithm
320
+ }
321
+
322
+ private resolveRotation(input?: Partial<RotationPolicy>): RotationPolicy {
323
+ const base = this.config.keys.rotation
324
+ return {
325
+ intervalDays: input?.intervalDays ?? base.intervalDays,
326
+ graceDays: input?.graceDays ?? base.graceDays,
327
+ autoRotate: input?.autoRotate ?? base.autoRotate,
328
+ reencrypt: input?.reencrypt ?? base.reencrypt,
329
+ }
330
+ }
331
+
332
+ private actorOf(input: GenerateKeyInput | RotateKeyInput | DestroyKeyInput, key: VaultKey): VaultEventContext {
333
+ return {
334
+ actorId: input.actor?.actorId,
335
+ tenantId: input.actor?.tenantId ?? key.tenantId,
336
+ correlationId: input.actor?.correlationId,
337
+ }
338
+ }
339
+ }