@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,167 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createPublicKey,
5
+ generateKeyPairSync,
6
+ randomBytes,
7
+ sign as cryptoSign,
8
+ verify as cryptoVerify,
9
+ type KeyObject,
10
+ } from "node:crypto"
11
+ import {VAULT_ERRORS, VaultError} from "../errors.ts"
12
+ import type {KeyAlgorithm, KmsCapability, KmsGenerateInput, KmsKeyRef, KmsProvider} from "../types.ts"
13
+
14
+ interface Material {
15
+ algorithm: KeyAlgorithm
16
+ secret?: Buffer
17
+ privateKey?: KeyObject
18
+ publicKey?: KeyObject
19
+ publicKeyPem?: string
20
+ }
21
+
22
+ const AES_IV_BYTES = 12
23
+ const AES_TAG_BYTES = 16
24
+
25
+ /**
26
+ * Development KMS provider backed by Node/Bun's audited `node:crypto` module.
27
+ *
28
+ * It keeps material in memory and is intended for tests, local development and
29
+ * demonstrations. Production deployments must provide a cloud KMS or HSM
30
+ * adapter implementing the same contract.
31
+ */
32
+ export class LocalKmsProvider implements KmsProvider {
33
+ readonly name = "local"
34
+ readonly capabilities: readonly KmsCapability[] = [
35
+ "generate",
36
+ "encrypt",
37
+ "decrypt",
38
+ "sign",
39
+ "verify",
40
+ "destroy",
41
+ ]
42
+
43
+ private readonly material = new Map<string, Material>()
44
+
45
+ async generate(input: KmsGenerateInput): Promise<KmsKeyRef> {
46
+ const ref = `local:${input.keyId}:${input.version}:${randomBytes(8).toString("hex")}`
47
+ switch (input.algorithm) {
48
+ case "aes-256-gcm": {
49
+ this.material.set(ref, {
50
+ algorithm: input.algorithm,
51
+ secret: randomBytes(32),
52
+ })
53
+ return {ref, algorithm: input.algorithm}
54
+ }
55
+ case "ed25519": {
56
+ const {publicKey, privateKey} = generateKeyPairSync("ed25519")
57
+ this.material.set(ref, {
58
+ algorithm: input.algorithm,
59
+ publicKey,
60
+ privateKey,
61
+ publicKeyPem: publicKey.export({type: "spki", format: "pem"}).toString(),
62
+ })
63
+ return {ref, algorithm: input.algorithm, publicKey: this.material.get(ref)!.publicKeyPem}
64
+ }
65
+ case "ecdsa-p256": {
66
+ const {publicKey, privateKey} = generateKeyPairSync("ec", {namedCurve: "P-256"})
67
+ this.material.set(ref, {
68
+ algorithm: input.algorithm,
69
+ publicKey,
70
+ privateKey,
71
+ publicKeyPem: publicKey.export({type: "spki", format: "pem"}).toString(),
72
+ })
73
+ return {ref, algorithm: input.algorithm, publicKey: this.material.get(ref)!.publicKeyPem}
74
+ }
75
+ case "rsa-oaep-256": {
76
+ const {publicKey, privateKey} = generateKeyPairSync("rsa", {modulusLength: 2048})
77
+ this.material.set(ref, {
78
+ algorithm: input.algorithm,
79
+ publicKey,
80
+ privateKey,
81
+ publicKeyPem: publicKey.export({type: "spki", format: "pem"}).toString(),
82
+ })
83
+ return {ref, algorithm: input.algorithm, publicKey: this.material.get(ref)!.publicKeyPem}
84
+ }
85
+ default:
86
+ throw new VaultError(VAULT_ERRORS.KMS_UNSUPPORTED, {algorithm: input.algorithm})
87
+ }
88
+ }
89
+
90
+ async encrypt(ref: string, plaintext: Uint8Array, aad?: string): Promise<string> {
91
+ const entry = this.requireMaterial(ref)
92
+ if (entry.algorithm !== "aes-256-gcm" || !entry.secret) {
93
+ throw new VaultError(VAULT_ERRORS.KMS_UNSUPPORTED, {operation: "encrypt", algorithm: entry.algorithm})
94
+ }
95
+ const iv = randomBytes(AES_IV_BYTES)
96
+ const cipher = createCipheriv("aes-256-gcm", entry.secret, iv)
97
+ if (aad) cipher.setAAD(Buffer.from(aad, "utf-8"))
98
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()])
99
+ const tag = cipher.getAuthTag()
100
+ return Buffer.concat([iv, tag, ciphertext]).toString("base64")
101
+ }
102
+
103
+ async decrypt(ref: string, ciphertext: string, aad?: string): Promise<Uint8Array> {
104
+ const entry = this.requireMaterial(ref)
105
+ if (entry.algorithm !== "aes-256-gcm" || !entry.secret) {
106
+ throw new VaultError(VAULT_ERRORS.KMS_UNSUPPORTED, {operation: "decrypt", algorithm: entry.algorithm})
107
+ }
108
+ try {
109
+ const raw = Buffer.from(ciphertext, "base64")
110
+ if (raw.length < AES_IV_BYTES + AES_TAG_BYTES) {
111
+ throw new Error("Ciphertext too short")
112
+ }
113
+ const iv = raw.subarray(0, AES_IV_BYTES)
114
+ const tag = raw.subarray(AES_IV_BYTES, AES_IV_BYTES + AES_TAG_BYTES)
115
+ const body = raw.subarray(AES_IV_BYTES + AES_TAG_BYTES)
116
+ const decipher = createDecipheriv("aes-256-gcm", entry.secret, iv)
117
+ decipher.setAuthTag(tag)
118
+ if (aad) decipher.setAAD(Buffer.from(aad, "utf-8"))
119
+ return Buffer.concat([decipher.update(body), decipher.final()])
120
+ } catch (error: any) {
121
+ throw new VaultError(VAULT_ERRORS.DECRYPT_FAILED, {message: error?.message ?? String(error)})
122
+ }
123
+ }
124
+
125
+ async sign(ref: string, data: Uint8Array): Promise<string> {
126
+ const entry = this.requireMaterial(ref)
127
+ if (!entry.privateKey) {
128
+ throw new VaultError(VAULT_ERRORS.KMS_UNSUPPORTED, {operation: "sign", algorithm: entry.algorithm})
129
+ }
130
+ const algorithm = entry.algorithm === "ed25519" ? null : "sha256"
131
+ return cryptoSign(algorithm, data, entry.privateKey).toString("base64")
132
+ }
133
+
134
+ async verify(ref: string, data: Uint8Array, signature: string): Promise<boolean> {
135
+ const entry = this.requireMaterial(ref)
136
+ const publicKey = entry.publicKey ?? (entry.privateKey ? createPublicKey(entry.privateKey) : undefined)
137
+ if (!publicKey) {
138
+ throw new VaultError(VAULT_ERRORS.KMS_UNSUPPORTED, {operation: "verify", algorithm: entry.algorithm})
139
+ }
140
+ const algorithm = entry.algorithm === "ed25519" ? null : "sha256"
141
+ try {
142
+ return cryptoVerify(algorithm, data, publicKey, Buffer.from(signature, "base64"))
143
+ } catch {
144
+ return false
145
+ }
146
+ }
147
+
148
+ async destroy(ref: string): Promise<void> {
149
+ this.material.delete(ref)
150
+ }
151
+
152
+ /** Number of key materials held by this provider (diagnostics and tests). */
153
+ size(): number {
154
+ return this.material.size
155
+ }
156
+
157
+ private requireMaterial(ref: string): Material {
158
+ const entry = this.material.get(ref)
159
+ if (!entry) {
160
+ throw new VaultError(VAULT_ERRORS.KMS_UNAVAILABLE, {
161
+ ref,
162
+ hint: "Le matériel de clé est absent ou a été détruit.",
163
+ })
164
+ }
165
+ return entry
166
+ }
167
+ }
@@ -0,0 +1,120 @@
1
+ import type {
2
+ AuditEntry,
3
+ AuditFilter,
4
+ KeyFilter,
5
+ KeyVersion,
6
+ VaultAdapter,
7
+ VaultKey,
8
+ } from "../types.ts"
9
+
10
+ function clone<T>(value: T): T {
11
+ return structuredClone(value)
12
+ }
13
+
14
+ /**
15
+ * Deterministic in-memory adapter for tests, demonstrations and agent
16
+ * evaluations. It preserves tenant separation and never mutates returned
17
+ * records by reference.
18
+ */
19
+ export class MemoryVaultAdapter implements VaultAdapter {
20
+ readonly name = "memory"
21
+ readonly capabilities: readonly string[] = [
22
+ "foundation",
23
+ "keys",
24
+ "kms",
25
+ "envelope",
26
+ "audit",
27
+ ]
28
+
29
+ private readonly keys = new Map<string, VaultKey>()
30
+ private readonly versions = new Map<string, KeyVersion>()
31
+ private readonly audit: AuditEntry[] = []
32
+
33
+ async createKey(key: VaultKey): Promise<void> {
34
+ this.keys.set(key.id, clone(key))
35
+ }
36
+
37
+ async updateKey(key: VaultKey): Promise<void> {
38
+ this.keys.set(key.id, clone(key))
39
+ }
40
+
41
+ async deleteKey(id: string): Promise<void> {
42
+ this.keys.delete(id)
43
+ for (const [versionId, version] of this.versions) {
44
+ if (version.keyId === id) this.versions.delete(versionId)
45
+ }
46
+ }
47
+
48
+ async getKey(id: string): Promise<VaultKey | null> {
49
+ const key = this.keys.get(id)
50
+ return key ? clone(key) : null
51
+ }
52
+
53
+ async findKeyByAlias(alias: string, tenantId?: string): Promise<VaultKey | null> {
54
+ for (const key of this.keys.values()) {
55
+ if (key.alias === alias && (key.tenantId ?? undefined) === (tenantId ?? undefined)) return clone(key)
56
+ }
57
+ return null
58
+ }
59
+
60
+ async listKeys(filter: KeyFilter = {}): Promise<VaultKey[]> {
61
+ return [...this.keys.values()]
62
+ .filter(key => {
63
+ if (filter.tenantId !== undefined && (key.tenantId ?? undefined) !== filter.tenantId) return false
64
+ if (filter.usage && key.usage !== filter.usage) return false
65
+ if (filter.status && key.status !== filter.status) return false
66
+ if (filter.alias && key.alias !== filter.alias) return false
67
+ return true
68
+ })
69
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt))
70
+ .map(clone)
71
+ }
72
+
73
+ async createKeyVersion(version: KeyVersion): Promise<void> {
74
+ this.versions.set(version.id, clone(version))
75
+ }
76
+
77
+ async updateKeyVersion(version: KeyVersion): Promise<void> {
78
+ this.versions.set(version.id, clone(version))
79
+ }
80
+
81
+ async getKeyVersion(keyId: string, version: number): Promise<KeyVersion | null> {
82
+ for (const candidate of this.versions.values()) {
83
+ if (candidate.keyId === keyId && candidate.version === version) return clone(candidate)
84
+ }
85
+ return null
86
+ }
87
+
88
+ async listKeyVersions(keyId: string): Promise<KeyVersion[]> {
89
+ return [...this.versions.values()]
90
+ .filter(version => version.keyId === keyId)
91
+ .sort((left, right) => left.version - right.version)
92
+ .map(clone)
93
+ }
94
+
95
+ async appendAudit(entry: AuditEntry): Promise<void> {
96
+ this.audit.push(clone(entry))
97
+ }
98
+
99
+ async listAudit(filter: AuditFilter = {}): Promise<AuditEntry[]> {
100
+ const entries = this.audit
101
+ .filter(entry => {
102
+ if (filter.tenantId !== undefined && (entry.tenantId ?? undefined) !== filter.tenantId) return false
103
+ if (filter.actorId && entry.actorId !== filter.actorId) return false
104
+ if (filter.action && entry.action !== filter.action) return false
105
+ if (filter.resourceId && entry.resourceId !== filter.resourceId) return false
106
+ if (filter.since && entry.occurredAt < filter.since) return false
107
+ return true
108
+ })
109
+ .sort((left, right) => left.occurredAt.localeCompare(right.occurredAt))
110
+ .map(clone)
111
+ return filter.limit && filter.limit > 0 ? entries.slice(-filter.limit) : entries
112
+ }
113
+
114
+ /** Remove every record. Intended for test isolation. */
115
+ clear(): void {
116
+ this.keys.clear()
117
+ this.versions.clear()
118
+ this.audit.length = 0
119
+ }
120
+ }
@@ -0,0 +1,4 @@
1
+ export {VaultPlugin, vaultHealth} from "./plugin.ts"
2
+ export * from "./cqrs/handlers.ts"
3
+ export * from "./events.ts"
4
+ export * from "./http/contracts.ts"
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ import "reflect-metadata"
3
+ import {Command} from "commander"
4
+ import {RaitonCommands, RaitonConfig} from "raiton/core"
5
+ import VaultCommand from "../commands/definitions.ts"
6
+
7
+ const cli = new Command().name("raiton-vault").version("0.0.1")
8
+
9
+ try {
10
+ await RaitonConfig.sync(process.cwd())
11
+ } catch {
12
+ // The standalone binary remains usable outside a Raiton project; commands
13
+ // report a clear prerequisite error instead of crashing.
14
+ }
15
+
16
+ const appdir = new URL("../..", import.meta.url).pathname
17
+ const harvester = new RaitonCommands(cli, appdir, process.cwd())
18
+ await harvester.harvest()
19
+ const vaultCommand = cli.commands.find(command => command.name() === "vault")
20
+ if (!vaultCommand || !vaultCommand.commands.some(command => command.name() === "init")) {
21
+ const command = new VaultCommand(cli, process.cwd(), appdir)
22
+ command.register()
23
+ }
24
+ cli.parse(process.argv)
@@ -0,0 +1,248 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import {LocalKmsProvider} from "../adapters/local-kms.ts"
4
+ import {MemoryVaultAdapter} from "../adapters/memory.ts"
5
+ import {VaultKernel, VaultRuntime, createVaultKernel} from "../kernel.ts"
6
+ import {
7
+ CAPABILITY_DEFINITIONS,
8
+ IMPLEMENTED_CAPABILITIES,
9
+ type VaultConfigInput,
10
+ } from "../types.ts"
11
+ import {
12
+ CONFIG_FILE,
13
+ PRESETS,
14
+ loadProjectConfig,
15
+ presetConfig,
16
+ resolveVaultConfig,
17
+ writeProjectConfig,
18
+ type Preset,
19
+ } from "../config.ts"
20
+ import {planPersistence, writePersistence, type Dialect, type Orm} from "../persistence/generator.ts"
21
+ import {VAULT_ERRORS, VaultError, toVaultError} from "../errors.ts"
22
+
23
+ export interface CliResult {
24
+ code: number
25
+ message?: string
26
+ data?: unknown
27
+ }
28
+
29
+ function splitList(value: unknown): string[] | undefined {
30
+ if (Array.isArray(value)) return value.map(String)
31
+ if (typeof value !== "string" || !value.trim()) return undefined
32
+ return value.split(",").map(item => item.trim()).filter(Boolean)
33
+ }
34
+
35
+ function failure(error: unknown): CliResult {
36
+ const normalized = toVaultError(error)
37
+ return {
38
+ code: normalized.status >= 500 ? 2 : 1,
39
+ message: `${normalized.code}: ${normalized.message}`,
40
+ data: normalized.toJSON(),
41
+ }
42
+ }
43
+
44
+ export class VaultCliService {
45
+ constructor(private readonly workdir: string = process.cwd()) {}
46
+
47
+ private async input(): Promise<VaultConfigInput> {
48
+ return loadProjectConfig(this.workdir)
49
+ }
50
+
51
+ async kernel(input?: VaultConfigInput): Promise<VaultKernel> {
52
+ const config = resolveVaultConfig(input ?? await this.input())
53
+ const kernel = createVaultKernel(config, {
54
+ adapter: new MemoryVaultAdapter(),
55
+ kms: new LocalKmsProvider(),
56
+ })
57
+ VaultRuntime.use(kernel)
58
+ return kernel
59
+ }
60
+
61
+ async init(options: Record<string, any> = {}): Promise<CliResult> {
62
+ try {
63
+ const preset = (options.preset ?? "local") as Preset
64
+ if (!PRESETS.includes(preset)) {
65
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {field: "preset", value: preset, allowed: PRESETS})
66
+ }
67
+ const capabilities = splitList(options.capabilities)
68
+ const input: VaultConfigInput = {
69
+ ...presetConfig(preset),
70
+ ...(capabilities ? {capabilities} : {}),
71
+ ...(options.mode ? {mode: options.mode as VaultConfigInput["mode"]} : {}),
72
+ ...(options.orm || options.dialect || options.directory
73
+ ? {
74
+ persistence: {
75
+ ...(options.orm ? {orm: String(options.orm)} : {}),
76
+ ...(options.dialect ? {dialect: options.dialect} : {}),
77
+ ...(options.directory ? {directory: String(options.directory)} : {}),
78
+ },
79
+ }
80
+ : {}),
81
+ }
82
+ const config = resolveVaultConfig(input)
83
+ const target = path.resolve(this.workdir, CONFIG_FILE)
84
+ if (fs.existsSync(target) && !options.force) {
85
+ throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {
86
+ file: CONFIG_FILE,
87
+ hint: "Utilisez --force pour remplacer la configuration existante.",
88
+ })
89
+ }
90
+
91
+ const files: string[] = []
92
+ if (!options.dryRun) {
93
+ files.push(writeProjectConfig(this.workdir, config))
94
+ const plan = planPersistence({
95
+ orm: options.orm as Orm | undefined,
96
+ dialect: options.dialect as Dialect | undefined,
97
+ directory: config.persistence.directory,
98
+ })
99
+ files.push(...writePersistence(plan, this.workdir))
100
+ }
101
+
102
+ const data = {
103
+ config: CONFIG_FILE,
104
+ capabilities: config.capabilities,
105
+ adapter: options.adapter ?? "memory",
106
+ kms: config.kms.provider,
107
+ files: options.dryRun ? [] : files,
108
+ dryRun: Boolean(options.dryRun),
109
+ }
110
+ return {
111
+ code: 0,
112
+ message: options.dryRun
113
+ ? `Configuration prête (${config.capabilities.join(", ")}), aucune écriture.`
114
+ : `@raiton/vault initialisé : ${config.capabilities.join(", ")}.`,
115
+ data,
116
+ }
117
+ } catch (error) {
118
+ return failure(error)
119
+ }
120
+ }
121
+
122
+ async doctor(options: Record<string, any> = {}): Promise<CliResult> {
123
+ try {
124
+ const kernel = await this.kernel()
125
+ const health = await kernel.health()
126
+ const failed = health.checks.filter(check => check.status === "fail")
127
+ return {
128
+ code: failed.length === 0 ? 0 : 2,
129
+ message: failed.length === 0
130
+ ? `Coffre sain (${health.adapter}, ${health.kms}, ${health.keys.total} clé(s)).`
131
+ : `Diagnostic en échec : ${failed.map(check => check.name).join(", ")}.`,
132
+ data: health,
133
+ }
134
+ } catch (error) {
135
+ return failure(error)
136
+ }
137
+ }
138
+
139
+ async capabilities(options: Record<string, any> = {}): Promise<CliResult> {
140
+ try {
141
+ const config = resolveVaultConfig(await this.input(), {allowUnimplemented: true})
142
+ const enabled = new Set(config.capabilities)
143
+ const data = CAPABILITY_DEFINITIONS.map(definition => ({
144
+ id: definition.id,
145
+ code: definition.code,
146
+ label: definition.label,
147
+ requires: definition.requires,
148
+ implemented: IMPLEMENTED_CAPABILITIES.includes(definition.id),
149
+ enabled: enabled.has(definition.id),
150
+ }))
151
+ return {code: 0, data}
152
+ } catch (error) {
153
+ return failure(error)
154
+ }
155
+ }
156
+
157
+ async inspect(options: Record<string, any> = {}): Promise<CliResult> {
158
+ try {
159
+ const kernel = await this.kernel()
160
+ const filter = {
161
+ tenantId: options.tenant,
162
+ alias: options.alias,
163
+ }
164
+ const keys = await kernel.keys.list(filter)
165
+ const data = await Promise.all(keys.map(async key => ({
166
+ ...key,
167
+ versions: await kernel.keys.listVersions(key),
168
+ })))
169
+ return {
170
+ code: 0,
171
+ message: `${data.length} clé(s).`,
172
+ data,
173
+ }
174
+ } catch (error) {
175
+ return failure(error)
176
+ }
177
+ }
178
+
179
+ async rotate(options: Record<string, any> = {}): Promise<CliResult> {
180
+ try {
181
+ const kernel = await this.kernel()
182
+ const reference = options.key ?? options.alias
183
+ if (!reference) throw new VaultError(VAULT_ERRORS.CONFIG_INVALID, {field: "key"})
184
+ const result = await kernel.keys.rotate({
185
+ key: String(reference),
186
+ tenantId: options.tenant,
187
+ reason: options.reason ?? "cli",
188
+ actor: {actorId: "cli", tenantId: options.tenant, correlationId: `cli-${Date.now()}`},
189
+ })
190
+ return {
191
+ code: 0,
192
+ message: `Clé ${result.key.alias} portée à la version ${result.version.version}.`,
193
+ data: result,
194
+ }
195
+ } catch (error) {
196
+ return failure(error)
197
+ }
198
+ }
199
+
200
+ async export(options: Record<string, any> = {}): Promise<CliResult> {
201
+ try {
202
+ const kernel = await this.kernel()
203
+ const entries = await kernel.audit.list({
204
+ tenantId: options.tenant,
205
+ actorId: options.actor,
206
+ action: options.action,
207
+ resourceId: options.resource,
208
+ limit: options.limit ? Number(options.limit) : undefined,
209
+ })
210
+ if (options.out) {
211
+ const target = path.resolve(this.workdir, String(options.out))
212
+ fs.mkdirSync(path.dirname(target), {recursive: true})
213
+ fs.writeFileSync(target, `${JSON.stringify(entries, null, 2)}\n`, "utf-8")
214
+ return {code: 0, message: `Preuves exportées vers ${target}.`, data: {file: target, count: entries.length}}
215
+ }
216
+ return {code: 0, message: `${entries.length} preuve(s).`, data: entries}
217
+ } catch (error) {
218
+ return failure(error)
219
+ }
220
+ }
221
+
222
+ async generate(options: Record<string, any> = {}): Promise<CliResult> {
223
+ try {
224
+ const plan = planPersistence({
225
+ orm: (options.orm ?? "generic") as Orm,
226
+ dialect: (options.dialect ?? "postgres") as Dialect,
227
+ directory: options.out,
228
+ tablePrefix: options.prefix ?? "",
229
+ })
230
+ if (!options.dryRun) writePersistence(plan, this.workdir)
231
+ return {
232
+ code: 0,
233
+ message: options.dryRun
234
+ ? `Plan ${plan.orm}/${plan.dialect} prêt pour ${plan.directory}.`
235
+ : `Plan ${plan.orm}/${plan.dialect} écrit dans ${plan.directory}.`,
236
+ data: {
237
+ orm: plan.orm,
238
+ dialect: plan.dialect,
239
+ directory: plan.directory,
240
+ entities: plan.entities.map(entity => entity.entity),
241
+ files: options.dryRun ? [] : Object.keys(plan.files),
242
+ },
243
+ }
244
+ } catch (error) {
245
+ return failure(error)
246
+ }
247
+ }
248
+ }