kxco-pq-vault 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,182 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combined work (in which such
78
+ Contribution(s) with the Work. If You institute patent litigation
79
+ against any entity (including a cross-claim or counterclaim in a
80
+ lawsuit) alleging that the Work or any Contribution embodied within
81
+ the Work constitutes direct or contributory patent infringement,
82
+ then any patent licenses granted to You under this License for that
83
+ Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative
91
+ Works a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text
106
+ file distributed as part of the Derivative Works; within
107
+ the Source form or documentation, if provided along with the
108
+ Derivative Works; or, within a display generated by the
109
+ Derivative Works, if and wherever such third-party notices
110
+ normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License.
112
+ You may add Your own attribution notices within Derivative
113
+ Works that You distribute, alongside or in addition to the
114
+ NOTICE text from the Work, provided that such additional
115
+ attribution notices cannot be construed as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, reproduce, modify,
119
+ prepare Derivative Works of, publicly display, publicly perform,
120
+ sublicense, and distribute those modifications and that Work.
121
+
122
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
123
+ any Contribution intentionally submitted for inclusion in the Work
124
+ by You to the Licensor shall be under the terms and conditions of
125
+ this License, without any additional terms or conditions.
126
+ Notwithstanding the above, nothing herein shall supersede or modify
127
+ the terms of any separate license agreement you may have executed
128
+ with Licensor regarding such Contributions.
129
+
130
+ 6. Trademarks. This License does not grant permission to use the trade
131
+ names, trademarks, service marks, or product names of the Licensor,
132
+ except as required for reasonable and customary use in describing the
133
+ origin of the Work and reproducing the content of the NOTICE file.
134
+
135
+ 7. Disclaimer of Warranty. Unless required by applicable law or
136
+ agreed to in writing, Licensor provides the Work (and each
137
+ Contributor provides its Contributions) on an "AS IS" BASIS,
138
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
139
+ implied, including, without limitation, any warranties or conditions
140
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
141
+ PARTICULAR PURPOSE. You are solely responsible for determining the
142
+ appropriateness of using or reproducing the Work and assume any
143
+ risks associated with Your exercise of permissions under this License.
144
+
145
+ 8. Limitation of Liability. In no event and under no legal theory,
146
+ whether in tort (including negligence), contract, or otherwise,
147
+ unless required by applicable law (such as deliberate and grossly
148
+ negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special,
150
+ incidental, or exemplary damages of any character arising as a
151
+ result of this License or out of the use or inability to use the
152
+ Work (including but not limited to damages for loss of goodwill,
153
+ work stoppage, computer failure or malfunction, or all other
154
+ commercial damages or losses), even if such Contributor has been
155
+ advised of the possibility of such damages.
156
+
157
+ 9. Accepting Warranty or Additional Liability. While redistributing
158
+ the Work or Derivative Works thereof, You may choose to offer,
159
+ and charge a fee for, acceptance of support, warranty, indemnity,
160
+ or other liability obligations and/or rights consistent with this
161
+ License. However, in accepting such obligations, You may offer only
162
+ conditions that are Your own responsibility and not on behalf of any
163
+ other Contributor, and only if You agree to indemnify, defend, and
164
+ hold each Contributor harmless for any liability incurred by, or
165
+ claims asserted against, such Contributor by reason of your accepting
166
+ any such warranty or additional liability.
167
+
168
+ END OF TERMS AND CONDITIONS
169
+
170
+ Copyright 2026 KXCO
171
+
172
+ Licensed under the Apache License, Version 2.0 (the "License");
173
+ you may not use this file except in compliance with the License.
174
+ You may obtain a copy of the License at
175
+
176
+ http://www.apache.org/licenses/LICENSE-2.0
177
+
178
+ Unless required by applicable law or agreed to in writing, software
179
+ distributed under the License is distributed on an "AS IS" BASIS,
180
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
181
+ See the License for the specific language governing permissions and
182
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,149 @@
1
+ # kxco-pq-vault
2
+
3
+ Post-quantum file encryption CLI and library. Uses **ML-KEM-768** (NIST FIPS 203) for key encapsulation and **AES-256-GCM** for symmetric encryption.
4
+
5
+ A direct answer to "harvest now, decrypt later" attacks: files encrypted today cannot be broken even by a future quantum computer.
6
+
7
+ ```
8
+ npm install -g kxco-pq-vault
9
+ ```
10
+
11
+ ---
12
+
13
+ ## Quick start
14
+
15
+ ```sh
16
+ # 1. Generate a keypair
17
+ kxco-vault keygen --out alice.kxco
18
+
19
+ # 2. Share your recipient string with senders
20
+ kxco-vault recipient alice.kxco
21
+ # → kxco1qvp93xj... (paste this to anyone who needs to encrypt to you)
22
+
23
+ # 3. Encrypt a file
24
+ kxco-vault encrypt secret.txt --recipient kxco1qvp93xj... --out secret.txt.kxco
25
+
26
+ # 4. Decrypt it
27
+ kxco-vault decrypt secret.txt.kxco --identity alice.kxco --out secret.txt
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Commands
33
+
34
+ ### `keygen`
35
+
36
+ ```
37
+ kxco-vault keygen --out <keypair.kxco>
38
+ kxco-vault keygen --out <keypair.kxco> --master <hex> --label <string>
39
+ ```
40
+
41
+ Generates an ML-KEM-768 keypair. The identity file contains both public and secret key material — keep it private.
42
+
43
+ With `--master` + `--label`, derivation is deterministic (same inputs always produce the same keypair). Different labels under the same master produce different keypairs.
44
+
45
+ ### `recipient`
46
+
47
+ ```
48
+ kxco-vault recipient <keypair.kxco>
49
+ ```
50
+
51
+ Prints the `kxco1...` bech32m recipient string from an identity file. Share this string with anyone who needs to encrypt files to you.
52
+
53
+ ### `encrypt`
54
+
55
+ ```
56
+ kxco-vault encrypt <file> --recipient <kxco1...|@keyfile> [--recipient ...] [--out <file.kxco>]
57
+ ```
58
+
59
+ Encrypts a file for one or more recipients. Each recipient can independently decrypt using their identity file.
60
+
61
+ `--recipient` accepts either a `kxco1...` bech32m string or `@/path/to/keypair.kxco`.
62
+
63
+ Multiple `--recipient` flags produce a multi-recipient envelope. All recipients decrypt the same plaintext.
64
+
65
+ ### `decrypt`
66
+
67
+ ```
68
+ kxco-vault decrypt <file.kxco> --identity <keypair.kxco> [--out <file>]
69
+ ```
70
+
71
+ Decrypts an envelope using your identity file. Fails cleanly if your identity is not a recipient in the envelope, or if the envelope has been tampered with.
72
+
73
+ ### `inspect`
74
+
75
+ ```
76
+ kxco-vault inspect <file.kxco>
77
+ ```
78
+
79
+ Prints the envelope header without decrypting: algorithm, recipient count, recipient key IDs, nonce, created timestamp, and ciphertext size.
80
+
81
+ ---
82
+
83
+ ## Envelope format
84
+
85
+ `.kxco` files have a plain-text header (readable with `cat`/`less`) followed by raw binary ciphertext:
86
+
87
+ ```
88
+ KXCO-VAULT/1.0
89
+ algorithm: ml-kem-768+aes-256-gcm
90
+ recipients: 1
91
+ recipient[0].kid: <16 hex chars — first 8 bytes of SHA-256(pubkey)>
92
+ recipient[0].encapsulated_key: <hex — 1088-byte ML-KEM-768 ciphertext>
93
+ recipient[0].wrapped_dek: <hex — 48 bytes: AES-256-GCM(ss, nonce=0, ad=kid).encrypt(dek)>
94
+ nonce: <hex — 12-byte GCM nonce>
95
+ created: 2026-05-23T00:00:00Z
96
+ --- BEGIN CIPHERTEXT ---
97
+ <binary — AES-256-GCM ciphertext + 16-byte auth tag>
98
+ ```
99
+
100
+ The entire header (everything before `--- BEGIN CIPHERTEXT ---`) is used as **additional authenticated data** in the GCM call. Tampering with any header field — including the nonce, recipient entries, or algorithm line — causes decryption to fail with an authentication error.
101
+
102
+ ---
103
+
104
+ ## Crypto design
105
+
106
+ - **ML-KEM-768** (FIPS 203 final) — Security Category 3, ~AES-192 equivalent. Pure post-quantum; no classical fallback by design.
107
+ - **AES-256-GCM** — AEAD symmetric encryption of the file payload.
108
+ - **DEK wrapping** — A random 32-byte data encryption key (DEK) is generated per file. Each recipient's ML-KEM shared secret is used directly as a per-recipient AES-256-GCM key to wrap the DEK.
109
+ - **Header integrity** — The full canonical header is the GCM additional data, binding header + ciphertext together.
110
+
111
+ ---
112
+
113
+ ## Identity file format
114
+
115
+ ```
116
+ KXCO-VAULT-IDENTITY/1.0
117
+ algorithm: ml-kem-768
118
+ created: 2026-05-23T00:00:00Z
119
+ public: kxco1<bech32m of 1184-byte ML-KEM-768 public key>
120
+ secret: <hex of 2400-byte ML-KEM-768 secret key>
121
+ ```
122
+
123
+ The identity file is the only secret. The `public:` field can be shared freely. There is no passphrase protection in v1 (v0.2.0).
124
+
125
+ ---
126
+
127
+ ## Library usage
128
+
129
+ ```js
130
+ import {
131
+ encodePublicKey, decodePublicKey,
132
+ serializeHeader, parseEnvelope,
133
+ computeKid, generateDek, generateNonce,
134
+ wrapDek, unwrapDek, encryptPayload, decryptPayload,
135
+ KxcoVaultError,
136
+ } from 'kxco-pq-vault'
137
+ ```
138
+
139
+ ---
140
+
141
+ ## Why not hybrid X25519+ML-KEM?
142
+
143
+ This is a deliberate v1 choice. ML-KEM-768 is FIPS 203 final. Files encrypted here cannot be broken by a quantum computer. A hybrid adds implementation complexity without meaningful security gain over a finalized PQC standard. Hybrid support (defense-in-depth for non-PQ-capable recipients) is planned for v0.2.0.
144
+
145
+ ---
146
+
147
+ ## License
148
+
149
+ Apache-2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../src/cli.js'
3
+
4
+ run(process.argv.slice(2)).then(
5
+ (code) => process.exit(code ?? 0),
6
+ (err) => {
7
+ process.stderr.write(`kxco-vault: ${err.message || err}\n`)
8
+ process.exit(1)
9
+ },
10
+ )
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "kxco-pq-vault",
3
+ "version": "0.1.0",
4
+ "description": "Post-quantum file encryption CLI and library — ML-KEM-768 + AES-256-GCM",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./src/index.js"
9
+ },
10
+ "bin": {
11
+ "kxco-vault": "./bin/kxco-vault.js"
12
+ },
13
+ "files": [
14
+ "bin/",
15
+ "src/"
16
+ ],
17
+ "dependencies": {
18
+ "@scure/base": "^1.2.4",
19
+ "kxco-post-quantum": "^1.1.2"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/*.test.js",
23
+ "lint": "node --input-type=module --eval \"import('./src/cli.js')\" && echo lint ok"
24
+ },
25
+ "engines": {
26
+ "node": ">=20.19"
27
+ },
28
+ "keywords": [
29
+ "post-quantum",
30
+ "encryption",
31
+ "ml-kem",
32
+ "kyber",
33
+ "cli",
34
+ "kxco",
35
+ "pqc",
36
+ "aes-gcm"
37
+ ],
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/JackKXCO/kxco-pq-vault"
41
+ },
42
+ "author": "KXCO <dev@kxco.ai>"
43
+ }
package/src/bech32.js ADDED
@@ -0,0 +1,28 @@
1
+ import { bech32m } from '@scure/base'
2
+ import { KxcoVaultError } from './errors.js'
3
+
4
+ const HRP = 'kxco'
5
+ const PUBKEY_BYTES = 1184 // ML-KEM-768 public key
6
+ const LIMIT = false // disable default 90-char cap
7
+
8
+ export function encodePublicKey(pubkeyBytes) {
9
+ const words = bech32m.toWords(pubkeyBytes)
10
+ return bech32m.encode(HRP, words, LIMIT)
11
+ }
12
+
13
+ export function decodePublicKey(str) {
14
+ let decoded
15
+ try {
16
+ decoded = bech32m.decode(str, LIMIT)
17
+ } catch (e) {
18
+ throw new KxcoVaultError(`invalid recipient string: ${e.message}`)
19
+ }
20
+ if (decoded.prefix !== HRP) {
21
+ throw new KxcoVaultError(`invalid recipient prefix: expected "${HRP}", got "${decoded.prefix}"`)
22
+ }
23
+ const bytes = Buffer.from(bech32m.fromWords(decoded.words))
24
+ if (bytes.length !== PUBKEY_BYTES) {
25
+ throw new KxcoVaultError(`invalid recipient: expected ${PUBKEY_BYTES} bytes, got ${bytes.length}`)
26
+ }
27
+ return bytes
28
+ }
package/src/cli.js ADDED
@@ -0,0 +1,59 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { join, dirname } from 'node:path'
4
+
5
+ const USAGE = `
6
+ kxco-vault — post-quantum file encryption (ML-KEM-768 + AES-256-GCM)
7
+
8
+ commands:
9
+ keygen generate an ML-KEM-768 identity keypair
10
+ encrypt encrypt a file for one or more recipients
11
+ decrypt decrypt a file with your identity
12
+ recipient extract the public recipient string from an identity file
13
+ inspect show envelope header info
14
+
15
+ run 'kxco-vault <command> --help' for command-specific usage
16
+ `.trim()
17
+
18
+ export async function run(argv) {
19
+ const [cmd, ...args] = argv
20
+
21
+ if (!cmd || cmd === '--help' || cmd === '-h') {
22
+ process.stdout.write(USAGE + '\n')
23
+ return 0
24
+ }
25
+
26
+ if (cmd === '--version' || cmd === '-v') {
27
+ const pkg = JSON.parse(
28
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf-8'),
29
+ )
30
+ process.stdout.write(`${pkg.name} ${pkg.version}\n`)
31
+ return 0
32
+ }
33
+
34
+ switch (cmd) {
35
+ case 'keygen': {
36
+ const { keygen } = await import('./commands/keygen.js')
37
+ return keygen(args)
38
+ }
39
+ case 'encrypt': {
40
+ const { encrypt } = await import('./commands/encrypt.js')
41
+ return encrypt(args)
42
+ }
43
+ case 'decrypt': {
44
+ const { decrypt } = await import('./commands/decrypt.js')
45
+ return decrypt(args)
46
+ }
47
+ case 'recipient': {
48
+ const { recipient } = await import('./commands/recipient.js')
49
+ return recipient(args)
50
+ }
51
+ case 'inspect': {
52
+ const { inspect } = await import('./commands/inspect.js')
53
+ return inspect(args)
54
+ }
55
+ default:
56
+ process.stderr.write(`kxco-vault: unknown command "${cmd}"\n${USAGE}\n`)
57
+ return 2
58
+ }
59
+ }
@@ -0,0 +1,75 @@
1
+ import { writeFileSync } from 'node:fs'
2
+ import { mlKem } from 'kxco-post-quantum'
3
+ import { parseEnvelope } from '../envelope.js'
4
+ import { computeKid, unwrapDek, decryptPayload } from '../crypto.js'
5
+ import { readFileBytes, readIdentity } from '../util.js'
6
+ import { KxcoVaultError } from '../errors.js'
7
+
8
+ function parseArgs(args) {
9
+ let inputFile = null
10
+ let identityPath = null
11
+ let outPath = null
12
+ let i = 0
13
+ while (i < args.length) {
14
+ const arg = args[i]
15
+ if (arg === '--identity') {
16
+ if (!args[i + 1]) throw new KxcoVaultError('--identity requires a value')
17
+ identityPath = args[i + 1]
18
+ i += 2
19
+ } else if (arg.startsWith('--identity=')) {
20
+ identityPath = arg.slice('--identity='.length)
21
+ i++
22
+ } else if (arg === '--out') {
23
+ if (!args[i + 1]) throw new KxcoVaultError('--out requires a value')
24
+ outPath = args[i + 1]
25
+ i += 2
26
+ } else if (arg.startsWith('--out=')) {
27
+ outPath = arg.slice('--out='.length)
28
+ i++
29
+ } else if (!arg.startsWith('--')) {
30
+ inputFile = arg
31
+ i++
32
+ } else {
33
+ throw new KxcoVaultError(`unknown flag: ${arg}`)
34
+ }
35
+ }
36
+ return { inputFile, identityPath, outPath }
37
+ }
38
+
39
+ export async function decrypt(args) {
40
+ if (args.includes('--help') || args.includes('-h')) {
41
+ process.stdout.write(
42
+ `usage: kxco-vault decrypt <file.kxco> --identity <keypair.kxco> [--out <file>]\n`,
43
+ )
44
+ return 0
45
+ }
46
+
47
+ const { inputFile, identityPath, outPath } = parseArgs(args)
48
+
49
+ if (!inputFile) throw new KxcoVaultError('decrypt: input file required')
50
+ if (!identityPath) throw new KxcoVaultError('decrypt: --identity is required')
51
+
52
+ const { publicKey, secretKey } = readIdentity(identityPath)
53
+ const myKid = computeKid(publicKey)
54
+
55
+ const buf = readFileBytes(inputFile)
56
+ const { header, canonicalHeader, ciphertext } = parseEnvelope(buf)
57
+
58
+ const recipientBlock = header.recipients.find(r => r.kid === myKid)
59
+ if (!recipientBlock) throw new KxcoVaultError('recipient kid not in envelope')
60
+
61
+ const mlKemCt = Buffer.from(recipientBlock.encapsulatedKey, 'hex')
62
+ const ss = Buffer.from(mlKem.decapsulate(mlKemCt, secretKey))
63
+ const wrappedDek = Buffer.from(recipientBlock.wrappedDek, 'hex')
64
+ const dek = unwrapDek(ss, myKid, wrappedDek)
65
+
66
+ const nonce = Buffer.from(header.nonce, 'hex')
67
+ const plaintext = decryptPayload(dek, nonce, canonicalHeader, ciphertext)
68
+
69
+ const defaultOut = inputFile.endsWith('.kxco') ? inputFile.slice(0, -5) : `${inputFile}.dec`
70
+ const outFile = outPath || defaultOut
71
+
72
+ writeFileSync(outFile, plaintext)
73
+ process.stdout.write(`decrypted: ${outFile}\n`)
74
+ return 0
75
+ }
@@ -0,0 +1,88 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs'
2
+ import { mlKem } from 'kxco-post-quantum'
3
+ import { serializeHeader } from '../envelope.js'
4
+ import { generateDek, generateNonce, computeKid, wrapDek, encryptPayload } from '../crypto.js'
5
+ import { resolveRecipient } from '../util.js'
6
+ import { KxcoVaultError } from '../errors.js'
7
+
8
+ const SEPARATOR = Buffer.from('--- BEGIN CIPHERTEXT ---\n', 'utf-8')
9
+
10
+ function parseArgs(args) {
11
+ const recipients = []
12
+ let inputFile = null
13
+ let outPath = null
14
+ let i = 0
15
+ while (i < args.length) {
16
+ const arg = args[i]
17
+ if (arg === '--recipient') {
18
+ if (!args[i + 1]) throw new KxcoVaultError('--recipient requires a value')
19
+ recipients.push(args[i + 1])
20
+ i += 2
21
+ } else if (arg.startsWith('--recipient=')) {
22
+ recipients.push(arg.slice('--recipient='.length))
23
+ i++
24
+ } else if (arg === '--out') {
25
+ if (!args[i + 1]) throw new KxcoVaultError('--out requires a value')
26
+ outPath = args[i + 1]
27
+ i += 2
28
+ } else if (arg.startsWith('--out=')) {
29
+ outPath = arg.slice('--out='.length)
30
+ i++
31
+ } else if (!arg.startsWith('--')) {
32
+ inputFile = arg
33
+ i++
34
+ } else {
35
+ throw new KxcoVaultError(`unknown flag: ${arg}`)
36
+ }
37
+ }
38
+ return { inputFile, recipients, outPath }
39
+ }
40
+
41
+ export async function encrypt(args) {
42
+ if (args.includes('--help') || args.includes('-h')) {
43
+ process.stdout.write(
44
+ `usage: kxco-vault encrypt <file> --recipient <kxco1...|@keyfile> [--recipient ...] [--out <file.kxco>]\n`,
45
+ )
46
+ return 0
47
+ }
48
+
49
+ const { inputFile, recipients: recipientStrs, outPath } = parseArgs(args)
50
+
51
+ if (!inputFile) throw new KxcoVaultError('encrypt: input file required')
52
+ if (recipientStrs.length === 0) throw new KxcoVaultError('encrypt: at least one --recipient required')
53
+
54
+ const outFile = outPath || `${inputFile}.kxco`
55
+
56
+ let plaintext
57
+ try {
58
+ plaintext = readFileSync(inputFile)
59
+ } catch (e) {
60
+ throw new KxcoVaultError(`cannot read "${inputFile}": ${e.message}`)
61
+ }
62
+
63
+ const dek = generateDek()
64
+ const nonce = generateNonce()
65
+ const created = new Date().toISOString().replace(/\.\d+Z$/, 'Z')
66
+
67
+ const recipientBlocks = recipientStrs.map((str) => {
68
+ const pubkeyBytes = resolveRecipient(str)
69
+ const kid = computeKid(pubkeyBytes)
70
+ const { ciphertext: mlKemCt, sharedSecret: ss } = mlKem.encapsulate(pubkeyBytes)
71
+ const wrappedDek = wrapDek(Buffer.from(ss), kid, dek)
72
+ return {
73
+ kid,
74
+ encapsulatedKey: Buffer.from(mlKemCt).toString('hex'),
75
+ wrappedDek: wrappedDek.toString('hex'),
76
+ }
77
+ })
78
+
79
+ const headerText = serializeHeader({ recipients: recipientBlocks, nonce: nonce.toString('hex'), created })
80
+ const canonicalHeader = Buffer.from(headerText, 'utf-8')
81
+ const payload = encryptPayload(dek, nonce, canonicalHeader, plaintext)
82
+
83
+ writeFileSync(outFile, Buffer.concat([canonicalHeader, SEPARATOR, payload]))
84
+
85
+ process.stdout.write(`encrypted: ${outFile}\n`)
86
+ process.stdout.write(`recipients: ${recipientBlocks.length}\n`)
87
+ return 0
88
+ }
@@ -0,0 +1,42 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { parseHeaderText } from '../envelope.js'
3
+ import { KxcoVaultError } from '../errors.js'
4
+
5
+ const SEPARATOR = '--- BEGIN CIPHERTEXT ---\n'
6
+
7
+ export async function inspect(args) {
8
+ if (args.includes('--help') || args.includes('-h')) {
9
+ process.stdout.write(`usage: kxco-vault inspect <file.kxco>\n`)
10
+ return 0
11
+ }
12
+
13
+ const inputFile = args.find(a => !a.startsWith('--'))
14
+ if (!inputFile) throw new KxcoVaultError('inspect: input file required')
15
+
16
+ let buf
17
+ try {
18
+ buf = readFileSync(inputFile)
19
+ } catch (e) {
20
+ throw new KxcoVaultError(`cannot read "${inputFile}": ${e.message}`)
21
+ }
22
+
23
+ const text = buf.toString('utf-8')
24
+ const sepIdx = text.indexOf(SEPARATOR)
25
+ if (sepIdx === -1) throw new KxcoVaultError('invalid envelope: missing ciphertext separator')
26
+
27
+ const headerText = text.slice(0, sepIdx)
28
+ const ciphertextBytes = buf.length - sepIdx - Buffer.byteLength(SEPARATOR)
29
+
30
+ const header = parseHeaderText(headerText)
31
+
32
+ process.stdout.write(`version: KXCO-VAULT/1.0\n`)
33
+ process.stdout.write(`algorithm: ${header.algorithm}\n`)
34
+ process.stdout.write(`recipients: ${header.recipients.length}\n`)
35
+ for (let i = 0; i < header.recipients.length; i++) {
36
+ process.stdout.write(` [${i}] kid: ${header.recipients[i].kid}\n`)
37
+ }
38
+ process.stdout.write(`nonce: ${header.nonce}\n`)
39
+ process.stdout.write(`created: ${header.created}\n`)
40
+ process.stdout.write(`ciphertext: ${ciphertextBytes} bytes\n`)
41
+ return 0
42
+ }
@@ -0,0 +1,80 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { writeFileSync } from 'node:fs'
3
+ import { mlKem, deriveSeed } from 'kxco-post-quantum'
4
+ import { encodePublicKey } from '../bech32.js'
5
+ import { KxcoVaultError } from '../errors.js'
6
+
7
+ const FLAGS = new Set(['out', 'master', 'label'])
8
+
9
+ function parseFlags(args) {
10
+ const flags = {}
11
+ let i = 0
12
+ while (i < args.length) {
13
+ const arg = args[i]
14
+ if (!arg.startsWith('--')) throw new KxcoVaultError(`unexpected argument: ${arg}`)
15
+ let key, val
16
+ if (arg.includes('=')) {
17
+ const eq = arg.indexOf('=')
18
+ key = arg.slice(2, eq)
19
+ val = arg.slice(eq + 1)
20
+ i++
21
+ } else {
22
+ key = arg.slice(2)
23
+ if (i + 1 >= args.length || args[i + 1].startsWith('--')) {
24
+ throw new KxcoVaultError(`--${key} requires a value`)
25
+ }
26
+ val = args[i + 1]
27
+ i += 2
28
+ }
29
+ if (!FLAGS.has(key)) throw new KxcoVaultError(`unknown flag --${key}`)
30
+ flags[key] = val
31
+ }
32
+ return flags
33
+ }
34
+
35
+ export async function keygen(args) {
36
+ if (args.includes('--help') || args.includes('-h')) {
37
+ process.stdout.write(`usage: kxco-vault keygen --out <keypair.kxco> [--master <hex> --label <string>]\n`)
38
+ return 0
39
+ }
40
+
41
+ const flags = parseFlags(args)
42
+ if (!flags.out) throw new KxcoVaultError('keygen: --out is required')
43
+
44
+ let publicKey, secretKey
45
+
46
+ if (flags.master) {
47
+ // Deterministic derivation
48
+ if (!flags.label) throw new KxcoVaultError('keygen: --label is required with --master')
49
+ if (!/^[0-9a-fA-F]+$/.test(flags.master) || flags.master.length < 32) {
50
+ throw new KxcoVaultError('keygen: --master must be at least 16 hex bytes')
51
+ }
52
+ const masterBytes = Buffer.from(flags.master, 'hex')
53
+ const result = mlKem.keypairFromMaster(masterBytes, flags.label)
54
+ publicKey = result.publicKey
55
+ secretKey = result.secretKey
56
+ } else {
57
+ // Random keygen: generate 32-byte random master, derive 64-byte seed
58
+ const randomMaster = randomBytes(32)
59
+ const result = mlKem.keypairFromMaster(randomMaster, 'kxco-vault/keygen/v1')
60
+ publicKey = result.publicKey
61
+ secretKey = result.secretKey
62
+ }
63
+
64
+ const created = new Date().toISOString().replace(/\.\d+Z$/, 'Z')
65
+ const recipient = encodePublicKey(Buffer.from(publicKey))
66
+
67
+ const identity = [
68
+ 'KXCO-VAULT-IDENTITY/1.0',
69
+ 'algorithm: ml-kem-768',
70
+ `created: ${created}`,
71
+ `public: ${recipient}`,
72
+ `secret: ${Buffer.from(secretKey).toString('hex')}`,
73
+ '',
74
+ ].join('\n')
75
+
76
+ writeFileSync(flags.out, identity, 'utf-8')
77
+ process.stdout.write(`identity: ${flags.out}\n`)
78
+ process.stdout.write(`recipient: ${recipient}\n`)
79
+ return 0
80
+ }
@@ -0,0 +1,28 @@
1
+ import { readFileText } from '../util.js'
2
+ import { decodePublicKey, encodePublicKey } from '../bech32.js'
3
+ import { KxcoVaultError } from '../errors.js'
4
+
5
+ export async function recipient(args) {
6
+ if (args.includes('--help') || args.includes('-h')) {
7
+ process.stdout.write(`usage: kxco-vault recipient <keypair.kxco>\n`)
8
+ return 0
9
+ }
10
+
11
+ const keyfile = args.find(a => !a.startsWith('--'))
12
+ if (!keyfile) throw new KxcoVaultError('recipient: identity file argument required')
13
+
14
+ const content = readFileText(keyfile)
15
+ if (!content.startsWith('KXCO-VAULT-IDENTITY/')) {
16
+ throw new KxcoVaultError(`not a kxco-vault identity file: ${keyfile}`)
17
+ }
18
+
19
+ const match = content.match(/^public:\s*(kxco1\S+)/m)
20
+ if (!match) throw new KxcoVaultError(`identity file missing public key: ${keyfile}`)
21
+
22
+ // Validate bech32m round-trip
23
+ const pubkeyBytes = decodePublicKey(match[1])
24
+ const recipient = encodePublicKey(pubkeyBytes)
25
+
26
+ process.stdout.write(`${recipient}\n`)
27
+ return 0
28
+ }
package/src/crypto.js ADDED
@@ -0,0 +1,56 @@
1
+ import { randomBytes, createHash, createCipheriv, createDecipheriv } from 'node:crypto'
2
+ import { KxcoVaultError } from './errors.js'
3
+
4
+ export function generateDek() { return randomBytes(32) }
5
+ export function generateNonce() { return randomBytes(12) }
6
+
7
+ // kid = first 8 bytes of SHA-256(pubkey), as 16-char lowercase hex
8
+ export function computeKid(pubkeyBytes) {
9
+ return createHash('sha256').update(pubkeyBytes).digest().slice(0, 8).toString('hex')
10
+ }
11
+
12
+ // Wrap DEK with the ML-KEM shared secret (32 bytes = AES-256 key).
13
+ // nonce = 12 zero bytes (ss is fresh per encapsulation, reuse-safe).
14
+ // ad = raw kid bytes (8 bytes) for domain separation.
15
+ // Output: 48 bytes (32-byte ciphertext + 16-byte GCM auth tag).
16
+ export function wrapDek(ss, kid, dek) {
17
+ const cipher = createCipheriv('aes-256-gcm', ss, Buffer.alloc(12))
18
+ cipher.setAAD(Buffer.from(kid, 'hex'))
19
+ const ct = Buffer.concat([cipher.update(dek), cipher.final()])
20
+ return Buffer.concat([ct, cipher.getAuthTag()])
21
+ }
22
+
23
+ // Unwrap DEK. Throws KxcoVaultError if auth fails.
24
+ export function unwrapDek(ss, kid, wrappedDek) {
25
+ if (wrappedDek.length !== 48) throw new KxcoVaultError('authentication failed: invalid wrapped_dek length')
26
+ const decipher = createDecipheriv('aes-256-gcm', ss, Buffer.alloc(12))
27
+ decipher.setAAD(Buffer.from(kid, 'hex'))
28
+ decipher.setAuthTag(wrappedDek.slice(32))
29
+ try {
30
+ return Buffer.concat([decipher.update(wrappedDek.slice(0, 32)), decipher.final()])
31
+ } catch {
32
+ throw new KxcoVaultError('authentication failed')
33
+ }
34
+ }
35
+
36
+ // Encrypt plaintext. Returns ciphertext||tag (payload.length = plaintext.length + 16).
37
+ // ad = canonicalHeader bytes.
38
+ export function encryptPayload(dek, nonce, ad, plaintext) {
39
+ const cipher = createCipheriv('aes-256-gcm', dek, nonce)
40
+ cipher.setAAD(ad)
41
+ const ct = Buffer.concat([cipher.update(plaintext), cipher.final()])
42
+ return Buffer.concat([ct, cipher.getAuthTag()])
43
+ }
44
+
45
+ // Decrypt payload (ciphertext||tag). Throws KxcoVaultError if auth fails.
46
+ export function decryptPayload(dek, nonce, ad, payload) {
47
+ if (payload.length < 16) throw new KxcoVaultError('authentication failed: ciphertext too short')
48
+ const decipher = createDecipheriv('aes-256-gcm', dek, nonce)
49
+ decipher.setAAD(ad)
50
+ decipher.setAuthTag(payload.slice(-16))
51
+ try {
52
+ return Buffer.concat([decipher.update(payload.slice(0, -16)), decipher.final()])
53
+ } catch {
54
+ throw new KxcoVaultError('authentication failed')
55
+ }
56
+ }
@@ -0,0 +1,73 @@
1
+ import { KxcoVaultError } from './errors.js'
2
+
3
+ const SEPARATOR = '--- BEGIN CIPHERTEXT ---\n'
4
+ const VERSION = 'KXCO-VAULT/1.0'
5
+ const ALGORITHM = 'ml-kem-768+aes-256-gcm'
6
+
7
+ // Serialize a header object to a UTF-8 string (no separator line).
8
+ // recipients: [{ kid, encapsulatedKey, wrappedDek }] (all hex strings)
9
+ // nonce: hex string (24 chars = 12 bytes)
10
+ // created: ISO 8601 string
11
+ export function serializeHeader({ recipients, nonce, created }) {
12
+ const lines = [
13
+ VERSION,
14
+ `algorithm: ${ALGORITHM}`,
15
+ `recipients: ${recipients.length}`,
16
+ ]
17
+ for (let i = 0; i < recipients.length; i++) {
18
+ const r = recipients[i]
19
+ lines.push(`recipient[${i}].kid: ${r.kid}`)
20
+ lines.push(`recipient[${i}].encapsulated_key: ${r.encapsulatedKey}`)
21
+ lines.push(`recipient[${i}].wrapped_dek: ${r.wrappedDek}`)
22
+ }
23
+ lines.push(`nonce: ${nonce}`)
24
+ lines.push(`created: ${created}`)
25
+ return lines.join('\n') + '\n'
26
+ }
27
+
28
+ // Parse a full envelope Buffer into { header, canonicalHeader, ciphertext }.
29
+ // canonicalHeader is the raw bytes used as GCM AAD.
30
+ export function parseEnvelope(buf) {
31
+ const sepBytes = Buffer.from(SEPARATOR, 'utf-8')
32
+ const sepIdx = buf.indexOf(sepBytes)
33
+ if (sepIdx === -1) throw new KxcoVaultError('invalid envelope: missing ciphertext separator')
34
+
35
+ const canonicalHeader = buf.slice(0, sepIdx)
36
+ const ciphertext = buf.slice(sepIdx + sepBytes.length)
37
+
38
+ const header = parseHeaderText(canonicalHeader.toString('utf-8'))
39
+ return { header, canonicalHeader, ciphertext }
40
+ }
41
+
42
+ // Parse just the text portion of a header (for inspect).
43
+ export function parseHeaderText(text) {
44
+ const lines = text.split('\n').map(l => l.trim()).filter(l => l.length > 0)
45
+ if (lines[0] !== VERSION) throw new KxcoVaultError(`unsupported vault version: ${lines[0]}`)
46
+
47
+ const get = (key) => {
48
+ const line = lines.find(l => l.startsWith(`${key}: `))
49
+ if (!line) throw new KxcoVaultError(`missing header field: ${key}`)
50
+ return line.slice(key.length + 2)
51
+ }
52
+
53
+ const algorithm = get('algorithm')
54
+ if (algorithm !== ALGORITHM) throw new KxcoVaultError(`unsupported algorithm: ${algorithm}`)
55
+
56
+ const nRecipients = parseInt(get('recipients'), 10)
57
+ if (!Number.isFinite(nRecipients) || nRecipients < 1) {
58
+ throw new KxcoVaultError(`invalid recipients count: ${get('recipients')}`)
59
+ }
60
+
61
+ const recipients = []
62
+ for (let i = 0; i < nRecipients; i++) {
63
+ const kid = get(`recipient[${i}].kid`)
64
+ const encapsulatedKey = get(`recipient[${i}].encapsulated_key`)
65
+ const wrappedDek = get(`recipient[${i}].wrapped_dek`)
66
+ recipients.push({ kid, encapsulatedKey, wrappedDek })
67
+ }
68
+
69
+ const nonce = get('nonce')
70
+ const created = get('created')
71
+
72
+ return { algorithm, recipients, nonce, created }
73
+ }
package/src/errors.js ADDED
@@ -0,0 +1,6 @@
1
+ export class KxcoVaultError extends Error {
2
+ constructor(message) {
3
+ super(message)
4
+ this.name = 'KxcoVaultError'
5
+ }
6
+ }
package/src/index.js ADDED
@@ -0,0 +1,14 @@
1
+ // Library entry point — re-exports all public primitives.
2
+ export { encodePublicKey, decodePublicKey } from './bech32.js'
3
+ export { serializeHeader, parseEnvelope, parseHeaderText } from './envelope.js'
4
+ export {
5
+ generateDek,
6
+ generateNonce,
7
+ computeKid,
8
+ wrapDek,
9
+ unwrapDek,
10
+ encryptPayload,
11
+ decryptPayload,
12
+ } from './crypto.js'
13
+ export { resolveRecipient, readIdentity } from './util.js'
14
+ export { KxcoVaultError } from './errors.js'
package/src/util.js ADDED
@@ -0,0 +1,47 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { decodePublicKey } from './bech32.js'
3
+ import { KxcoVaultError } from './errors.js'
4
+
5
+ export function readFileBytes(path) {
6
+ try {
7
+ return readFileSync(path)
8
+ } catch (e) {
9
+ throw new KxcoVaultError(`cannot read file "${path}": ${e.message}`)
10
+ }
11
+ }
12
+
13
+ export function readFileText(path) {
14
+ return readFileBytes(path).toString('utf-8')
15
+ }
16
+
17
+ // Resolve a --recipient value to raw pubkey bytes.
18
+ // Accepts: "kxco1..." bech32m string, or "@/path/to/file"
19
+ export function resolveRecipient(str) {
20
+ if (str.startsWith('@')) {
21
+ const content = readFileText(str.slice(1)).trim()
22
+ if (content.startsWith('KXCO-VAULT-IDENTITY/')) {
23
+ const match = content.match(/^public:\s*(kxco1\S+)/m)
24
+ if (!match) throw new KxcoVaultError('identity file missing public key')
25
+ return decodePublicKey(match[1])
26
+ }
27
+ return decodePublicKey(content)
28
+ }
29
+ return decodePublicKey(str)
30
+ }
31
+
32
+ // Parse an identity file (keypair.kxco) and return { publicKey, secretKey }
33
+ export function readIdentity(path) {
34
+ const content = readFileText(path)
35
+ if (!content.startsWith('KXCO-VAULT-IDENTITY/')) {
36
+ throw new KxcoVaultError(`not a kxco-vault identity file: ${path}`)
37
+ }
38
+ const pubMatch = content.match(/^public:\s*(kxco1\S+)/m)
39
+ const secMatch = content.match(/^secret:\s*([0-9a-fA-F]+)/m)
40
+ if (!pubMatch || !secMatch) throw new KxcoVaultError(`malformed identity file: ${path}`)
41
+ const publicKey = decodePublicKey(pubMatch[1])
42
+ const secretKey = Buffer.from(secMatch[1], 'hex')
43
+ if (secretKey.length !== 2400) {
44
+ throw new KxcoVaultError(`invalid secret key length in ${path}: expected 2400 bytes, got ${secretKey.length}`)
45
+ }
46
+ return { publicKey, secretKey }
47
+ }