@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,151 @@
1
+ import {RaitonCommand} from "raiton/core"
2
+ import type {Command} from "commander"
3
+ import {VaultCliService, type CliResult} from "../cli/service.ts"
4
+
5
+ function emit(result: CliResult, options: Record<string, any> = {}): void {
6
+ if (result.data !== undefined) {
7
+ if (options.json || options.ci) {
8
+ const payload = Array.isArray(result.data)
9
+ ? {code: result.code, data: result.data}
10
+ : {code: result.code, ...((result.data && typeof result.data === "object") ? result.data as object : {result: result.data})}
11
+ process.stdout.write(JSON.stringify(payload) + "\n")
12
+ } else if (result.message) {
13
+ process.stdout.write(`${result.message}\n`)
14
+ } else if (typeof result.data === "string") {
15
+ process.stdout.write(`${result.data}\n`)
16
+ } else {
17
+ process.stdout.write(JSON.stringify(result.data, null, 2) + "\n")
18
+ }
19
+ } else if (result.message) {
20
+ if (options.json || options.ci) process.stdout.write(JSON.stringify({code: result.code, message: result.message}) + "\n")
21
+ else process.stdout.write(`${result.message}\n`)
22
+ }
23
+ process.exitCode = result.code
24
+ }
25
+
26
+ export abstract class VaultDomainCommand extends RaitonCommand {
27
+ protected readonly service: VaultCliService
28
+
29
+ constructor(cli: Command, workdir: string, appdir = "") {
30
+ super(cli, workdir, appdir)
31
+ this.service = new VaultCliService(workdir)
32
+ }
33
+
34
+ protected get vaultParent(): Command {
35
+ const existing = this.cli.commands.find(command => command.name() === "vault")
36
+ if (existing) return existing
37
+ return this.cli
38
+ .command("vault")
39
+ .description("Coffre-fort cryptographique (@raiton/vault)")
40
+ }
41
+
42
+ protected define(parent: Command, name: string, description: string, configure: (command: Command) => void): Command {
43
+ const existing = parent.commands.find(command => command.name() === name)
44
+ if (existing) {
45
+ // The Raiton harvester registers a generic `vault doctor` and `vault keys`
46
+ // before module commands. The module owns its domain commands: replace the
47
+ // colliding entry while keeping idempotence on hot reload.
48
+ if ((existing as any).__raitonVaultCommand) return existing
49
+ const index = parent.commands.indexOf(existing)
50
+ if (index >= 0) (parent.commands as Command[]).splice(index, 1)
51
+ }
52
+ const command = parent.command(name).description(description)
53
+ ;(command as any).__raitonVaultCommand = true
54
+ configure(command)
55
+ return command
56
+ }
57
+
58
+ protected options(command: any): Record<string, any> {
59
+ if (command && typeof command.opts === "function") return command.opts()
60
+ return command && typeof command === "object" ? command : {}
61
+ }
62
+
63
+ protected async done(result: CliResult | Promise<CliResult>, options: Record<string, any> = {}): Promise<void> {
64
+ emit(await result, options)
65
+ }
66
+ }
67
+
68
+ export default class VaultCommand extends VaultDomainCommand {
69
+ readonly name = "vault"
70
+ readonly description = "Coffre-fort cryptographique (@raiton/vault)"
71
+ readonly version = "0.0.1"
72
+
73
+ register(): void {
74
+ const vault = this.vaultParent
75
+
76
+ this.define(vault, "init", "Initialise @raiton/vault dans une application Raiton", command => {
77
+ command
78
+ .option("--preset <preset>", "local, team, regulated", "local")
79
+ .option("--capabilities <liste>", "Capacités séparées par des virgules")
80
+ .option("--mode <mode>", "single, multi", "single")
81
+ .option("--adapter <nom>", "Adaptateur (memory)")
82
+ .option("--orm <orm>", "prisma, drizzle, typeorm, kysely, sequelize, generic")
83
+ .option("--dialect <dialect>", "postgres, mysql, sqlite", "postgres")
84
+ .option("--directory <dir>", "Répertoire de persistance", "source/database")
85
+ .option("--dry-run", "Aucune écriture")
86
+ .option("--yes", "Mode non interactif")
87
+ .option("--force", "Remplace la configuration existante")
88
+ .option("--json", "Sortie JSON")
89
+ .action((cmd: Command) => this.done(this.service.init(this.options(cmd)), this.options(cmd)))
90
+ })
91
+
92
+ this.define(vault, "doctor", "Diagnostique la configuration, le KMS et les clés", command => {
93
+ command.option("--json", "Sortie JSON").option("--ci", "Sortie CI")
94
+ .action((cmd: Command) => this.done(this.service.doctor(this.options(cmd)), this.options(cmd)))
95
+ })
96
+
97
+ this.define(vault, "capabilities", "Liste les capacités et leur disponibilité", command => {
98
+ command.option("--json", "Sortie JSON")
99
+ .action((cmd: Command) => this.done(this.service.capabilities(this.options(cmd)), this.options(cmd)))
100
+ })
101
+
102
+ this.define(vault, "inspect", "Inspecte les clés, versions et usages", command => {
103
+ command
104
+ .option("--alias <alias>", "Alias de clé")
105
+ .option("--tenant <id>", "Tenant")
106
+ .option("--json", "Sortie JSON")
107
+ .action((cmd: Command) => this.done(this.service.inspect(this.options(cmd)), this.options(cmd)))
108
+ })
109
+
110
+ this.define(vault, "keys", "Liste les clés et versions du coffre", command => {
111
+ command
112
+ .option("--alias <alias>", "Alias de clé")
113
+ .option("--tenant <id>", "Tenant")
114
+ .option("--json", "Sortie JSON")
115
+ .action((cmd: Command) => this.done(this.service.inspect(this.options(cmd)), this.options(cmd)))
116
+ })
117
+
118
+ this.define(vault, "rotate", "Fait tourner une clé avec preuve d'audit", command => {
119
+ command.argument("<key>", "Alias ou identifiant de clé")
120
+ .option("--tenant <id>", "Tenant")
121
+ .option("--reason <reason>", "Motif de rotation")
122
+ .option("--json", "Sortie JSON")
123
+ .action((key: string, cmd: Command) => this.done(this.service.rotate({...this.options(cmd), key}), this.options(cmd)))
124
+ })
125
+
126
+ this.define(vault, "export", "Exporte les preuves d'audit", command => {
127
+ command
128
+ .option("--tenant <id>", "Tenant")
129
+ .option("--actor <id>", "Acteur")
130
+ .option("--action <action>", "Action auditée")
131
+ .option("--resource <id>", "Ressource")
132
+ .option("--limit <nombre>", "Nombre maximal d'entrées")
133
+ .option("--out <fichier>", "Fichier de sortie JSON")
134
+ .option("--json", "Sortie JSON")
135
+ .action((cmd: Command) => this.done(this.service.export(this.options(cmd)), this.options(cmd)))
136
+ })
137
+
138
+ this.define(vault, "generate", "Génère le schéma SQL et le squelette d'adaptateur", command => {
139
+ command
140
+ .option("--orm <orm>", "prisma, drizzle, typeorm, kysely, sequelize, generic", "generic")
141
+ .option("--dialect <dialect>", "postgres, mysql, sqlite", "postgres")
142
+ .option("--out <dir>", "Répertoire de sortie", "source/database")
143
+ .option("--prefix <prefix>", "Préfixe des tables", "")
144
+ .option("--dry-run", "Aucune écriture")
145
+ .option("--json", "Sortie JSON")
146
+ .action((cmd: Command) => this.done(this.service.generate(this.options(cmd)), this.options(cmd)))
147
+ })
148
+
149
+ vault.action((cmd: Command) => this.done(this.service.doctor(this.options(cmd)), this.options(cmd)))
150
+ }
151
+ }
@@ -0,0 +1,281 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import {pathToFileURL} from "node:url"
4
+ import {
5
+ CAPABILITIES,
6
+ CAPABILITY_BY_CODE,
7
+ CAPABILITY_BY_ID,
8
+ CAPABILITY_DEFINITIONS,
9
+ IMPLEMENTED_CAPABILITIES,
10
+ type CapabilityId,
11
+ type CapabilityInput,
12
+ type KeyAlgorithm,
13
+ type VaultConfig,
14
+ type VaultConfigInput,
15
+ type VaultMode,
16
+ } from "./types.ts"
17
+ import {VAULT_ERRORS, VaultError} from "./errors.ts"
18
+
19
+ export const CONTRACT_VERSION = "1.0.0"
20
+ export const RAITON_SUPPORTED_RANGE = ">=6.20.0-beta.41 <7.0.0"
21
+ export const CONFIG_VERSION = 1
22
+ export const CONFIG_FILE = "raiton-vault.config.json"
23
+
24
+ export const PRESETS = ["local", "team", "regulated"] as const
25
+ export type Preset = (typeof PRESETS)[number]
26
+
27
+ const MODES: VaultMode[] = ["single", "multi"]
28
+ const ALGORITHMS: KeyAlgorithm[] = ["aes-256-gcm", "ed25519", "ecdsa-p256", "rsa-oaep-256"]
29
+
30
+ export const DEFAULT_VAULT_CONFIG: VaultConfig = {
31
+ mode: "single",
32
+ capabilities: [...IMPLEMENTED_CAPABILITIES],
33
+ keys: {
34
+ defaultAlgorithm: "aes-256-gcm",
35
+ rotation: {
36
+ intervalDays: 90,
37
+ graceDays: 7,
38
+ autoRotate: false,
39
+ reencrypt: false,
40
+ },
41
+ },
42
+ kms: {
43
+ provider: "local",
44
+ keyCacheSeconds: 60,
45
+ },
46
+ envelope: {
47
+ algorithm: "aes-256-gcm",
48
+ bindAad: true,
49
+ },
50
+ audit: {
51
+ enabled: true,
52
+ retentionDays: 365,
53
+ },
54
+ persistence: {
55
+ orm: null,
56
+ dialect: "postgres",
57
+ directory: "source/database",
58
+ },
59
+ }
60
+
61
+ const PRESET_VALUES: Record<Preset, VaultConfigInput> = {
62
+ local: {},
63
+ team: {
64
+ mode: "multi",
65
+ capabilities: [...IMPLEMENTED_CAPABILITIES],
66
+ keys: {
67
+ rotation: {intervalDays: 60, graceDays: 7, autoRotate: true, reencrypt: true},
68
+ },
69
+ },
70
+ regulated: {
71
+ mode: "multi",
72
+ capabilities: [...IMPLEMENTED_CAPABILITIES],
73
+ keys: {
74
+ rotation: {intervalDays: 30, graceDays: 14, autoRotate: true, reencrypt: true},
75
+ },
76
+ audit: {enabled: true, retentionDays: 3650},
77
+ },
78
+ }
79
+
80
+ export function presetConfig(preset: Preset): VaultConfigInput {
81
+ const value = PRESET_VALUES[preset]
82
+ return JSON.parse(JSON.stringify(value)) as VaultConfigInput
83
+ }
84
+
85
+ function isPlainObject(value: unknown): value is Record<string, any> {
86
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value)
87
+ }
88
+
89
+ function mergeDefined<T extends Record<string, any>>(base: T, patch?: Record<string, any>): T {
90
+ const result: Record<string, any> = {...base}
91
+ if (!patch) return result as T
92
+ for (const [key, value] of Object.entries(patch)) {
93
+ if (value === undefined) continue
94
+ if (isPlainObject(value) && isPlainObject(base[key])) {
95
+ result[key] = mergeDefined(base[key], value)
96
+ } else {
97
+ result[key] = value
98
+ }
99
+ }
100
+ return result as T
101
+ }
102
+
103
+ export function normalizeCapability(input: CapabilityInput): CapabilityId {
104
+ const raw = String(input ?? "").trim().toLowerCase()
105
+ if (!raw) throw new VaultError(VAULT_ERRORS.CAPABILITY_UNKNOWN, {capability: input})
106
+ if ((CAPABILITIES as readonly string[]).includes(raw)) return raw as CapabilityId
107
+ const byCode = CAPABILITY_BY_CODE[raw]
108
+ if (byCode) return byCode.id
109
+ const byAlias = CAPABILITY_DEFINITIONS.find(definition =>
110
+ definition.aliases.some(alias => alias.toLowerCase() === raw),
111
+ )
112
+ if (byAlias) return byAlias.id
113
+ throw new VaultError(VAULT_ERRORS.CAPABILITY_UNKNOWN, {
114
+ capability: input,
115
+ available: CAPABILITIES,
116
+ })
117
+ }
118
+
119
+ export function resolveCapabilities(input: CapabilityInput[] = [...IMPLEMENTED_CAPABILITIES]): CapabilityId[] {
120
+ const selected = new Set<CapabilityId>()
121
+ const visit = (capability: CapabilityId): void => {
122
+ if (selected.has(capability)) return
123
+ selected.add(capability)
124
+ for (const dependency of CAPABILITY_BY_ID[capability].requires) visit(dependency)
125
+ }
126
+ for (const value of input) visit(normalizeCapability(value))
127
+ return CAPABILITIES.filter(capability => selected.has(capability))
128
+ }
129
+
130
+ export interface CapabilityValidationOptions {
131
+ /** Allow declaring capabilities that are not implemented yet (planning mode). */
132
+ allowUnimplemented?: boolean
133
+ }
134
+
135
+ export function validateCapabilityComposition(
136
+ config: VaultConfig,
137
+ options: CapabilityValidationOptions = {},
138
+ ): void {
139
+ for (const capability of config.capabilities) {
140
+ const definition = CAPABILITY_BY_ID[capability]
141
+ if (!definition) throw new VaultError(VAULT_ERRORS.CAPABILITY_UNKNOWN, {capability})
142
+ for (const dependency of definition.requires) {
143
+ if (!config.capabilities.includes(dependency)) {
144
+ throw new VaultError(VAULT_ERRORS.CAPABILITY_DEPENDENCY, {
145
+ capability,
146
+ missing: dependency,
147
+ })
148
+ }
149
+ }
150
+ if (!options.allowUnimplemented && !IMPLEMENTED_CAPABILITIES.includes(capability)) {
151
+ throw new VaultError(VAULT_ERRORS.CAPABILITY_NOT_IMPLEMENTED, {
152
+ capability,
153
+ implemented: IMPLEMENTED_CAPABILITIES,
154
+ hint: "Activez uniquement les capacités implémentées ou attendez la spec correspondante.",
155
+ })
156
+ }
157
+ }
158
+ }
159
+
160
+ function assertRange(value: number, field: string, min: number, max: number): void {
161
+ if (!Number.isFinite(value) || value < min || value > max) {
162
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {field, value, min, max})
163
+ }
164
+ }
165
+
166
+ export function resolveVaultConfig(input: VaultConfigInput = {}, options: CapabilityValidationOptions = {}): VaultConfig {
167
+ const mode = input.mode ?? DEFAULT_VAULT_CONFIG.mode
168
+ if (!MODES.includes(mode)) {
169
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {field: "mode", value: mode})
170
+ }
171
+
172
+ const config = mergeDefined(DEFAULT_VAULT_CONFIG as any, input as any) as VaultConfig
173
+ config.mode = mode
174
+ config.capabilities = resolveCapabilities(input.capabilities ?? DEFAULT_VAULT_CONFIG.capabilities)
175
+
176
+ if (!ALGORITHMS.includes(config.keys.defaultAlgorithm)) {
177
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
178
+ field: "keys.defaultAlgorithm",
179
+ value: config.keys.defaultAlgorithm,
180
+ allowed: ALGORITHMS,
181
+ })
182
+ }
183
+ assertRange(config.keys.rotation.intervalDays, "keys.rotation.intervalDays", 1, 3650)
184
+ assertRange(config.keys.rotation.graceDays, "keys.rotation.graceDays", 0, 365)
185
+ assertRange(config.kms.keyCacheSeconds, "kms.keyCacheSeconds", 0, 3600)
186
+ if (!["local", "custom"].includes(config.kms.provider)) {
187
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {field: "kms.provider", value: config.kms.provider})
188
+ }
189
+ if (config.envelope.algorithm !== "aes-256-gcm") {
190
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
191
+ field: "envelope.algorithm",
192
+ value: config.envelope.algorithm,
193
+ })
194
+ }
195
+ assertRange(config.audit.retentionDays, "audit.retentionDays", 0, 3650)
196
+ if (config.capabilities.includes("audit") && !config.audit.enabled) {
197
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
198
+ field: "audit.enabled",
199
+ hint: "La capacité audit exige l'audit activé (fail-closed).",
200
+ })
201
+ }
202
+ if (!["postgres", "mysql", "sqlite"].includes(config.persistence.dialect)) {
203
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
204
+ field: "persistence.dialect",
205
+ value: config.persistence.dialect,
206
+ })
207
+ }
208
+ validateCapabilityComposition(config, options)
209
+ return config
210
+ }
211
+
212
+ export function configPath(workdir: string): string | null {
213
+ const candidates = [CONFIG_FILE, "raiton.vault.json"]
214
+ for (const candidate of candidates) {
215
+ const target = path.join(workdir, candidate)
216
+ if (fs.existsSync(target)) return target
217
+ }
218
+ return null
219
+ }
220
+
221
+ export async function loadProjectConfig(workdir: string): Promise<VaultConfigInput> {
222
+ const file = configPath(workdir)
223
+ if (file) {
224
+ try {
225
+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8"))
226
+ if (!isPlainObject(parsed)) {
227
+ throw new Error("La configuration doit être un objet JSON.")
228
+ }
229
+ const version = parsed.configVersion
230
+ if (version !== undefined && version !== CONFIG_VERSION) {
231
+ throw new VaultError(VAULT_ERRORS.CONTRACT_INCOMPATIBLE, {
232
+ file: path.relative(workdir, file),
233
+ configVersion: version,
234
+ supported: CONFIG_VERSION,
235
+ })
236
+ }
237
+ return parsed as VaultConfigInput
238
+ } catch (error: any) {
239
+ if (error instanceof VaultError) throw error
240
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
241
+ file: path.relative(workdir, file),
242
+ message: error?.message ?? String(error),
243
+ })
244
+ }
245
+ }
246
+ for (const candidate of ["raiton.config.ts", "raiton.config.js", "raiton.config.mjs"]) {
247
+ const target = path.join(workdir, candidate)
248
+ if (!fs.existsSync(target)) continue
249
+ try {
250
+ const module = await import(pathToFileURL(target).href)
251
+ const value = module.default ?? module.config ?? {}
252
+ const vault = value.vault ?? value.module ?? {}
253
+ return isPlainObject(vault) ? vault : {}
254
+ } catch (error: any) {
255
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
256
+ file: candidate,
257
+ message: error?.message ?? String(error),
258
+ })
259
+ }
260
+ }
261
+ return {}
262
+ }
263
+
264
+ export async function loadResolvedConfig(workdir: string): Promise<VaultConfig> {
265
+ return resolveVaultConfig(await loadProjectConfig(workdir))
266
+ }
267
+
268
+ export function writeProjectConfig(workdir: string, config: VaultConfigInput): string {
269
+ const target = path.join(workdir, CONFIG_FILE)
270
+ const payload = {configVersion: CONFIG_VERSION, ...config}
271
+ fs.writeFileSync(target, `${JSON.stringify(payload, null, 2)}\n`, "utf-8")
272
+ return target
273
+ }
274
+
275
+ export function capabilitySummary(config: VaultConfig): Array<{id: CapabilityId; enabled: boolean; implemented: boolean}> {
276
+ return CAPABILITIES.map(id => ({
277
+ id,
278
+ enabled: config.capabilities.includes(id),
279
+ implemented: IMPLEMENTED_CAPABILITIES.includes(id),
280
+ }))
281
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./types.ts"
2
+ export * from "./errors.ts"
3
+ export * from "./events.ts"
4
+ export * from "./http/contracts.ts"
5
+ export * from "./cqrs/contracts.ts"
@@ -0,0 +1,111 @@
1
+ import {defineCommand, defineQuery, t} from "raiton/contracts"
2
+
3
+ const ctx = {
4
+ actorId: t.optional(t.string()),
5
+ correlationId: t.optional(t.string()),
6
+ }
7
+
8
+ // Key lifecycle -------------------------------------------------------------
9
+
10
+ export const GenerateKeyCommand = defineCommand({
11
+ name: "vault.keys.generate",
12
+ version: 1,
13
+ payload: t.object({
14
+ alias: t.string().min(1),
15
+ tenantId: t.optional(t.string()),
16
+ usage: t.optional(t.string()),
17
+ algorithm: t.optional(t.string()),
18
+ ownerId: t.optional(t.string()),
19
+ rotation: t.optional(t.any()),
20
+ metadata: t.optional(t.any()),
21
+ ...ctx,
22
+ }),
23
+ })
24
+
25
+ export const RotateKeyCommand = defineCommand({
26
+ name: "vault.keys.rotate",
27
+ version: 1,
28
+ payload: t.object({
29
+ key: t.string().min(1),
30
+ tenantId: t.optional(t.string()),
31
+ reason: t.optional(t.string()),
32
+ ...ctx,
33
+ }),
34
+ })
35
+
36
+ export const DestroyKeyCommand = defineCommand({
37
+ name: "vault.keys.destroy",
38
+ version: 1,
39
+ payload: t.object({
40
+ key: t.string().min(1),
41
+ tenantId: t.optional(t.string()),
42
+ reason: t.optional(t.string()),
43
+ ...ctx,
44
+ }),
45
+ })
46
+
47
+ export const GetKeyQuery = defineQuery({
48
+ name: "vault.keys.get",
49
+ version: 1,
50
+ payload: t.object({
51
+ key: t.string().min(1),
52
+ tenantId: t.optional(t.string()),
53
+ }),
54
+ })
55
+
56
+ export const ListKeysQuery = defineQuery({
57
+ name: "vault.keys.list",
58
+ version: 1,
59
+ payload: t.object({
60
+ tenantId: t.optional(t.string()),
61
+ usage: t.optional(t.string()),
62
+ status: t.optional(t.string()),
63
+ alias: t.optional(t.string()),
64
+ }),
65
+ })
66
+
67
+ // Crypto --------------------------------------------------------------------
68
+
69
+ export const EncryptCommand = defineCommand({
70
+ name: "vault.crypto.encrypt",
71
+ version: 1,
72
+ payload: t.object({
73
+ plaintext: t.string(),
74
+ key: t.string().min(1),
75
+ tenantId: t.optional(t.string()),
76
+ aad: t.optional(t.string()),
77
+ ...ctx,
78
+ }),
79
+ })
80
+
81
+ export const DecryptCommand = defineCommand({
82
+ name: "vault.crypto.decrypt",
83
+ version: 1,
84
+ payload: t.object({
85
+ envelope: t.any(),
86
+ tenantId: t.optional(t.string()),
87
+ aad: t.optional(t.string()),
88
+ ...ctx,
89
+ }),
90
+ })
91
+
92
+ // Audit ---------------------------------------------------------------------
93
+
94
+ export const ListAuditQuery = defineQuery({
95
+ name: "vault.audit.list",
96
+ version: 1,
97
+ payload: t.object({
98
+ tenantId: t.optional(t.string()),
99
+ actorId: t.optional(t.string()),
100
+ action: t.optional(t.string()),
101
+ resourceId: t.optional(t.string()),
102
+ since: t.optional(t.string()),
103
+ limit: t.optional(t.number()),
104
+ }),
105
+ })
106
+
107
+ export const VaultHealthQuery = defineQuery({
108
+ name: "vault.health",
109
+ version: 1,
110
+ payload: t.object({}),
111
+ })
@@ -0,0 +1,122 @@
1
+ import {CommandHandler, QueryHandler} from "raiton/cqrs"
2
+ import {VaultRuntime} from "../kernel.ts"
3
+ import type {AuditAction, KeyAlgorithm, KeyStatus, KeyUsage, VaultActor} from "../types.ts"
4
+ import * as C from "./contracts.ts"
5
+
6
+ function kernel() {
7
+ return VaultRuntime.require()
8
+ }
9
+
10
+ function actorOf(payload: Record<string, any>): VaultActor {
11
+ return {
12
+ actorId: payload.actorId,
13
+ tenantId: payload.tenantId,
14
+ correlationId: payload.correlationId,
15
+ }
16
+ }
17
+
18
+ @CommandHandler(C.GenerateKeyCommand)
19
+ export class GenerateKeyHandler {
20
+ async handle(message: any) {
21
+ return kernel().keys.generate({
22
+ alias: message.payload.alias,
23
+ tenantId: message.payload.tenantId,
24
+ usage: message.payload.usage as KeyUsage | undefined,
25
+ algorithm: message.payload.algorithm as KeyAlgorithm | undefined,
26
+ ownerId: message.payload.ownerId,
27
+ rotation: message.payload.rotation,
28
+ metadata: message.payload.metadata,
29
+ actor: actorOf(message.payload),
30
+ })
31
+ }
32
+ }
33
+
34
+ @CommandHandler(C.RotateKeyCommand)
35
+ export class RotateKeyHandler {
36
+ async handle(message: any) {
37
+ return kernel().keys.rotate({
38
+ key: message.payload.key,
39
+ tenantId: message.payload.tenantId,
40
+ reason: message.payload.reason,
41
+ actor: actorOf(message.payload),
42
+ })
43
+ }
44
+ }
45
+
46
+ @CommandHandler(C.DestroyKeyCommand)
47
+ export class DestroyKeyHandler {
48
+ async handle(message: any) {
49
+ return kernel().keys.destroy({
50
+ key: message.payload.key,
51
+ tenantId: message.payload.tenantId,
52
+ reason: message.payload.reason,
53
+ actor: actorOf(message.payload),
54
+ })
55
+ }
56
+ }
57
+
58
+ @QueryHandler(C.GetKeyQuery)
59
+ export class GetKeyHandler {
60
+ async handle(message: any) {
61
+ return kernel().keys.get(message.payload.key, message.payload.tenantId)
62
+ }
63
+ }
64
+
65
+ @QueryHandler(C.ListKeysQuery)
66
+ export class ListKeysHandler {
67
+ async handle(message: any) {
68
+ return kernel().keys.list({
69
+ tenantId: message.payload.tenantId,
70
+ usage: message.payload.usage as KeyUsage | undefined,
71
+ status: message.payload.status as KeyStatus | undefined,
72
+ alias: message.payload.alias,
73
+ })
74
+ }
75
+ }
76
+
77
+ @CommandHandler(C.EncryptCommand)
78
+ export class EncryptHandler {
79
+ async handle(message: any) {
80
+ return kernel().envelope.encrypt({
81
+ plaintext: message.payload.plaintext,
82
+ key: message.payload.key,
83
+ tenantId: message.payload.tenantId,
84
+ aad: message.payload.aad,
85
+ actor: actorOf(message.payload),
86
+ })
87
+ }
88
+ }
89
+
90
+ @CommandHandler(C.DecryptCommand)
91
+ export class DecryptHandler {
92
+ async handle(message: any) {
93
+ const plaintext = await kernel().envelope.decrypt({
94
+ envelope: message.payload.envelope,
95
+ tenantId: message.payload.tenantId,
96
+ aad: message.payload.aad,
97
+ actor: actorOf(message.payload),
98
+ })
99
+ return {plaintext}
100
+ }
101
+ }
102
+
103
+ @QueryHandler(C.ListAuditQuery)
104
+ export class ListAuditHandler {
105
+ async handle(message: any) {
106
+ return kernel().audit.list({
107
+ tenantId: message.payload.tenantId,
108
+ actorId: message.payload.actorId,
109
+ action: message.payload.action as AuditAction | undefined,
110
+ resourceId: message.payload.resourceId,
111
+ since: message.payload.since,
112
+ limit: message.payload.limit,
113
+ })
114
+ }
115
+ }
116
+
117
+ @QueryHandler(C.VaultHealthQuery)
118
+ export class VaultHealthHandler {
119
+ async handle() {
120
+ return kernel().health()
121
+ }
122
+ }