@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,57 @@
1
+ import "reflect-metadata"
2
+
3
+ export type EncryptionMode = "random" | "deterministic"
4
+
5
+ export interface EncryptedOptions {
6
+ /** Key alias used to encrypt the field. Defaults to the module configuration. */
7
+ key?: string
8
+ /** Random (default) or deterministic encryption. */
9
+ mode?: EncryptionMode
10
+ /** Declare a blind index so equality search remains possible. */
11
+ blindIndex?: boolean
12
+ /** Classification consumed by @raiton/compliance when active. */
13
+ classification?: string
14
+ /** Additional authenticated data bound to the value. */
15
+ aad?: string
16
+ }
17
+
18
+ export interface EncryptedFieldMetadata extends EncryptedOptions {
19
+ property: string
20
+ mode: EncryptionMode
21
+ blindIndex: boolean
22
+ }
23
+
24
+ const ENCRYPTED_METADATA = Symbol.for("@raiton/vault:encrypted-fields")
25
+
26
+ /**
27
+ * Mark an entity or DTO property as encrypted.
28
+ *
29
+ * The decorator only records metadata: the ORM adapter generated by the module
30
+ * reads it to encrypt before persisting and decrypt after loading. Values are
31
+ * never transformed at decoration time.
32
+ */
33
+ export function Encrypted(options: EncryptedOptions = {}): PropertyDecorator {
34
+ return (target: object, propertyKey: string | symbol) => {
35
+ if (typeof propertyKey !== "string") return
36
+ const fields = encryptedFields(target.constructor)
37
+ fields[propertyKey] = {
38
+ ...options,
39
+ property: propertyKey,
40
+ mode: options.mode ?? "random",
41
+ blindIndex: options.blindIndex ?? false,
42
+ }
43
+ Reflect.defineMetadata(ENCRYPTED_METADATA, fields, target.constructor)
44
+ }
45
+ }
46
+
47
+ export function encryptedFields(target: Function): Record<string, EncryptedFieldMetadata> {
48
+ return {...(Reflect.getMetadata(ENCRYPTED_METADATA, target) ?? {})}
49
+ }
50
+
51
+ export function hasEncryptedFields(target: Function): boolean {
52
+ return Object.keys(encryptedFields(target)).length > 0
53
+ }
54
+
55
+ export function encryptedField(target: Function, property: string): EncryptedFieldMetadata | null {
56
+ return encryptedFields(target)[property] ?? null
57
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Stable public error catalogue.
3
+ *
4
+ * Codes never vary with the existence of a key, a tenant or a secret, and are
5
+ * safe to expose to an API client. The HTTP status is aligned with the Raiton
6
+ * error catalogue.
7
+ */
8
+ export interface VaultErrorDefinition {
9
+ code: string
10
+ status: number
11
+ message: string
12
+ docsUrl?: string
13
+ }
14
+
15
+ const DOCS = "https://github.com/protorians/raiton-vault/blob/main/docs/errors.md"
16
+
17
+ function define(code: string, status: number, message: string): VaultErrorDefinition {
18
+ return {code, status, message, docsUrl: `${DOCS}#${code.toLowerCase()}`}
19
+ }
20
+
21
+ export const VAULT_ERRORS = {
22
+ CONFIG_INVALID: define("VAULT_CONFIG_INVALID", 500, "La configuration du coffre est invalide."),
23
+ CONTRACT_INCOMPATIBLE: define("VAULT_CONTRACT_INCOMPATIBLE", 500, "Le contrat du module est incompatible avec cette version du runtime."),
24
+ CAPABILITY_UNKNOWN: define("VAULT_CAPABILITY_UNKNOWN", 500, "La capacité demandée est inconnue."),
25
+ CAPABILITY_DEPENDENCY: define("VAULT_CAPABILITY_DEPENDENCY", 500, "Une dépendance de capacité est manquante."),
26
+ CAPABILITY_NOT_IMPLEMENTED: define("VAULT_CAPABILITY_NOT_IMPLEMENTED", 501, "Cette capacité n'est pas encore implémentée."),
27
+ CAPABILITY_DISABLED: define("VAULT_CAPABILITY_DISABLED", 403, "Cette capacité est désactivée."),
28
+ SECRET_MISSING: define("VAULT_SECRET_MISSING", 500, "Un secret requis est absent de l'environnement."),
29
+ ADAPTER_MISSING: define("VAULT_ADAPTER_MISSING", 500, "Aucun adaptateur de persistance n'est configuré."),
30
+ ADAPTER_INCOMPLETE: define("VAULT_ADAPTER_INCOMPLETE", 500, "L'adaptateur de persistance est incomplet."),
31
+ KMS_UNAVAILABLE: define("VAULT_KMS_UNAVAILABLE", 503, "Le KMS est indisponible."),
32
+ KMS_UNSUPPORTED: define("VAULT_KMS_UNSUPPORTED", 501, "Le KMS ne supporte pas l'opération demandée."),
33
+ KEY_NOT_FOUND: define("VAULT_KEY_NOT_FOUND", 404, "Clé introuvable."),
34
+ KEY_ALIAS_CONFLICT: define("VAULT_KEY_ALIAS_CONFLICT", 409, "Cet alias de clé est déjà utilisé."),
35
+ KEY_DESTROYED: define("VAULT_KEY_DESTROYED", 410, "Cette clé a été détruite."),
36
+ KEY_RETIRED: define("VAULT_KEY_RETIRED", 410, "Cette clé a été retirée."),
37
+ KEY_VERSION_NOT_FOUND: define("VAULT_KEY_VERSION_NOT_FOUND", 404, "Version de clé introuvable."),
38
+ KEY_VERSION_MISMATCH: define("VAULT_KEY_VERSION_MISMATCH", 409, "La version de clé ne correspond pas à l'enveloppe."),
39
+ KEY_USAGE_INVALID: define("VAULT_KEY_USAGE_INVALID", 422, "Cette clé ne permet pas cet usage."),
40
+ ROTATION_FAILED: define("VAULT_ROTATION_FAILED", 500, "La rotation de clé a échoué."),
41
+ ENCRYPT_FAILED: define("VAULT_ENCRYPT_FAILED", 500, "Le chiffrement a échoué."),
42
+ DECRYPT_FAILED: define("VAULT_DECRYPT_FAILED", 500, "Le déchiffrement a échoué."),
43
+ SIGNATURE_INVALID: define("VAULT_SIGNATURE_INVALID", 401, "La signature est invalide."),
44
+ TENANT_REQUIRED: define("VAULT_TENANT_REQUIRED", 403, "Un tenant est requis."),
45
+ TENANT_FORBIDDEN: define("VAULT_TENANT_FORBIDDEN", 403, "Accès refusé."),
46
+ PERMISSION_DENIED: define("VAULT_PERMISSION_DENIED", 403, "Permission refusée."),
47
+ AUDIT_DISABLED: define("VAULT_AUDIT_DISABLED", 409, "L'audit est désactivé."),
48
+ BUDGET_EXCEEDED: define("VAULT_BUDGET_EXCEEDED", 429, "Le quota ou le budget est dépassé."),
49
+ } as const
50
+
51
+ export type VaultErrorCode = (typeof VAULT_ERRORS)[keyof typeof VAULT_ERRORS]["code"]
52
+
53
+ export interface VaultErrorDetails {
54
+ [key: string]: unknown
55
+ }
56
+
57
+ export class VaultError extends Error {
58
+ readonly code: string
59
+ readonly status: number
60
+ readonly details: VaultErrorDetails
61
+ readonly docsUrl?: string
62
+
63
+ constructor(definition: VaultErrorDefinition, details: VaultErrorDetails = {}) {
64
+ const hint = details.hint ? ` ${String(details.hint)}` : ""
65
+ super(`${definition.message}${hint}`)
66
+ this.name = "VaultError"
67
+ this.code = definition.code
68
+ this.status = definition.status
69
+ this.details = details
70
+ this.docsUrl = definition.docsUrl
71
+ }
72
+
73
+ toJSON(): Record<string, unknown> {
74
+ return {
75
+ name: this.name,
76
+ code: this.code,
77
+ status: this.status,
78
+ message: this.message,
79
+ details: this.details,
80
+ docsUrl: this.docsUrl,
81
+ }
82
+ }
83
+ }
84
+
85
+ export function isVaultError(error: unknown): error is VaultError {
86
+ return error instanceof VaultError
87
+ }
88
+
89
+ export function toVaultError(error: unknown): VaultError {
90
+ if (isVaultError(error)) return error
91
+ const message = error instanceof Error ? error.message : String(error)
92
+ return new VaultError(VAULT_ERRORS.CONFIG_INVALID, {message})
93
+ }
@@ -0,0 +1,104 @@
1
+ import {defineEvent, t} from "raiton/contracts"
2
+
3
+ const envelope = {
4
+ eventId: t.string(),
5
+ occurredAt: t.string(),
6
+ tenantId: t.optional(t.string()),
7
+ actorId: t.optional(t.string()),
8
+ correlationId: t.optional(t.string()),
9
+ }
10
+
11
+ export const VaultInstallationCompleted = defineEvent({
12
+ name: "vault.installation.completed",
13
+ version: 1,
14
+ payload: t.object({
15
+ ...envelope,
16
+ mode: t.string(),
17
+ capabilities: t.array(t.string()),
18
+ adapter: t.string(),
19
+ kms: t.string(),
20
+ }),
21
+ })
22
+
23
+ export const VaultStarted = defineEvent({
24
+ name: "vault.started",
25
+ version: 1,
26
+ payload: t.object({
27
+ ...envelope,
28
+ capabilities: t.array(t.string()),
29
+ adapter: t.string(),
30
+ kms: t.string(),
31
+ }),
32
+ })
33
+
34
+ export const VaultKeyCreated = defineEvent({
35
+ name: "vault.key.created",
36
+ version: 1,
37
+ payload: t.object({
38
+ ...envelope,
39
+ keyId: t.string(),
40
+ alias: t.string(),
41
+ usage: t.string(),
42
+ algorithm: t.string(),
43
+ version: t.number(),
44
+ }),
45
+ })
46
+
47
+ export const VaultKeyRotated = defineEvent({
48
+ name: "vault.key.rotated",
49
+ version: 1,
50
+ payload: t.object({
51
+ ...envelope,
52
+ keyId: t.string(),
53
+ alias: t.string(),
54
+ fromVersion: t.number(),
55
+ toVersion: t.number(),
56
+ }),
57
+ })
58
+
59
+ export const VaultKeyDestroyed = defineEvent({
60
+ name: "vault.key.destroyed",
61
+ version: 1,
62
+ payload: t.object({
63
+ ...envelope,
64
+ keyId: t.string(),
65
+ alias: t.string(),
66
+ versions: t.array(t.number()),
67
+ }),
68
+ })
69
+
70
+ export const VaultKeyUsed = defineEvent({
71
+ name: "vault.key.used",
72
+ version: 1,
73
+ payload: t.object({
74
+ ...envelope,
75
+ keyId: t.string(),
76
+ alias: t.string(),
77
+ version: t.number(),
78
+ action: t.string(),
79
+ outcome: t.string(),
80
+ }),
81
+ })
82
+
83
+ export const VaultAuditRecorded = defineEvent({
84
+ name: "vault.audit.recorded",
85
+ version: 1,
86
+ payload: t.object({
87
+ ...envelope,
88
+ auditId: t.string(),
89
+ action: t.string(),
90
+ outcome: t.string(),
91
+ resourceType: t.string(),
92
+ resourceId: t.string(),
93
+ }),
94
+ })
95
+
96
+ export const VAULT_EVENTS = {
97
+ VaultInstallationCompleted,
98
+ VaultStarted,
99
+ VaultKeyCreated,
100
+ VaultKeyRotated,
101
+ VaultKeyDestroyed,
102
+ VaultKeyUsed,
103
+ VaultAuditRecorded,
104
+ } as const
@@ -0,0 +1,111 @@
1
+ import {t} from "raiton/contracts"
2
+
3
+ const actor = {
4
+ actorId: t.optional(t.string()),
5
+ correlationId: t.optional(t.string()),
6
+ }
7
+
8
+ export const GenerateKeyBody = t.object({
9
+ alias: t.string().min(1),
10
+ tenantId: t.optional(t.string()),
11
+ usage: t.optional(t.string()),
12
+ algorithm: t.optional(t.string()),
13
+ ownerId: t.optional(t.string()),
14
+ rotation: t.optional(t.any()),
15
+ metadata: t.optional(t.any()),
16
+ ...actor,
17
+ })
18
+
19
+ export const RotateKeyBody = t.object({
20
+ key: t.string().min(1),
21
+ tenantId: t.optional(t.string()),
22
+ reason: t.optional(t.string()),
23
+ ...actor,
24
+ })
25
+
26
+ export const DestroyKeyBody = t.object({
27
+ key: t.string().min(1),
28
+ tenantId: t.optional(t.string()),
29
+ reason: t.optional(t.string()),
30
+ ...actor,
31
+ })
32
+
33
+ export const EncryptBody = t.object({
34
+ plaintext: t.string(),
35
+ key: t.string().min(1),
36
+ tenantId: t.optional(t.string()),
37
+ aad: t.optional(t.string()),
38
+ ...actor,
39
+ })
40
+
41
+ export const DecryptBody = t.object({
42
+ envelope: t.any(),
43
+ tenantId: t.optional(t.string()),
44
+ aad: t.optional(t.string()),
45
+ ...actor,
46
+ })
47
+
48
+ export const KeyListQuery = t.object({
49
+ tenantId: t.optional(t.string()),
50
+ usage: t.optional(t.string()),
51
+ status: t.optional(t.string()),
52
+ alias: t.optional(t.string()),
53
+ })
54
+
55
+ export const AuditQuery = t.object({
56
+ tenantId: t.optional(t.string()),
57
+ actorId: t.optional(t.string()),
58
+ action: t.optional(t.string()),
59
+ resourceId: t.optional(t.string()),
60
+ since: t.optional(t.string()),
61
+ limit: t.optional(t.number()),
62
+ })
63
+
64
+ export const VaultKeyOutput = t.object({
65
+ id: t.string(),
66
+ tenantId: t.optional(t.string()),
67
+ alias: t.string(),
68
+ usage: t.string(),
69
+ algorithm: t.string(),
70
+ status: t.string(),
71
+ currentVersion: t.number(),
72
+ rotation: t.any(),
73
+ ownerId: t.optional(t.string()),
74
+ metadata: t.optional(t.any()),
75
+ createdAt: t.string(),
76
+ updatedAt: t.string(),
77
+ })
78
+
79
+ export const EncryptedEnvelopeOutput = t.object({
80
+ keyId: t.string(),
81
+ keyAlias: t.string(),
82
+ keyVersion: t.number(),
83
+ algorithm: t.string(),
84
+ ciphertext: t.string(),
85
+ aad: t.optional(t.string()),
86
+ createdAt: t.string(),
87
+ })
88
+
89
+ export const HealthOutput = t.object({
90
+ status: t.string(),
91
+ mode: t.string(),
92
+ adapter: t.string(),
93
+ kms: t.string(),
94
+ capabilities: t.array(t.string()),
95
+ contractVersion: t.string(),
96
+ migrations: t.any(),
97
+ keys: t.any(),
98
+ checks: t.array(t.any()),
99
+ })
100
+
101
+ /** Schema-first surface consumed by REST, OpenAPI, MCP and AI structured outputs. */
102
+ export const VAULT_HTTP_CONTRACTS = {
103
+ "vault.keys.generate": {method: "POST", path: "/vault/keys", input: GenerateKeyBody, output: VaultKeyOutput},
104
+ "vault.keys.rotate": {method: "POST", path: "/vault/keys/rotate", input: RotateKeyBody, output: VaultKeyOutput},
105
+ "vault.keys.destroy": {method: "POST", path: "/vault/keys/destroy", input: DestroyKeyBody, output: VaultKeyOutput},
106
+ "vault.keys.list": {method: "GET", path: "/vault/keys", input: KeyListQuery, output: t.array(VaultKeyOutput)},
107
+ "vault.encrypt": {method: "POST", path: "/vault/encrypt", input: EncryptBody, output: EncryptedEnvelopeOutput},
108
+ "vault.decrypt": {method: "POST", path: "/vault/decrypt", input: DecryptBody, output: t.object({plaintext: t.string()})},
109
+ "vault.audit.list": {method: "GET", path: "/vault/audit", input: AuditQuery, output: t.array(t.any())},
110
+ "vault.health": {method: "GET", path: "/vault/health", input: t.object({}), output: HealthOutput},
111
+ } as const
@@ -0,0 +1,18 @@
1
+ export * from "./types.ts"
2
+ export * from "./errors.ts"
3
+ export * from "./config.ts"
4
+ export * from "./kernel.ts"
5
+ export * from "./plugin.ts"
6
+ export * from "./decorators.ts"
7
+ export * from "./events.ts"
8
+ export * from "./adapters/memory.ts"
9
+ export * from "./adapters/local-kms.ts"
10
+ export * from "./services/audit.ts"
11
+ export * from "./services/keys.ts"
12
+ export * from "./services/envelope.ts"
13
+ export * from "./cqrs/contracts.ts"
14
+ export * from "./cqrs/handlers.ts"
15
+ export * from "./http/contracts.ts"
16
+ export * from "./persistence/model.ts"
17
+ export * from "./persistence/generator.ts"
18
+ export * from "./cli/service.ts"
@@ -0,0 +1,232 @@
1
+ import {randomUUID} from "node:crypto"
2
+ import {CONTRACT_VERSION, resolveVaultConfig} from "./config.ts"
3
+ import type {
4
+ CapabilityId,
5
+ KmsProvider,
6
+ VaultAdapter,
7
+ VaultCheck,
8
+ VaultConfig,
9
+ VaultConfigInput,
10
+ VaultEventContext,
11
+ VaultHealthReport,
12
+ } from "./types.ts"
13
+ import {VAULT_ERRORS, VaultError} from "./errors.ts"
14
+ import {AuditService} from "./services/audit.ts"
15
+ import {KeyService, type VaultEventSink} from "./services/keys.ts"
16
+ import {EnvelopeService} from "./services/envelope.ts"
17
+
18
+ export type VaultListener = (
19
+ name: string,
20
+ payload: Record<string, unknown>,
21
+ context?: VaultEventContext,
22
+ ) => void | Promise<void>
23
+
24
+ export interface VaultKernelOptions {
25
+ adapter: VaultAdapter
26
+ kms: KmsProvider
27
+ now?: () => number
28
+ emit?: VaultEventSink
29
+ }
30
+
31
+ /** Process-wide runtime used by CQRS handlers, controllers and the CLI. */
32
+ export class VaultRuntime {
33
+ private static currentKernel: VaultKernel | null = null
34
+
35
+ static use(kernel: VaultKernel | null): void {
36
+ VaultRuntime.currentKernel = kernel
37
+ }
38
+
39
+ static get current(): VaultKernel | null {
40
+ return VaultRuntime.currentKernel
41
+ }
42
+
43
+ static require(): VaultKernel {
44
+ if (!VaultRuntime.currentKernel) {
45
+ throw new VaultError(VAULT_ERRORS.ADAPTER_MISSING, {
46
+ hint: "Configurez VaultPlugin ou appelez VaultRuntime.use(kernel).",
47
+ })
48
+ }
49
+ return VaultRuntime.currentKernel
50
+ }
51
+
52
+ static reset(): void {
53
+ VaultRuntime.currentKernel = null
54
+ }
55
+ }
56
+
57
+ export class VaultKernel {
58
+ readonly config: VaultConfig
59
+ readonly adapter: VaultAdapter
60
+ readonly kms: KmsProvider
61
+ readonly audit: AuditService
62
+ readonly keys: KeyService
63
+ readonly envelope: EnvelopeService
64
+
65
+ private readonly now: () => number
66
+ private readonly listeners = new Map<string, Set<VaultListener>>()
67
+ private readonly sink?: VaultEventSink
68
+
69
+ constructor(config: VaultConfig, options: VaultKernelOptions) {
70
+ this.config = config
71
+ this.adapter = options.adapter
72
+ this.kms = options.kms
73
+ this.now = options.now ?? (() => Date.now())
74
+ this.sink = options.emit
75
+ this.audit = new AuditService(this.adapter, config.audit, this.now)
76
+ this.keys = new KeyService(this.adapter, this.kms, config, this.audit, {
77
+ now: this.now,
78
+ emit: (name, payload, context) => this.emit(name, payload, context),
79
+ })
80
+ this.envelope = new EnvelopeService(this.keys, this.kms, config, {now: this.now})
81
+ }
82
+
83
+ validate(): this {
84
+ const supported = new Set(this.adapter.capabilities.map(capability => String(capability)))
85
+ for (const capability of this.config.capabilities) {
86
+ if (capability === "foundation") continue
87
+ if (!supported.has(capability)) {
88
+ throw new VaultError(VAULT_ERRORS.ADAPTER_INCOMPLETE, {
89
+ adapter: this.adapter.name,
90
+ capability,
91
+ supported: [...supported],
92
+ })
93
+ }
94
+ }
95
+ if (this.config.capabilities.includes("envelope")) {
96
+ for (const capability of ["generate", "encrypt", "decrypt"] as const) {
97
+ if (!this.kms.capabilities.includes(capability)) {
98
+ throw new VaultError(VAULT_ERRORS.ADAPTER_INCOMPLETE, {
99
+ adapter: this.kms.name,
100
+ capability,
101
+ hint: "Le KMS doit supporter la génération et l'enveloppe.",
102
+ })
103
+ }
104
+ }
105
+ }
106
+ if (this.config.capabilities.includes("audit") && !this.config.audit.enabled) {
107
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
108
+ field: "audit.enabled",
109
+ hint: "La capacité audit exige l'audit activé (fail-closed).",
110
+ })
111
+ }
112
+ return this
113
+ }
114
+
115
+ on(name: string, listener: VaultListener): () => void {
116
+ const listeners = this.listeners.get(name) ?? new Set<VaultListener>()
117
+ listeners.add(listener)
118
+ this.listeners.set(name, listeners)
119
+ return () => listeners.delete(listener)
120
+ }
121
+
122
+ async emit(name: string, payload: Record<string, unknown>, context?: VaultEventContext): Promise<void> {
123
+ const envelope = {
124
+ eventId: randomUUID(),
125
+ occurredAt: new Date(this.now()).toISOString(),
126
+ tenantId: context?.tenantId,
127
+ actorId: context?.actorId,
128
+ correlationId: context?.correlationId,
129
+ ...payload,
130
+ }
131
+ for (const listener of this.listeners.get(name) ?? []) {
132
+ await listener(name, envelope, context)
133
+ }
134
+ if (this.sink) await this.sink(name, envelope, context)
135
+ }
136
+
137
+ async logEvent(name: string, payload: Record<string, unknown>, context: VaultEventContext = {}): Promise<void> {
138
+ await this.emit(name, payload, context)
139
+ }
140
+
141
+ async health(): Promise<VaultHealthReport> {
142
+ const checks: VaultCheck[] = []
143
+ const keys = await this.adapter.listKeys()
144
+ const active = keys.filter(key => key.status === "active")
145
+
146
+ checks.push({
147
+ name: "adapter",
148
+ status: this.adapter.name ? "pass" : "fail",
149
+ message: `Adaptateur ${this.adapter.name}`,
150
+ remediation: this.adapter.name ? undefined : "Configurez un adaptateur de persistance.",
151
+ })
152
+
153
+ const requiredKms: Array<KmsProvider["capabilities"][number]> = this.config.capabilities.includes("envelope")
154
+ ? ["generate", "encrypt", "decrypt"]
155
+ : ["generate"]
156
+ const missing = requiredKms.filter(capability => !this.kms.capabilities.includes(capability))
157
+ checks.push({
158
+ name: "kms",
159
+ status: missing.length === 0 ? "pass" : "fail",
160
+ message: missing.length === 0
161
+ ? `KMS ${this.kms.name}`
162
+ : `KMS ${this.kms.name} incomplet : ${missing.join(", ")}`,
163
+ remediation: missing.length === 0 ? undefined : "Fournissez un KMS supportant les opérations requises.",
164
+ })
165
+
166
+ checks.push({
167
+ name: "audit",
168
+ status: this.config.audit.enabled ? "pass" : "fail",
169
+ message: this.config.audit.enabled ? "Audit actif" : "Audit désactivé",
170
+ remediation: this.config.audit.enabled ? undefined : "Activez audit.enabled pour respecter le fail-closed.",
171
+ })
172
+
173
+ const pending: string[] = []
174
+ checks.push({
175
+ name: "migrations",
176
+ status: pending.length === 0 ? "pass" : "warn",
177
+ message: pending.length === 0 ? "Aucune migration en attente" : `${pending.length} migration(s) en attente`,
178
+ remediation: pending.length === 0 ? undefined : "Exécutez `raiton vault init` pour générer le plan.",
179
+ })
180
+
181
+ const status = checks.some(check => check.status === "fail")
182
+ ? "unhealthy"
183
+ : checks.some(check => check.status === "warn")
184
+ ? "degraded"
185
+ : "healthy"
186
+
187
+ return {
188
+ status,
189
+ mode: this.config.mode,
190
+ adapter: this.adapter.name,
191
+ kms: this.kms.name,
192
+ capabilities: [...this.config.capabilities],
193
+ contractVersion: CONTRACT_VERSION,
194
+ migrations: {applied: 0, pending},
195
+ keys: {total: keys.length, active: active.length},
196
+ checks,
197
+ }
198
+ }
199
+ }
200
+
201
+ export interface CreateVaultKernelOptions {
202
+ adapter?: VaultAdapter
203
+ kms?: KmsProvider
204
+ now?: () => number
205
+ emit?: VaultEventSink
206
+ allowUnimplemented?: boolean
207
+ }
208
+
209
+ export function createVaultKernel(input: VaultConfigInput = {}, options: CreateVaultKernelOptions = {}): VaultKernel {
210
+ const config = resolveVaultConfig(input, {allowUnimplemented: options.allowUnimplemented})
211
+ const adapter = options.adapter
212
+ if (!adapter) {
213
+ throw new VaultError(VAULT_ERRORS.ADAPTER_MISSING, {
214
+ hint: "Passez MemoryVaultAdapter ou un adaptateur ORM généré.",
215
+ })
216
+ }
217
+ if (!options.kms) {
218
+ throw new VaultError(VAULT_ERRORS.KMS_UNAVAILABLE, {
219
+ hint: "Passez LocalKmsProvider ou un adaptateur KMS cloud/HSM.",
220
+ })
221
+ }
222
+ return new VaultKernel(config, {
223
+ adapter,
224
+ kms: options.kms,
225
+ now: options.now,
226
+ emit: options.emit,
227
+ }).validate()
228
+ }
229
+
230
+ export function capabilityEnabled(kernel: VaultKernel, capability: CapabilityId): boolean {
231
+ return kernel.config.capabilities.includes(capability)
232
+ }