@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.
- package/AGENTS.md +56 -0
- package/CHANGELOG.md +21 -0
- package/README.en.md +93 -0
- package/README.fr.md +84 -0
- package/README.md +83 -2
- package/docs/errors.fr.md +57 -0
- package/docs/errors.md +57 -0
- package/examples/basic.ts +59 -0
- package/llms.txt +54 -0
- package/main.console.ts +9 -0
- package/package.json +77 -4
- package/source/adapters/local-kms.ts +167 -0
- package/source/adapters/memory.ts +120 -0
- package/source/artifacts.ts +4 -0
- package/source/bin/index.ts +24 -0
- package/source/cli/service.ts +248 -0
- package/source/commands/definitions.ts +151 -0
- package/source/config.ts +281 -0
- package/source/contracts.ts +5 -0
- package/source/cqrs/contracts.ts +111 -0
- package/source/cqrs/handlers.ts +122 -0
- package/source/decorators.ts +57 -0
- package/source/errors.ts +93 -0
- package/source/events.ts +104 -0
- package/source/http/contracts.ts +111 -0
- package/source/index.ts +18 -0
- package/source/kernel.ts +232 -0
- package/source/persistence/generator.ts +180 -0
- package/source/persistence/model.ts +91 -0
- package/source/plugin.ts +148 -0
- package/source/services/audit.ts +52 -0
- package/source/services/envelope.ts +133 -0
- package/source/services/keys.ts +339 -0
- package/source/types.ts +501 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import fs from "node:fs"
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
import {CANONICAL_ENTITIES, type ColumnDefinition, type EntityDefinition} from "./model.ts"
|
|
4
|
+
|
|
5
|
+
export type Dialect = "postgres" | "mysql" | "sqlite"
|
|
6
|
+
export type Orm = "prisma" | "drizzle" | "typeorm" | "kysely" | "sequelize" | "generic"
|
|
7
|
+
|
|
8
|
+
export interface PlanOptions {
|
|
9
|
+
orm?: Orm
|
|
10
|
+
dialect?: Dialect
|
|
11
|
+
directory?: string
|
|
12
|
+
tablePrefix?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface PersistencePlan {
|
|
16
|
+
orm: Orm
|
|
17
|
+
dialect: Dialect
|
|
18
|
+
directory: string
|
|
19
|
+
tablePrefix: string
|
|
20
|
+
entities: EntityDefinition[]
|
|
21
|
+
files: Record<string, string>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const TYPES: Record<Dialect, Record<ColumnDefinition["type"], string>> = {
|
|
25
|
+
postgres: {
|
|
26
|
+
uuid: "uuid",
|
|
27
|
+
text: "text",
|
|
28
|
+
integer: "integer",
|
|
29
|
+
real: "double precision",
|
|
30
|
+
json: "jsonb",
|
|
31
|
+
timestamp: "timestamptz",
|
|
32
|
+
boolean: "boolean",
|
|
33
|
+
},
|
|
34
|
+
mysql: {
|
|
35
|
+
uuid: "char(36)",
|
|
36
|
+
text: "text",
|
|
37
|
+
integer: "int",
|
|
38
|
+
real: "double",
|
|
39
|
+
json: "json",
|
|
40
|
+
timestamp: "datetime",
|
|
41
|
+
boolean: "boolean",
|
|
42
|
+
},
|
|
43
|
+
sqlite: {
|
|
44
|
+
uuid: "text",
|
|
45
|
+
text: "text",
|
|
46
|
+
integer: "integer",
|
|
47
|
+
real: "real",
|
|
48
|
+
json: "text",
|
|
49
|
+
timestamp: "text",
|
|
50
|
+
boolean: "integer",
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function quote(dialect: Dialect, identifier: string): string {
|
|
55
|
+
return dialect === "mysql" ? `\`${identifier}\`` : `"${identifier}"`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function camel(name: string): string {
|
|
59
|
+
return name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function tableName(entity: EntityDefinition, prefix = ""): string {
|
|
63
|
+
return `${prefix}${entity.table}`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function generateSql(dialect: Dialect, prefix = ""): string {
|
|
67
|
+
const statements: string[] = []
|
|
68
|
+
for (const entity of CANONICAL_ENTITIES) {
|
|
69
|
+
const table = tableName(entity, prefix)
|
|
70
|
+
const columns = entity.columns.map(column => {
|
|
71
|
+
const parts = [quote(dialect, column.name), TYPES[dialect][column.type]]
|
|
72
|
+
if (column.primary) parts.push("PRIMARY KEY")
|
|
73
|
+
if (!column.nullable && !column.primary) parts.push("NOT NULL")
|
|
74
|
+
if (column.unique) parts.push("UNIQUE")
|
|
75
|
+
if (dialect === "postgres" && column.type === "timestamp" && (column.name === "created_at" || column.name === "updated_at")) {
|
|
76
|
+
parts.push("DEFAULT now()")
|
|
77
|
+
}
|
|
78
|
+
return ` ${parts.join(" ")}`
|
|
79
|
+
})
|
|
80
|
+
statements.push(`CREATE TABLE IF NOT EXISTS ${quote(dialect, table)} (\n${columns.join(",\n")}\n);`)
|
|
81
|
+
for (const column of entity.columns.filter(item => item.indexed && !item.primary)) {
|
|
82
|
+
statements.push(`CREATE INDEX IF NOT EXISTS ${quote(dialect, `idx_${table}_${column.name}`)} ON ${quote(dialect, table)} (${quote(dialect, column.name)});`)
|
|
83
|
+
}
|
|
84
|
+
for (const index of entity.indexes ?? []) {
|
|
85
|
+
statements.push(`CREATE INDEX IF NOT EXISTS ${quote(dialect, `idx_${table}_${index.join("_")}`)} ON ${quote(dialect, table)} (${index.map(item => quote(dialect, item)).join(", ")});`)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return `${statements.join("\n\n")}\n`
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function generateTables(prefix: string): string {
|
|
92
|
+
const tables: Record<string, string> = {}
|
|
93
|
+
const columns: Record<string, Record<string, string>> = {}
|
|
94
|
+
for (const entity of CANONICAL_ENTITIES) {
|
|
95
|
+
tables[entity.entity] = tableName(entity, prefix)
|
|
96
|
+
columns[entity.entity] = Object.fromEntries(entity.columns.map(column => [camel(column.name), column.name]))
|
|
97
|
+
}
|
|
98
|
+
return `/** Generated by @raiton/vault. Do not edit by hand. */
|
|
99
|
+
export const TABLES = ${JSON.stringify(tables, null, 2)} as const
|
|
100
|
+
|
|
101
|
+
export const COLUMNS = ${JSON.stringify(columns, null, 2)} as const
|
|
102
|
+
`
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function generateAdapter(orm: Orm): string {
|
|
106
|
+
return `/**
|
|
107
|
+
* Generated VaultAdapter skeleton for ${orm}.
|
|
108
|
+
*
|
|
109
|
+
* Provide a repository factory backed by your ORM and a transaction runner.
|
|
110
|
+
* Key material references are opaque: the adapter must never decrypt values.
|
|
111
|
+
*/
|
|
112
|
+
import type {
|
|
113
|
+
AuditEntry,
|
|
114
|
+
AuditFilter,
|
|
115
|
+
KeyFilter,
|
|
116
|
+
KeyVersion,
|
|
117
|
+
VaultAdapter,
|
|
118
|
+
VaultKey,
|
|
119
|
+
} from "@raiton/vault"
|
|
120
|
+
|
|
121
|
+
export interface VaultDatabase {
|
|
122
|
+
keys: unknown
|
|
123
|
+
versions: unknown
|
|
124
|
+
audit: unknown
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function createVaultAdapter(db: VaultDatabase): VaultAdapter {
|
|
128
|
+
const missing = (operation: string) => {
|
|
129
|
+
throw new Error(\`VaultAdapter.${orm}: \${operation} is not implemented yet.\`)
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
name: "${orm}",
|
|
133
|
+
capabilities: ["foundation", "keys", "kms", "envelope", "audit"],
|
|
134
|
+
async createKey(_key: VaultKey) { return missing("createKey") },
|
|
135
|
+
async updateKey(_key: VaultKey) { return missing("updateKey") },
|
|
136
|
+
async deleteKey(_id: string) { return missing("deleteKey") },
|
|
137
|
+
async getKey(_id: string) { return missing("getKey") },
|
|
138
|
+
async findKeyByAlias(_alias: string, _tenantId?: string) { return missing("findKeyByAlias") },
|
|
139
|
+
async listKeys(_filter?: KeyFilter) { return missing("listKeys") },
|
|
140
|
+
async createKeyVersion(_version: KeyVersion) { return missing("createKeyVersion") },
|
|
141
|
+
async updateKeyVersion(_version: KeyVersion) { return missing("updateKeyVersion") },
|
|
142
|
+
async getKeyVersion(_keyId: string, _version: number) { return missing("getKeyVersion") },
|
|
143
|
+
async listKeyVersions(_keyId: string) { return missing("listKeyVersions") },
|
|
144
|
+
async appendAudit(_entry: AuditEntry) { return missing("appendAudit") },
|
|
145
|
+
async listAudit(_filter?: AuditFilter) { return missing("listAudit") },
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
`
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function planPersistence(options: PlanOptions = {}): PersistencePlan {
|
|
152
|
+
const orm = options.orm ?? "generic"
|
|
153
|
+
const dialect = options.dialect ?? "postgres"
|
|
154
|
+
const directory = options.directory ?? "source/database"
|
|
155
|
+
const tablePrefix = options.tablePrefix ?? ""
|
|
156
|
+
return {
|
|
157
|
+
orm,
|
|
158
|
+
dialect,
|
|
159
|
+
directory,
|
|
160
|
+
tablePrefix,
|
|
161
|
+
entities: CANONICAL_ENTITIES,
|
|
162
|
+
files: {
|
|
163
|
+
"schema.sql": generateSql(dialect, tablePrefix),
|
|
164
|
+
"tables.ts": generateTables(tablePrefix),
|
|
165
|
+
"adapter.ts": generateAdapter(orm),
|
|
166
|
+
},
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function writePersistence(plan: PersistencePlan, workdir = process.cwd()): string[] {
|
|
171
|
+
const target = path.join(workdir, plan.directory)
|
|
172
|
+
fs.mkdirSync(target, {recursive: true})
|
|
173
|
+
const written: string[] = []
|
|
174
|
+
for (const [name, content] of Object.entries(plan.files)) {
|
|
175
|
+
const file = path.join(target, name)
|
|
176
|
+
fs.writeFileSync(file, content, "utf-8")
|
|
177
|
+
written.push(file)
|
|
178
|
+
}
|
|
179
|
+
return written
|
|
180
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical persistence model of @raiton/vault.
|
|
3
|
+
*
|
|
4
|
+
* The core never imports an ORM. Generated adapters map these entities to the
|
|
5
|
+
* host project's database through the VaultAdapter contract.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type ColumnType = "uuid" | "text" | "integer" | "real" | "json" | "timestamp" | "boolean"
|
|
9
|
+
|
|
10
|
+
export interface ColumnDefinition {
|
|
11
|
+
name: string
|
|
12
|
+
type: ColumnType
|
|
13
|
+
nullable?: boolean
|
|
14
|
+
primary?: boolean
|
|
15
|
+
indexed?: boolean
|
|
16
|
+
unique?: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface EntityDefinition {
|
|
20
|
+
entity: string
|
|
21
|
+
table: string
|
|
22
|
+
description: string
|
|
23
|
+
columns: ColumnDefinition[]
|
|
24
|
+
indexes?: string[][]
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const base: ColumnDefinition[] = [
|
|
28
|
+
{name: "id", type: "uuid", primary: true},
|
|
29
|
+
{name: "created_at", type: "timestamp"},
|
|
30
|
+
{name: "updated_at", type: "timestamp"},
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
const tenant: ColumnDefinition = {name: "tenant_id", type: "text", nullable: true, indexed: true}
|
|
34
|
+
|
|
35
|
+
export const CANONICAL_ENTITIES: EntityDefinition[] = [
|
|
36
|
+
{
|
|
37
|
+
entity: "VaultKey",
|
|
38
|
+
table: "vault_keys",
|
|
39
|
+
description: "Clé logique : alias, usage, algorithme, politique de rotation et statut.",
|
|
40
|
+
columns: [
|
|
41
|
+
...base,
|
|
42
|
+
{name: "alias", type: "text", indexed: true},
|
|
43
|
+
{name: "usage", type: "text", indexed: true},
|
|
44
|
+
{name: "algorithm", type: "text"},
|
|
45
|
+
{name: "status", type: "text", indexed: true},
|
|
46
|
+
{name: "current_version", type: "integer"},
|
|
47
|
+
{name: "rotation", type: "json"},
|
|
48
|
+
{name: "owner_id", type: "text", nullable: true, indexed: true},
|
|
49
|
+
tenant,
|
|
50
|
+
{name: "metadata", type: "json", nullable: true},
|
|
51
|
+
],
|
|
52
|
+
indexes: [["alias", "tenant_id"]],
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
entity: "KeyVersion",
|
|
56
|
+
table: "vault_key_versions",
|
|
57
|
+
description: "Version immuable d'une clé, matériel référencé et cycle de vie.",
|
|
58
|
+
columns: [
|
|
59
|
+
...base,
|
|
60
|
+
{name: "key_id", type: "uuid", indexed: true},
|
|
61
|
+
{name: "version", type: "integer"},
|
|
62
|
+
{name: "material_ref", type: "text"},
|
|
63
|
+
{name: "algorithm", type: "text"},
|
|
64
|
+
{name: "status", type: "text", indexed: true},
|
|
65
|
+
{name: "activated_at", type: "timestamp", nullable: true},
|
|
66
|
+
{name: "deprecated_at", type: "timestamp", nullable: true},
|
|
67
|
+
{name: "destroyed_at", type: "timestamp", nullable: true},
|
|
68
|
+
],
|
|
69
|
+
indexes: [["key_id", "version"]],
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
entity: "AuditEntry",
|
|
73
|
+
table: "vault_audit",
|
|
74
|
+
description: "Trace d'usage, d'accès, de rotation et de destruction attribuable.",
|
|
75
|
+
columns: [
|
|
76
|
+
{name: "id", type: "uuid", primary: true},
|
|
77
|
+
{name: "occurred_at", type: "timestamp", indexed: true},
|
|
78
|
+
{name: "action", type: "text", indexed: true},
|
|
79
|
+
{name: "outcome", type: "text", indexed: true},
|
|
80
|
+
{name: "resource_type", type: "text"},
|
|
81
|
+
{name: "resource_id", type: "text", indexed: true},
|
|
82
|
+
{name: "key_id", type: "text", nullable: true, indexed: true},
|
|
83
|
+
{name: "key_version", type: "integer", nullable: true},
|
|
84
|
+
tenant,
|
|
85
|
+
{name: "actor_id", type: "text", nullable: true, indexed: true},
|
|
86
|
+
{name: "correlation_id", type: "text", nullable: true, indexed: true},
|
|
87
|
+
{name: "context", type: "json", nullable: true},
|
|
88
|
+
],
|
|
89
|
+
indexes: [["tenant_id", "occurred_at"]],
|
|
90
|
+
},
|
|
91
|
+
]
|
package/source/plugin.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import "reflect-metadata"
|
|
2
|
+
import fs from "node:fs"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
import {pathToFileURL} from "node:url"
|
|
5
|
+
import {Plugin} from "raiton/framework"
|
|
6
|
+
import {Application, RaitonConfig} from "raiton/core"
|
|
7
|
+
import type {PluginScope} from "raiton/core"
|
|
8
|
+
import type {KmsProvider, VaultAdapter, VaultConfigInput, VaultHealthReport} from "./types.ts"
|
|
9
|
+
import {MemoryVaultAdapter} from "./adapters/memory.ts"
|
|
10
|
+
import {LocalKmsProvider} from "./adapters/local-kms.ts"
|
|
11
|
+
import {VaultKernel, VaultRuntime} from "./kernel.ts"
|
|
12
|
+
import {CONTRACT_VERSION, loadProjectConfig, resolveVaultConfig} from "./config.ts"
|
|
13
|
+
import {VAULT_EVENTS} from "./events.ts"
|
|
14
|
+
import {VAULT_ERRORS, VaultError} from "./errors.ts"
|
|
15
|
+
|
|
16
|
+
let providedAdapter: VaultAdapter | (() => VaultAdapter) | null = null
|
|
17
|
+
let providedKms: KmsProvider | (() => KmsProvider) | null = null
|
|
18
|
+
let lastKernel: VaultKernel | null = null
|
|
19
|
+
|
|
20
|
+
export function setVaultAdapter(adapter: VaultAdapter | (() => VaultAdapter) | null): void {
|
|
21
|
+
providedAdapter = adapter
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function getVaultAdapter(): VaultAdapter {
|
|
25
|
+
if (!providedAdapter) return new MemoryVaultAdapter()
|
|
26
|
+
return typeof providedAdapter === "function" ? providedAdapter() : providedAdapter
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function setVaultKms(kms: KmsProvider | (() => KmsProvider) | null): void {
|
|
30
|
+
providedKms = kms
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function getVaultKms(): KmsProvider {
|
|
34
|
+
if (!providedKms) return new LocalKmsProvider()
|
|
35
|
+
return typeof providedKms === "function" ? providedKms() : providedKms
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function getVaultKernel(): VaultKernel | null {
|
|
39
|
+
return lastKernel
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function moduleConfig(project: Record<string, any>): Promise<VaultConfigInput> {
|
|
43
|
+
const vault = project.vault ?? {}
|
|
44
|
+
const nested = vault.module ?? project.vaultModule ?? {}
|
|
45
|
+
const adapter = vault.adapter
|
|
46
|
+
if (adapter && typeof adapter === "object" && typeof adapter.transaction === "function") {
|
|
47
|
+
providedAdapter = adapter as VaultAdapter
|
|
48
|
+
}
|
|
49
|
+
const fileConfig = await loadProjectConfig(process.cwd())
|
|
50
|
+
return {...fileConfig, ...nested} as VaultConfigInput
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function generatedAdapter(config: ReturnType<typeof resolveVaultConfig>, project: Record<string, any>): Promise<VaultAdapter | undefined> {
|
|
54
|
+
if (providedAdapter) return undefined
|
|
55
|
+
const orm = config.persistence.orm
|
|
56
|
+
if (!orm) return undefined
|
|
57
|
+
const candidates = [
|
|
58
|
+
path.join("source", "vault", "persistence", String(orm), "adapter.ts"),
|
|
59
|
+
path.join(config.persistence.directory, "vault", "persistence", String(orm), "adapter.ts"),
|
|
60
|
+
path.join(config.persistence.directory, "adapter.ts"),
|
|
61
|
+
]
|
|
62
|
+
for (const candidate of candidates) {
|
|
63
|
+
if (!fs.existsSync(candidate)) continue
|
|
64
|
+
try {
|
|
65
|
+
const module = await import(pathToFileURL(path.resolve(candidate)).href)
|
|
66
|
+
const factoryName = Object.keys(module).find(key => /^create.*VaultAdapter$/.test(key))
|
|
67
|
+
const token = (typeof project.orm === "string" ? project.orm : project.orm?.token) ?? orm
|
|
68
|
+
const provider = Application.container.get(token) as any
|
|
69
|
+
const db = provider?.db ?? provider?.client ?? provider?.connection ?? provider
|
|
70
|
+
if (module.default && typeof module.default.transaction === "function") return module.default as VaultAdapter
|
|
71
|
+
if (factoryName && typeof module[factoryName] === "function") {
|
|
72
|
+
if (!db) throw new Error(`Le provider ORM "${token}" est introuvable dans le conteneur.`)
|
|
73
|
+
const adapter = module[factoryName](db)
|
|
74
|
+
if (adapter && typeof adapter.transaction === "function") return adapter as VaultAdapter
|
|
75
|
+
}
|
|
76
|
+
throw new Error(`Le fichier ${candidate} n'expose pas de fabrique d'adaptateur.`)
|
|
77
|
+
} catch (error: any) {
|
|
78
|
+
throw new VaultError(VAULT_ERRORS.ADAPTER_INCOMPLETE, {
|
|
79
|
+
file: candidate,
|
|
80
|
+
message: error?.message ?? String(error),
|
|
81
|
+
hint: "Générez le kit ORM Raiton et vérifiez le token du provider.",
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return undefined
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Idempotent module plugin: configures the kernel and publishes lifecycle events. */
|
|
89
|
+
@Plugin({name: "raiton-vault"})
|
|
90
|
+
export class VaultPlugin {
|
|
91
|
+
async setup(scope: PluginScope): Promise<void> {
|
|
92
|
+
const project = RaitonConfig.toObject() as Record<string, any>
|
|
93
|
+
const input = await moduleConfig(project)
|
|
94
|
+
const config = resolveVaultConfig(input)
|
|
95
|
+
|
|
96
|
+
const configuredAdapter = await generatedAdapter(config, project)
|
|
97
|
+
const adapter = configuredAdapter ?? getVaultAdapter()
|
|
98
|
+
const kms = getVaultKms()
|
|
99
|
+
const kernel = new VaultKernel(config, {adapter, kms}).validate()
|
|
100
|
+
lastKernel = kernel
|
|
101
|
+
VaultRuntime.use(kernel)
|
|
102
|
+
|
|
103
|
+
scope.addHook("onStart", async () => {
|
|
104
|
+
await kernel.logEvent("VaultStarted", {
|
|
105
|
+
capabilities: config.capabilities,
|
|
106
|
+
adapter: kernel.adapter.name,
|
|
107
|
+
kms: kernel.kms.name,
|
|
108
|
+
contractVersion: CONTRACT_VERSION,
|
|
109
|
+
}, {})
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
if (typeof (scope as any).use === "function") {
|
|
113
|
+
;(scope as any).use(async ({context, next}: any) => {
|
|
114
|
+
context.state.vaultModule = {
|
|
115
|
+
name: "@raiton/vault",
|
|
116
|
+
capabilities: config.capabilities,
|
|
117
|
+
adapter: kernel.adapter.name,
|
|
118
|
+
kms: kernel.kms.name,
|
|
119
|
+
}
|
|
120
|
+
return next()
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function vaultHealth(kernel: VaultKernel | null = VaultRuntime.current): Promise<VaultHealthReport> {
|
|
127
|
+
if (!kernel) {
|
|
128
|
+
return {
|
|
129
|
+
status: "unhealthy",
|
|
130
|
+
mode: "single",
|
|
131
|
+
adapter: "none",
|
|
132
|
+
kms: "none",
|
|
133
|
+
capabilities: [],
|
|
134
|
+
contractVersion: CONTRACT_VERSION,
|
|
135
|
+
migrations: {applied: 0, pending: ["kernel"]},
|
|
136
|
+
keys: {total: 0, active: 0},
|
|
137
|
+
checks: [{
|
|
138
|
+
name: "kernel",
|
|
139
|
+
status: "fail",
|
|
140
|
+
message: "Kernel non configuré",
|
|
141
|
+
remediation: "Montez VaultPlugin ou appelez VaultRuntime.use(kernel).",
|
|
142
|
+
}],
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return kernel.health()
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export {VAULT_EVENTS}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {randomUUID} from "node:crypto"
|
|
2
|
+
import type {AuditAction, AuditEntry, AuditFilter, AuditOutcome, VaultAdapter, VaultAuditConfig, VaultEventContext} from "../types.ts"
|
|
3
|
+
import {VAULT_ERRORS, VaultError} from "../errors.ts"
|
|
4
|
+
|
|
5
|
+
export interface AuditRecordInput {
|
|
6
|
+
action: AuditAction
|
|
7
|
+
outcome: AuditOutcome
|
|
8
|
+
resourceType: AuditEntry["resourceType"]
|
|
9
|
+
resourceId: string
|
|
10
|
+
keyId?: string
|
|
11
|
+
keyVersion?: number
|
|
12
|
+
context?: Record<string, unknown>
|
|
13
|
+
actor?: VaultEventContext
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class AuditService {
|
|
17
|
+
constructor(
|
|
18
|
+
private readonly adapter: VaultAdapter,
|
|
19
|
+
private readonly config: VaultAuditConfig,
|
|
20
|
+
private readonly now: () => number = () => Date.now(),
|
|
21
|
+
) {}
|
|
22
|
+
|
|
23
|
+
get enabled(): boolean {
|
|
24
|
+
return this.config.enabled
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async record(input: AuditRecordInput): Promise<AuditEntry> {
|
|
28
|
+
if (!this.config.enabled) {
|
|
29
|
+
throw new VaultError(VAULT_ERRORS.AUDIT_DISABLED, {action: input.action})
|
|
30
|
+
}
|
|
31
|
+
const entry: AuditEntry = {
|
|
32
|
+
id: randomUUID(),
|
|
33
|
+
action: input.action,
|
|
34
|
+
outcome: input.outcome,
|
|
35
|
+
resourceType: input.resourceType,
|
|
36
|
+
resourceId: input.resourceId,
|
|
37
|
+
keyId: input.keyId,
|
|
38
|
+
keyVersion: input.keyVersion,
|
|
39
|
+
tenantId: input.actor?.tenantId,
|
|
40
|
+
actorId: input.actor?.actorId,
|
|
41
|
+
correlationId: input.actor?.correlationId,
|
|
42
|
+
context: input.context,
|
|
43
|
+
occurredAt: new Date(this.now()).toISOString(),
|
|
44
|
+
}
|
|
45
|
+
await this.adapter.appendAudit(entry)
|
|
46
|
+
return entry
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async list(filter: AuditFilter = {}): Promise<AuditEntry[]> {
|
|
50
|
+
return this.adapter.listAudit(filter)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DecryptInput,
|
|
3
|
+
EncryptInput,
|
|
4
|
+
EncryptedEnvelope,
|
|
5
|
+
KmsProvider,
|
|
6
|
+
VaultConfig,
|
|
7
|
+
VaultEventContext,
|
|
8
|
+
} from "../types.ts"
|
|
9
|
+
import {VAULT_ERRORS, VaultError} from "../errors.ts"
|
|
10
|
+
import {KeyService} from "./keys.ts"
|
|
11
|
+
|
|
12
|
+
export interface EnvelopeServiceOptions {
|
|
13
|
+
now?: () => number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const encoder = new TextEncoder()
|
|
17
|
+
const decoder = new TextDecoder()
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Envelope encryption service.
|
|
21
|
+
*
|
|
22
|
+
* The data encryption key (DEK) is generated and used inside the configured KMS
|
|
23
|
+
* provider. The envelope only references the key and its immutable version, so
|
|
24
|
+
* rotating a key never breaks existing ciphertexts.
|
|
25
|
+
*/
|
|
26
|
+
export class EnvelopeService {
|
|
27
|
+
private readonly now: () => number
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
private readonly keys: KeyService,
|
|
31
|
+
private readonly kms: KmsProvider,
|
|
32
|
+
private readonly config: VaultConfig,
|
|
33
|
+
options: EnvelopeServiceOptions = {},
|
|
34
|
+
) {
|
|
35
|
+
this.now = options.now ?? (() => Date.now())
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async encrypt(input: EncryptInput): Promise<EncryptedEnvelope> {
|
|
39
|
+
this.assertEnabled()
|
|
40
|
+
const key = await this.keys.resolve(input.key, input.tenantId)
|
|
41
|
+
const version = await this.keys.activeVersion(key)
|
|
42
|
+
const actor: VaultEventContext = {
|
|
43
|
+
actorId: input.actor?.actorId,
|
|
44
|
+
tenantId: input.tenantId ?? key.tenantId,
|
|
45
|
+
correlationId: input.actor?.correlationId,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
this.keys.assertUsage(key, "encrypt")
|
|
50
|
+
} catch (error) {
|
|
51
|
+
await this.keys.recordUse(key, version, "encrypt", "denied", actor, {reason: "usage"})
|
|
52
|
+
throw error
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const plaintext = typeof input.plaintext === "string" ? encoder.encode(input.plaintext) : input.plaintext
|
|
56
|
+
const aad = this.aadFor(key.id, version.version, input.aad)
|
|
57
|
+
try {
|
|
58
|
+
const ciphertext = await this.kms.encrypt(version.materialRef, plaintext, aad)
|
|
59
|
+
await this.keys.recordUse(key, version, "encrypt", "success", actor, {
|
|
60
|
+
algorithm: key.algorithm,
|
|
61
|
+
aad: Boolean(aad),
|
|
62
|
+
})
|
|
63
|
+
return {
|
|
64
|
+
keyId: key.id,
|
|
65
|
+
keyAlias: key.alias,
|
|
66
|
+
keyVersion: version.version,
|
|
67
|
+
algorithm: key.algorithm,
|
|
68
|
+
ciphertext,
|
|
69
|
+
aad: input.aad,
|
|
70
|
+
createdAt: new Date(this.now()).toISOString(),
|
|
71
|
+
}
|
|
72
|
+
} catch (error) {
|
|
73
|
+
await this.keys.recordUse(key, version, "encrypt", "failure", actor, {reason: "kms"})
|
|
74
|
+
if (error instanceof VaultError) throw error
|
|
75
|
+
throw new VaultError(VAULT_ERRORS.ENCRYPT_FAILED, {
|
|
76
|
+
message: error instanceof Error ? error.message : String(error),
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async decrypt(input: DecryptInput): Promise<string> {
|
|
82
|
+
return decoder.decode(await this.decryptBytes(input))
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async decryptBytes(input: DecryptInput): Promise<Uint8Array> {
|
|
86
|
+
this.assertEnabled()
|
|
87
|
+
const envelope = input.envelope
|
|
88
|
+
const key = await this.keys.resolve(envelope.keyId, input.tenantId)
|
|
89
|
+
if (key.id !== envelope.keyId) {
|
|
90
|
+
throw new VaultError(VAULT_ERRORS.KEY_VERSION_MISMATCH, {keyId: envelope.keyId})
|
|
91
|
+
}
|
|
92
|
+
const version = await this.keys.version(key, envelope.keyVersion)
|
|
93
|
+
const actor: VaultEventContext = {
|
|
94
|
+
actorId: input.actor?.actorId,
|
|
95
|
+
tenantId: input.tenantId ?? key.tenantId,
|
|
96
|
+
correlationId: input.actor?.correlationId,
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
this.keys.assertUsage(key, "decrypt")
|
|
101
|
+
} catch (error) {
|
|
102
|
+
await this.keys.recordUse(key, version, "decrypt", "denied", actor, {reason: "usage"})
|
|
103
|
+
throw error
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const aad = this.aadFor(key.id, version.version, input.aad ?? envelope.aad)
|
|
107
|
+
try {
|
|
108
|
+
const plaintext = await this.kms.decrypt(version.materialRef, envelope.ciphertext, aad)
|
|
109
|
+
await this.keys.recordUse(key, version, "decrypt", "success", actor, {algorithm: key.algorithm})
|
|
110
|
+
return plaintext
|
|
111
|
+
} catch (error) {
|
|
112
|
+
await this.keys.recordUse(key, version, "decrypt", "failure", actor, {reason: "kms"})
|
|
113
|
+
if (error instanceof VaultError) throw error
|
|
114
|
+
throw new VaultError(VAULT_ERRORS.DECRYPT_FAILED, {
|
|
115
|
+
message: error instanceof Error ? error.message : String(error),
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private aadFor(keyId: string, version: number, provided?: string): string | undefined {
|
|
121
|
+
if (provided !== undefined) return provided
|
|
122
|
+
return this.config.envelope.bindAad ? `${keyId}:${version}` : undefined
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private assertEnabled(): void {
|
|
126
|
+
if (!this.config.capabilities.includes("envelope")) {
|
|
127
|
+
throw new VaultError(VAULT_ERRORS.CAPABILITY_DISABLED, {capability: "envelope"})
|
|
128
|
+
}
|
|
129
|
+
if (!this.config.capabilities.includes("kms")) {
|
|
130
|
+
throw new VaultError(VAULT_ERRORS.CAPABILITY_DISABLED, {capability: "kms"})
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|