@trebired/crypto 0.0.0-stage → 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.
Files changed (118) hide show
  1. package/.trebired/logger/config.ts +4 -0
  2. package/CHANGELOG.md +15 -0
  3. package/LICENSE +21 -0
  4. package/README.md +148 -2
  5. package/SPEC.md +175 -0
  6. package/dist/basics.d.ts +7 -0
  7. package/dist/basics.d.ts.map +1 -0
  8. package/dist/basics.js +17 -0
  9. package/dist/basics.js.map +1 -0
  10. package/dist/cli.d.ts +3 -0
  11. package/dist/cli.d.ts.map +1 -0
  12. package/dist/cli.js +135 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/errors.d.ts +9 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +12 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/files/files.d.ts +56 -0
  19. package/dist/files/files.d.ts.map +1 -0
  20. package/dist/files/files.js +117 -0
  21. package/dist/files/files.js.map +1 -0
  22. package/dist/files/format.d.ts +43 -0
  23. package/dist/files/format.d.ts.map +1 -0
  24. package/dist/files/format.js +82 -0
  25. package/dist/files/format.js.map +1 -0
  26. package/dist/files/slots.d.ts +20 -0
  27. package/dist/files/slots.d.ts.map +1 -0
  28. package/dist/files/slots.js +125 -0
  29. package/dist/files/slots.js.map +1 -0
  30. package/dist/files/streams.d.ts +18 -0
  31. package/dist/files/streams.d.ts.map +1 -0
  32. package/dist/files/streams.js +140 -0
  33. package/dist/files/streams.js.map +1 -0
  34. package/dist/index.d.ts +18 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +11 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/keys/env.d.ts +17 -0
  39. package/dist/keys/env.d.ts.map +1 -0
  40. package/dist/keys/env.js +99 -0
  41. package/dist/keys/env.js.map +1 -0
  42. package/dist/keys/ring.d.ts +13 -0
  43. package/dist/keys/ring.d.ts.map +1 -0
  44. package/dist/keys/ring.js +66 -0
  45. package/dist/keys/ring.js.map +1 -0
  46. package/dist/logging.d.ts +3 -0
  47. package/dist/logging.d.ts.map +1 -0
  48. package/dist/logging.js +7 -0
  49. package/dist/logging.js.map +1 -0
  50. package/dist/messages.d.ts +9 -0
  51. package/dist/messages.d.ts.map +1 -0
  52. package/dist/messages.js +29 -0
  53. package/dist/messages.js.map +1 -0
  54. package/dist/package-metadata.d.ts +3 -0
  55. package/dist/package-metadata.d.ts.map +1 -0
  56. package/dist/package-metadata.js +5 -0
  57. package/dist/package-metadata.js.map +1 -0
  58. package/dist/sealed/sealer.d.ts +17 -0
  59. package/dist/sealed/sealer.d.ts.map +1 -0
  60. package/dist/sealed/sealer.js +73 -0
  61. package/dist/sealed/sealer.js.map +1 -0
  62. package/dist/src/basics.d.ts +7 -0
  63. package/dist/src/basics.d.ts.map +1 -0
  64. package/dist/src/basics.js +17 -0
  65. package/dist/src/basics.js.map +1 -0
  66. package/dist/src/cli.d.ts +3 -0
  67. package/dist/src/cli.d.ts.map +1 -0
  68. package/dist/src/cli.js +135 -0
  69. package/dist/src/cli.js.map +1 -0
  70. package/dist/src/errors.d.ts +9 -0
  71. package/dist/src/errors.d.ts.map +1 -0
  72. package/dist/src/errors.js +12 -0
  73. package/dist/src/errors.js.map +1 -0
  74. package/dist/src/files/files.d.ts +56 -0
  75. package/dist/src/files/files.d.ts.map +1 -0
  76. package/dist/src/files/files.js +117 -0
  77. package/dist/src/files/files.js.map +1 -0
  78. package/dist/src/files/format.d.ts +43 -0
  79. package/dist/src/files/format.d.ts.map +1 -0
  80. package/dist/src/files/format.js +82 -0
  81. package/dist/src/files/format.js.map +1 -0
  82. package/dist/src/files/slots.d.ts +20 -0
  83. package/dist/src/files/slots.d.ts.map +1 -0
  84. package/dist/src/files/slots.js +125 -0
  85. package/dist/src/files/slots.js.map +1 -0
  86. package/dist/src/files/streams.d.ts +18 -0
  87. package/dist/src/files/streams.d.ts.map +1 -0
  88. package/dist/src/files/streams.js +140 -0
  89. package/dist/src/files/streams.js.map +1 -0
  90. package/dist/src/index.d.ts +18 -0
  91. package/dist/src/index.d.ts.map +1 -0
  92. package/dist/src/index.js +11 -0
  93. package/dist/src/index.js.map +1 -0
  94. package/dist/src/keys/env.d.ts +17 -0
  95. package/dist/src/keys/env.d.ts.map +1 -0
  96. package/dist/src/keys/env.js +99 -0
  97. package/dist/src/keys/env.js.map +1 -0
  98. package/dist/src/keys/ring.d.ts +13 -0
  99. package/dist/src/keys/ring.d.ts.map +1 -0
  100. package/dist/src/keys/ring.js +66 -0
  101. package/dist/src/keys/ring.js.map +1 -0
  102. package/dist/src/logging.d.ts +3 -0
  103. package/dist/src/logging.d.ts.map +1 -0
  104. package/dist/src/logging.js +7 -0
  105. package/dist/src/logging.js.map +1 -0
  106. package/dist/src/messages.d.ts +9 -0
  107. package/dist/src/messages.d.ts.map +1 -0
  108. package/dist/src/messages.js +29 -0
  109. package/dist/src/messages.js.map +1 -0
  110. package/dist/src/package-metadata.d.ts +3 -0
  111. package/dist/src/package-metadata.d.ts.map +1 -0
  112. package/dist/src/package-metadata.js +5 -0
  113. package/dist/src/package-metadata.js.map +1 -0
  114. package/dist/src/sealed/sealer.d.ts +17 -0
  115. package/dist/src/sealed/sealer.d.ts.map +1 -0
  116. package/dist/src/sealed/sealer.js +73 -0
  117. package/dist/src/sealed/sealer.js.map +1 -0
  118. package/package.json +82 -4
@@ -0,0 +1,4 @@
1
+ export default {
2
+ forVersion: "3.0.0",
3
+ prefix: "trebired.crypto",
4
+ };
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@trebired/crypto` will be documented here.
4
+
5
+ This project follows semantic versioning once published.
6
+
7
+ ## 0.1.0
8
+
9
+ - Added the key ring: `CRYPTO_KEYS` claimed through `@trebired/env`, random key ids, per-purpose HKDF subkeys, and `ensureKeyRing`, `rotateKey`, `retireKey`, `exportKeyRing`, and `importKeyRing`.
10
+ - Added sealed values (`tbs1`): `createSealer` with `seal`, `open`, `isCurrent`, `reseal`, and `asCipher`, bound to a purpose and a record context.
11
+ - Added the `.tb.enc` file format: public header, password (Argon2id) and key-ring slots, and authenticated 64 KiB chunks, with `encryptFile`, `decryptFile`, `inspectFile`, and streaming `createEncryptStream`/`createDecryptStream`.
12
+ - Added `SPEC.md` with the byte formats and test vectors.
13
+ - Added the `trebired-crypto` CLI with `inspect`, `decrypt`, `encrypt`, and `keygen`.
14
+ - Added English and Czech messages for every error code.
15
+ - Added logging of key ring changes through `@trebired/logger-adapter`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Miroslav Machynka (Trebired)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,149 @@
1
- # Temporary Holding Version
1
+ # @trebired/crypto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Encryption standard for Trebired applications: one key ring in the env file, sealed values for secrets stored in a database, and the `.tb.enc` file format for exports, backups, and downloads of sensitive data.
4
+
5
+ The package owns the key ring (`CRYPTO_KEYS`), every cipher and key-derivation choice, the byte formats defined in [SPEC.md](SPEC.md), and the `trebired-crypto` CLI. Callers own the purpose and context names, where sealed values are stored, when keys are rotated, and the loop that re-seals their own records. The package does not own password strength rules, a user interface, archive layouts, or the meaning of the files it encrypts.
6
+
7
+ ## Install
8
+
9
+ Runtime support: Bun 1.4+.
10
+
11
+ ```sh
12
+ bun i @trebired/crypto
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```ts
18
+ import { createSealer, encryptFile, encryptedFileName, ensureKeyRing } from "@trebired/crypto";
19
+
20
+ ensureKeyRing();
21
+
22
+ const credentials = createSealer("mail-account-credentials");
23
+ const token = credentials.seal("app-password", `mail_account:${accountId}`);
24
+ const password = credentials.open(token, `mail_account:${accountId}`);
25
+
26
+ const outcome = await encryptFile({
27
+ kind: "app-data",
28
+ password: userPassword,
29
+ source: "/var/lib/app/staging/export.tar.gz",
30
+ target: `/var/lib/app/staging/${encryptedFileName("app-data")}`,
31
+ });
32
+ ```
33
+
34
+ ## Concepts
35
+
36
+ ### Key Ring
37
+
38
+ `CRYPTO_KEYS` holds every key the installation can decrypt with, as `<id>:<base64url key>` entries separated by commas. The first entry is the active key; new values always use it. `@trebired/crypto` claims `CRYPTO_KEYS` through `@trebired/env`, so the application never reads it.
39
+
40
+ Each purpose gets its own subkey through HKDF, so a sealed mail password and a sealed session secret never share a key.
41
+
42
+ ### Sealed Values
43
+
44
+ A sealed value is one string, `tbs1.<keyId>.<payload>`, that fits a text column or a JSON field. It carries its key id, so a separate key id column is not needed. The context passed to `seal` and `open` names the record the value belongs to; a value copied to another record does not open.
45
+
46
+ ### Encrypted Files
47
+
48
+ A `.tb.enc` file has a public header (kind, creation time, caller `meta`, and key slots) followed by authenticated chunks. A file opens with a password, with the installation's key ring, or with either when both slots are present. Every chunk is checked before its plaintext is written, so a damaged or truncated file never produces partial output.
49
+
50
+ The header is readable without a key. `inspectFile` uses it to show what a file holds before asking for a password. Do not put secrets in `meta`.
51
+
52
+ ## Configuration
53
+
54
+ `@trebired/crypto` has no config file. The key ring comes from `CRYPTO_KEYS` in the env file that `@trebired/env` resolves.
55
+
56
+ ### Password Cost
57
+
58
+ `encryptFile` and `createEncryptStream` accept `passwordCost: { memory, passes, parallelism }` for the Argon2id password slot. The defaults are 64 MiB, 3 passes, and 4 lanes. The values are written into the file, so raising them later does not affect files already written.
59
+
60
+ ### Chunk Size
61
+
62
+ `chunkBytes` sets the plaintext bytes per chunk, from 1 KiB to 16 MiB. The default is 64 KiB.
63
+
64
+ ## Runtime
65
+
66
+ ### Key Ring Lifecycle
67
+
68
+ - `ensureKeyRing()` at startup creates `CRYPTO_KEYS` with one key when it is missing.
69
+ - `rotateKey()` adds a new active key. Old values keep opening.
70
+ - `sealer.reseal(token, context)` moves one value to the active key. The application loops its own records.
71
+ - `retireKey(id)` removes a key once nothing uses it. The active key cannot be retired.
72
+ - `exportKeyRing()` and `importKeyRing(spec)` move keys between installations. An import adds the other installation's keys as decrypt-only keys and never changes the active key, so imported records open without re-sealing.
73
+
74
+ ### Logging
75
+
76
+ Key ring changes (created, rotated, retired, imported) are logged through `@trebired/logger-adapter` with the key ids involved. Key material, plaintext, and passwords are never logged. The CLI prints its messages the same way and writes only data (decrypted paths, `inspect` JSON, `keygen` entries) to stdout.
77
+
78
+ ### Memory
79
+
80
+ Files are streamed chunk by chunk. Memory use does not grow with file size: a 2 GB stream peaks at about 140 MB of process memory, most of it the runtime itself. Password slots use the Argon2id memory cost (64 MiB by default) once per unlock.
81
+
82
+ ### Results
83
+
84
+ `encryptFile` and `decryptFile` return `@trebired/result` results. A failure carries one of the codes below as `status_code`. `createSealer(...).open` throws a `CryptoError` with the same codes. `CRYPTO_MESSAGES` holds English and Czech messages for every code.
85
+
86
+ | Code | Meaning |
87
+ | --- | --- |
88
+ | `crypto-file-damaged` | A header or chunk failed its check, or the file is truncated |
89
+ | `crypto-file-not-encrypted` | The file is not a `.tb.enc` file |
90
+ | `crypto-file-unsupported` | A newer format version, cipher, or KDF |
91
+ | `crypto-key-missing` | No key slot or sealed value matches a key in this ring |
92
+ | `crypto-keys-invalid` | `CRYPTO_KEYS` is malformed, or a key operation was refused |
93
+ | `crypto-keys-missing` | `CRYPTO_KEYS` is empty |
94
+ | `crypto-kind-mismatch` | The file holds a different `kind` than the caller expects |
95
+ | `crypto-password-required` | The file has only password slots and no password was given |
96
+ | `crypto-password-too-short` | The password has fewer than 8 characters |
97
+ | `crypto-password-wrong` | No password slot opens with the given password |
98
+ | `crypto-token-invalid` | A sealed value is malformed, damaged, or belongs to another purpose or context |
99
+
100
+ ## Public API
101
+
102
+ ### Key Ring
103
+
104
+ `ensureKeyRing`, `rotateKey`, `retireKey`, `exportKeyRing`, `importKeyRing`, `activeKeyId`, `reloadKeyRing`, `useKeyRing`, `generateKeyEntry`, `KEYS_ENV`.
105
+
106
+ `useKeyRing(spec)` replaces the env lookup with an explicit ring, for scripts and tools; `useKeyRing(null)` returns to the env file.
107
+
108
+ ### Sealed Values
109
+
110
+ `createSealer(purpose)` returns `{ seal, open, isCurrent, reseal, asCipher, purpose }`. `asCipher(context)` returns `{ encrypt, decrypt }` for packages that take a string cipher. `isSealed(value)` tells a sealed value from any other string.
111
+
112
+ ### Encrypted Files
113
+
114
+ `encryptFile`, `decryptFile`, `inspectFile`, `isEncryptedFile`, `encryptedFileName`, `createEncryptStream`, `createDecryptStream`, `FILE_EXTENSION` (`.tb.enc`), `MEDIA_TYPE` (`application/vnd.trebired.encrypted`), `MIN_PASSWORD_LENGTH`.
115
+
116
+ `createEncryptStream` and `createDecryptStream` return Node.js `Transform` streams for piping straight into an HTTP response, an archive tool, or a file.
117
+
118
+ ### Utilities
119
+
120
+ `randomToken(bytes)`, `sha256(value)`, `hmacSha256(secret, value)`, `safeEqual(left, right)`, `CryptoError`, `isCryptoError`, `CRYPTO_MESSAGES`.
121
+
122
+ ## CLI
123
+
124
+ `trebired-crypto` opens files without the application that wrote them.
125
+
126
+ ```sh
127
+ trebired-crypto inspect export.tb.enc
128
+ trebired-crypto decrypt export.tb.enc -o export.tar.gz
129
+ trebired-crypto decrypt export.tb.enc --env /etc/app/.env
130
+ trebired-crypto encrypt export.tar.gz --kind app-data
131
+ trebired-crypto keygen
132
+ ```
133
+
134
+ - `decrypt` uses the key ring from `--env`, or from the current folder's env file, and asks for the password when no key slot opens. `--password-file <file>` reads the password from a file instead.
135
+ - `encrypt` asks for the password twice.
136
+ - `keygen` prints one new `CRYPTO_KEYS` entry.
137
+
138
+ Exit codes: `0` success, `1` the operation failed (the message names the reason), `2` wrong usage.
139
+
140
+ ## What It Does Not Do
141
+
142
+ This package does not:
143
+
144
+ - Run in the browser. It uses `node:crypto` and needs Bun 1.4 or newer for Argon2id.
145
+ - Rate passwords. It refuses passwords under 8 characters; strength meters belong to the application.
146
+ - Find or re-seal the application's records after a rotation. The application owns that loop.
147
+ - Define archive layouts, manifests, or import rules for the data inside a file.
148
+ - Hide the header. `kind`, `created`, and `meta` are readable by anyone holding the file.
149
+ - Recover a file whose password and keys are both lost.
package/SPEC.md ADDED
@@ -0,0 +1,175 @@
1
+ # Trebired Encryption Formats, Version 1
2
+
3
+ This document defines the byte formats `@trebired/crypto` writes and reads: the key ring, sealed values (`tbs1`), and encrypted files (`.tb.enc`). An implementation that follows it opens what the package writes, and the package opens what the implementation writes. `scripts/verify/vectors.mjs` builds both test vectors below by hand with `node:crypto` and opens them with the package.
4
+
5
+ Notation: `‖` is byte concatenation. `base64url` is RFC 4648 section 5 without padding. `uint32be` is a 4-byte unsigned big-endian integer. All text is UTF-8.
6
+
7
+ ## Primitives
8
+
9
+ - Cipher: AES-256-GCM, 12-byte nonce, 16-byte tag.
10
+ - Subkeys: HKDF-SHA256 (RFC 5869).
11
+ - Password keys: Argon2id (RFC 9106), 32-byte output.
12
+
13
+ ## Key Ring
14
+
15
+ The key ring is one env value:
16
+
17
+ ```txt
18
+ CRYPTO_KEYS=<id>:<key>,<id>:<key>,...
19
+ ```
20
+
21
+ - `<id>` matches `[a-z0-9_-]{1,32}`. New ids are 8 characters from the alphabet `abcdefghijklmnopqrstuvwxyz234567`, drawn at random, so rings from different installations merge without collisions.
22
+ - `<key>` is 32 bytes, base64url. Readers also accept standard base64.
23
+ - The first entry is the active key. New values are always encrypted with it. The other entries only decrypt.
24
+ - An id appears once. A ring with no entries is not a ring.
25
+
26
+ Every use derives its own subkey from a master key:
27
+
28
+ ```txt
29
+ subkey(master, purpose) = HKDF-SHA256(ikm = master, salt = "trebired/crypto v1", info = purpose, length = 32)
30
+ ```
31
+
32
+ `purpose` matches `[a-z0-9][a-z0-9._-]{0,63}`. The purpose `files` is reserved for key slots of encrypted files.
33
+
34
+ ## Sealed Values
35
+
36
+ A sealed value is one ASCII string:
37
+
38
+ ```txt
39
+ tbs1.<keyId>.<base64url(iv ‖ ciphertext ‖ tag)>
40
+ ```
41
+
42
+ - `iv` is 12 random bytes.
43
+ - The key is `subkey(master of <keyId>, purpose)`.
44
+ - The additional authenticated data is `tbs1|<keyId>|<purpose>|<context>`.
45
+ - `context` names the record the value belongs to, for example `mail_account:12`. A value moved to another record, purpose, or key id fails its tag check.
46
+
47
+ ### Test Vector
48
+
49
+ | Input | Value |
50
+ | --- | --- |
51
+ | master | 32 bytes of `0x01` (`AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE`) |
52
+ | keyId | `testkey1` |
53
+ | purpose | `example` |
54
+ | context | `row:1` |
55
+ | iv | 12 bytes of `0x02` |
56
+ | plaintext | `vector` |
57
+
58
+ ```txt
59
+ tbs1.testkey1.AgICAgICAgICAgICarK2W9n6wLIB3JR3bDeDWjdGOAk64w
60
+ ```
61
+
62
+ ## Encrypted Files
63
+
64
+ File extension `.tb.enc`, media type `application/vnd.trebired.encrypted`.
65
+
66
+ ### Layout
67
+
68
+ | Offset | Size | Field |
69
+ | --- | --- | --- |
70
+ | 0 | 8 | Magic `54 42 45 4E 43 0D 0A 1A` (`TBENC\r\n\x1a`) |
71
+ | 8 | 1 | Format version, `1` |
72
+ | 9 | 4 | Header length `n`, uint32be, from 2 to 65536 |
73
+ | 13 | n | Header, UTF-8 JSON object |
74
+ | 13 + n | rest | Chunks |
75
+
76
+ The magic catches files mangled by text-mode transfers. A reader that meets a version other than `1` stops and reports the file as unsupported.
77
+
78
+ ### Header
79
+
80
+ ```json
81
+ {
82
+ "chunk": 65536,
83
+ "cipher": "aes-256-gcm",
84
+ "created": "2026-12-05T10:00:00.000Z",
85
+ "kind": "app-data",
86
+ "meta": {},
87
+ "nonce": "<base64url, 7 bytes>",
88
+ "slots": []
89
+ }
90
+ ```
91
+
92
+ | Field | Rule |
93
+ | --- | --- |
94
+ | `chunk` | Plaintext bytes per chunk, an integer from 1024 to 16777216. Writers use 65536. |
95
+ | `cipher` | `aes-256-gcm`. Any other value is unsupported. |
96
+ | `created` | ISO 8601 time the file was written. |
97
+ | `kind` | What the file holds, matching `[a-z0-9][a-z0-9._-]{0,63}`. Readers that expect a kind refuse any other. |
98
+ | `meta` | JSON object chosen by the writer. It is readable without a key and is not secret. |
99
+ | `nonce` | The 7-byte chunk nonce prefix, random per file. |
100
+ | `slots` | One or more key slots, below. |
101
+
102
+ The header is readable without a key so that an application can show what a file is before asking for a password. It is not trusted until a chunk decrypts: every chunk authenticates the header bytes.
103
+
104
+ ### Slots
105
+
106
+ Each file has a random 32-byte file key. Every slot wraps that key:
107
+
108
+ ```txt
109
+ wrapped = base64url(iv ‖ AES-256-GCM(kek, iv, fileKey, aad = "tbenc1|slot|<index>") ‖ tag)
110
+ ```
111
+
112
+ `iv` is 12 random bytes and `<index>` is the slot's position in `slots`, from 0.
113
+
114
+ A key slot opens with the installation's key ring:
115
+
116
+ ```json
117
+ { "type": "key", "keyId": "x7k2m9qa", "wrapped": "..." }
118
+ ```
119
+
120
+ `kek = subkey(master of keyId, "files")`.
121
+
122
+ A password slot opens with a password:
123
+
124
+ ```json
125
+ {
126
+ "type": "password",
127
+ "kdf": "argon2id",
128
+ "memory": 65536,
129
+ "passes": 3,
130
+ "parallelism": 4,
131
+ "salt": "<base64url, 16 bytes>",
132
+ "wrapped": "..."
133
+ }
134
+ ```
135
+
136
+ `kek = Argon2id(password, salt, memory KiB, passes, parallelism, length 32)`. Readers accept `memory` from 8192 to 1048576, and `passes` and `parallelism` from 1 to 16, and refuse anything outside those bounds so a crafted file cannot exhaust memory. Writers use the values shown. Passwords are at least 8 characters.
137
+
138
+ A reader tries key slots whose `keyId` is in its ring first, then password slots. Unknown slot types are skipped.
139
+
140
+ ### Chunks
141
+
142
+ The body is a sequence of chunks. Chunk `i` (from 0) is:
143
+
144
+ ```txt
145
+ nonce(i) = nonce prefix ‖ uint32be(i) ‖ last
146
+ sealed(i) = AES-256-GCM(fileKey, nonce(i), plaintext chunk, aad = SHA-256(bytes 0 to 13 + n)) ‖ tag
147
+ ```
148
+
149
+ - `last` is the byte `0x01` for the final chunk and `0x00` for every other chunk.
150
+ - Every chunk except the last holds exactly `chunk` plaintext bytes. The last holds from 0 to `chunk` bytes, so an empty file is one 16-byte chunk.
151
+ - A reader decrypts and checks each chunk before it releases that chunk's plaintext.
152
+ - A file that ends without a chunk marked last is truncated. Chunks in the wrong order fail their nonce. A changed header fails every chunk.
153
+ - A file holds at most 2^32 - 1 chunks.
154
+
155
+ ### Test Vector
156
+
157
+ | Input | Value |
158
+ | --- | --- |
159
+ | key ring | `testkey1:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE` |
160
+ | file key | 32 bytes of `0x03` |
161
+ | nonce prefix | 7 bytes of `0x04` |
162
+ | slot iv | 12 bytes of `0x05` |
163
+ | plaintext | 1500 bytes of `0x61` (`a`), two chunks of 1024 and 476 bytes |
164
+
165
+ Header JSON, byte for byte:
166
+
167
+ ```json
168
+ {"chunk":1024,"cipher":"aes-256-gcm","created":"2026-12-05T00:00:00.000Z","kind":"example-data","meta":{},"nonce":"BAQEBAQEBA","slots":[{"keyId":"testkey1","type":"key","wrapped":"BQUFBQUFBQUFBQUFt7kyGk-kDd0FzHyo9P1G-ObauEdmwKSBM27lHpocyC_tnR7vIIEnPxaSTOHQ4vF8"}]}
169
+ ```
170
+
171
+ SHA-256 of the whole file: `1150b3ecd07c506362e374678942c2f4ea70a52ea3daae90d790f3dc70a38a41`.
172
+
173
+ ## Versioning
174
+
175
+ A change to any byte layout above is a new format version: `tbs2` for sealed values, version byte `2` for files. Readers keep reading version 1. New KDF parameters, new slot types, and new `meta` fields are not new versions; readers skip slot types they do not know.
@@ -0,0 +1,7 @@
1
+ type Bytes = Buffer | string;
2
+ declare function randomToken(bytes?: number): string;
3
+ declare function sha256(value: Bytes): string;
4
+ declare function hmacSha256(secret: Bytes, value: Bytes): string;
5
+ declare function safeEqual(left: Bytes, right: Bytes): boolean;
6
+ export { hmacSha256, randomToken, safeEqual, sha256 };
7
+ //# sourceMappingURL=basics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"basics.d.ts","sourceRoot":"","sources":["../../src/basics.ts"],"names":[],"mappings":"AAEA,KAAK,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;AAE7B,iBAAS,WAAW,CAAC,KAAK,SAAK,GAAG,MAAM,CAEvC;AAED,iBAAS,MAAM,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAEpC;AAED,iBAAS,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,MAAM,CAEvD;AAED,iBAAS,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO,CAIrD;AAED,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC"}
package/dist/basics.js ADDED
@@ -0,0 +1,17 @@
1
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ function randomToken(bytes = 32) {
3
+ return randomBytes(bytes).toString("base64url");
4
+ }
5
+ function sha256(value) {
6
+ return createHash("sha256").update(value).digest("hex");
7
+ }
8
+ function hmacSha256(secret, value) {
9
+ return createHmac("sha256", secret).update(value).digest("hex");
10
+ }
11
+ function safeEqual(left, right) {
12
+ const leftDigest = createHash("sha256").update(left).digest();
13
+ const rightDigest = createHash("sha256").update(right).digest();
14
+ return timingSafeEqual(leftDigest, rightDigest) && Buffer.from(left).length === Buffer.from(right).length;
15
+ }
16
+ export { hmacSha256, randomToken, safeEqual, sha256 };
17
+ //# sourceMappingURL=basics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"basics.js","sourceRoot":"","sources":["../../src/basics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAInF,SAAS,WAAW,CAAC,KAAK,GAAG,EAAE;IAC7B,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,MAAM,CAAC,KAAY;IAC1B,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,UAAU,CAAC,MAAa,EAAE,KAAY;IAC7C,OAAO,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,SAAS,CAAC,IAAW,EAAE,KAAY;IAC1C,MAAM,UAAU,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC;IAC9D,MAAM,WAAW,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,CAAC;IAChE,OAAO,eAAe,CAAC,UAAU,EAAE,WAAW,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC;AAC5G,CAAC;AAED,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env bun
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env bun
2
+ import fs from "node:fs";
3
+ import { parseEnvText, readEnvFileText } from "@trebired/env";
4
+ import { FILE_EXTENSION } from "./files/format.js";
5
+ import { decryptFile, encryptFile, inspectFile } from "./files/files.js";
6
+ import { KEYS_ENV, useKeyRing } from "./keys/env.js";
7
+ import { generateKeyEntry } from "./keys/ring.js";
8
+ import { cryptoLog } from "./logging.js";
9
+ import { CRYPTO_MESSAGES } from "./messages.js";
10
+ const USAGE = [
11
+ "Usage:",
12
+ " trebired-crypto inspect <file>",
13
+ " trebired-crypto decrypt <file> [-o <out>] [--env <env file>] [--password-file <file>]",
14
+ " trebired-crypto encrypt <file> --kind <kind> [-o <out>] [--password-file <file>]",
15
+ " trebired-crypto keygen",
16
+ "",
17
+ ].join("\n");
18
+ function parseArgs(argv) {
19
+ const flags = new Map();
20
+ const positional = [];
21
+ for (let index = 0; index < argv.length; index += 1) {
22
+ const arg = argv[index];
23
+ if (arg === "-o" || arg.startsWith("--")) {
24
+ flags.set(arg === "-o" ? "out" : arg.slice(2), argv[index + 1] || "");
25
+ index += 1;
26
+ }
27
+ else {
28
+ positional.push(arg);
29
+ }
30
+ }
31
+ return { flags, positional };
32
+ }
33
+ function write(text) {
34
+ process.stdout.write(`${text}\n`);
35
+ }
36
+ class CliStop extends Error {
37
+ constructor(exitCode) {
38
+ super("cli-stop");
39
+ this.exitCode = exitCode;
40
+ }
41
+ }
42
+ function fail(text, code = 1) {
43
+ if (text)
44
+ cryptoLog()[code === 2 ? "info" : "fail"]("cli", text);
45
+ throw new CliStop(code);
46
+ }
47
+ function promptHidden(question) {
48
+ return new Promise((resolve) => {
49
+ const input = process.stdin;
50
+ process.stderr.write(question);
51
+ let value = "";
52
+ input.setRawMode?.(true);
53
+ input.resume();
54
+ input.setEncoding("utf8");
55
+ const onData = (key) => {
56
+ if (key === "\u0003")
57
+ process.exit(130);
58
+ if (key !== "\r" && key !== "\n") {
59
+ value = key === "\u007f" ? value.slice(0, -1) : value + key;
60
+ return;
61
+ }
62
+ input.setRawMode?.(false);
63
+ input.pause();
64
+ input.off("data", onData);
65
+ process.stderr.write("\n");
66
+ resolve(value);
67
+ };
68
+ input.on("data", onData);
69
+ });
70
+ }
71
+ async function readPassword(args, confirm) {
72
+ const file = args.flags.get("password-file");
73
+ if (file)
74
+ return fs.readFileSync(file, "utf8").replace(/\r?\n$/u, "");
75
+ if (!process.stdin.isTTY)
76
+ fail("Give --password-file when stdin is not a terminal.", 2);
77
+ const password = await promptHidden("Password: ");
78
+ if (confirm && (await promptHidden("Repeat password: ")) !== password)
79
+ fail("The passwords do not match.");
80
+ return password;
81
+ }
82
+ function messageFor(code) {
83
+ return CRYPTO_MESSAGES.en[code] || String(code);
84
+ }
85
+ function commandInspect(args) {
86
+ const info = inspectFile(args.positional[1] || "");
87
+ if (!info)
88
+ fail("Not a readable encrypted file.");
89
+ write(JSON.stringify(info, null, 2));
90
+ }
91
+ async function commandDecrypt(args) {
92
+ const source = args.positional[1] || fail(USAGE, 2);
93
+ const envFile = args.flags.get("env");
94
+ if (envFile)
95
+ useKeyRing(parseEnvText(readEnvFileText(envFile, true))[KEYS_ENV] || "");
96
+ const info = inspectFile(source) || fail("Not a readable encrypted file.");
97
+ const password = info.unlock.keyAvailable || !info.unlock.password ? undefined : await readPassword(args, false);
98
+ const stripped = source.endsWith(FILE_EXTENSION) ? source.slice(0, -FILE_EXTENSION.length) : `${source}.out`;
99
+ const outcome = await decryptFile({ password, source, target: args.flags.get("out") || stripped });
100
+ if (!outcome.ok)
101
+ fail(messageFor(outcome.status_code));
102
+ write(String(outcome.data.target));
103
+ }
104
+ async function commandEncrypt(args) {
105
+ const source = args.positional[1] || fail(USAGE, 2);
106
+ const kind = args.flags.get("kind") || fail(USAGE, 2);
107
+ const password = await readPassword(args, true);
108
+ const target = args.flags.get("out") || `${source}${FILE_EXTENSION}`;
109
+ const outcome = await encryptFile({ kind, password, source, target });
110
+ if (!outcome.ok)
111
+ fail(messageFor(outcome.status_code));
112
+ write(target);
113
+ }
114
+ async function main() {
115
+ const args = parseArgs(process.argv.slice(2));
116
+ const command = args.positional[0];
117
+ if (command === "inspect")
118
+ return commandInspect(args);
119
+ if (command === "decrypt")
120
+ return commandDecrypt(args);
121
+ if (command === "encrypt")
122
+ return commandEncrypt(args);
123
+ if (command === "keygen")
124
+ return write(`${KEYS_ENV}=${generateKeyEntry()}`);
125
+ fail(USAGE, 2);
126
+ }
127
+ try {
128
+ await main();
129
+ }
130
+ catch (error) {
131
+ if (!(error instanceof CliStop))
132
+ throw error;
133
+ process.exitCode = error.exitCode;
134
+ }
135
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,gBAAgB,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EAAE,CAAC;IACf,IAAI,CAAC,CAAC,KAAK,YAAY,OAAO,CAAC;QAAE,MAAM,KAAK,CAAC;IAC7C,OAAO,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;AACpC,CAAC"}
@@ -0,0 +1,9 @@
1
+ type CryptoErrorCode = "crypto-file-damaged" | "crypto-file-not-encrypted" | "crypto-file-unsupported" | "crypto-key-missing" | "crypto-keys-invalid" | "crypto-keys-missing" | "crypto-kind-mismatch" | "crypto-password-required" | "crypto-password-too-short" | "crypto-password-wrong" | "crypto-token-invalid";
2
+ declare class CryptoError extends Error {
3
+ readonly code: CryptoErrorCode;
4
+ constructor(code: CryptoErrorCode, detail?: string);
5
+ }
6
+ declare function isCryptoError(error: unknown): error is CryptoError;
7
+ export { CryptoError, isCryptoError };
8
+ export type { CryptoErrorCode };
9
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GACnB,qBAAqB,GACrB,2BAA2B,GAC3B,yBAAyB,GACzB,oBAAoB,GACpB,qBAAqB,GACrB,qBAAqB,GACrB,sBAAsB,GACtB,0BAA0B,GAC1B,2BAA2B,GAC3B,uBAAuB,GACvB,sBAAsB,CAAC;AAExB,cAAM,WAAY,SAAQ,KAAK;IAC7B,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;gBAEnB,IAAI,EAAE,eAAe,EAAE,MAAM,SAAK;CAK/C;AAED,iBAAS,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAE3D;AAED,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,CAAC;AACtC,YAAY,EAAE,eAAe,EAAE,CAAC"}
package/dist/errors.js ADDED
@@ -0,0 +1,12 @@
1
+ class CryptoError extends Error {
2
+ constructor(code, detail = "") {
3
+ super(detail ? `${code}: ${detail}` : code);
4
+ this.name = "CryptoError";
5
+ this.code = code;
6
+ }
7
+ }
8
+ function isCryptoError(error) {
9
+ return error instanceof CryptoError;
10
+ }
11
+ export { CryptoError, isCryptoError };
12
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAaA,MAAM,WAAY,SAAQ,KAAK;IAG7B,YAAY,IAAqB,EAAE,MAAM,GAAG,EAAE;QAC5C,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QAC5C,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,KAAK,YAAY,WAAW,CAAC;AACtC,CAAC;AAED,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1,56 @@
1
+ import * as result from "@trebired/result";
2
+ import { type DecryptOptions, type EncryptOptions } from "./streams.js";
3
+ type FileInfo = {
4
+ created: string;
5
+ kind: string;
6
+ meta: Record<string, unknown>;
7
+ unlock: {
8
+ keyAvailable: boolean;
9
+ keyIds: string[];
10
+ password: boolean;
11
+ };
12
+ };
13
+ type FilePaths = {
14
+ source: string;
15
+ target: string;
16
+ };
17
+ declare function encryptFile(options: EncryptOptions & FilePaths): Promise<result.ResultLike<{
18
+ code: import("../errors.js").CryptoErrorCode;
19
+ }, unknown, {
20
+ data: {
21
+ code: import("../errors.js").CryptoErrorCode;
22
+ };
23
+ }> | result.ResultLike<{
24
+ target: string;
25
+ }, unknown, {
26
+ message: false;
27
+ data: {
28
+ target: string;
29
+ };
30
+ }>>;
31
+ declare function decryptFile(options: DecryptOptions & FilePaths): Promise<result.ResultLike<{
32
+ code: import("../errors.js").CryptoErrorCode;
33
+ }, unknown, {
34
+ data: {
35
+ code: import("../errors.js").CryptoErrorCode;
36
+ };
37
+ }> | result.ResultLike<{
38
+ created: string;
39
+ kind: string;
40
+ meta: Record<string, unknown>;
41
+ target: string;
42
+ }, unknown, {
43
+ message: false;
44
+ data: {
45
+ created: string;
46
+ kind: string;
47
+ meta: Record<string, unknown>;
48
+ target: string;
49
+ };
50
+ }>>;
51
+ declare function inspectFile(filePath: string): FileInfo | null;
52
+ declare function isEncryptedFile(filePath: string): boolean;
53
+ declare function encryptedFileName(kind: string, date?: Date): string;
54
+ export { decryptFile, encryptedFileName, encryptFile, inspectFile, isEncryptedFile };
55
+ export type { FileInfo, FilePaths };
56
+ //# sourceMappingURL=files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../../src/files/files.ts"],"names":[],"mappings":"AAEA,OAAO,KAAI,MAAM,MAAM,kBAAkB,CAAC;AAI1C,OAAO,EAA4C,KAAK,cAAc,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAElH,KAAK,QAAQ,GAAG;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,MAAM,EAAE;QAAE,YAAY,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAA;KAAE,CAAC;CACxE,CAAC;AAEF,KAAK,SAAS,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAsBpD,iBAAe,WAAW,CAAC,OAAO,EAAE,cAAc,GAAC,SAAS;;;;;;;;;;;;;IAO3D;AAED,iBAAe,WAAW,CAAC,OAAO,EAAE,cAAc,GAAC,SAAS;;;;;;;;;;;;;;;;;;;IAmB3D;AAmBD,iBAAS,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAoBtD;AAED,iBAAS,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAYlD;AAED,iBAAS,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,OAAa,GAAG,MAAM,CAElE;AAED,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,CAAC;AACrF,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC"}