@tangentfeed/crypto 0.2.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sreeraj T A
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 ADDED
@@ -0,0 +1,7 @@
1
+ # @tangentfeed/crypto
2
+
3
+ End-to-end encryption for tangentfeed: XChaCha20-Poly1305 with HKDF key derivation, and scrypt for passphrases.
4
+
5
+ Cell values are encrypted before they enter the operation log, so storage, transports, and relays only ever hold ciphertext.
6
+
7
+ Part of [tangentfeed](https://github.com/sreerajta/tangentfeed). MIT licensed.
@@ -0,0 +1,39 @@
1
+ import { Cipher, Json } from '@tangentfeed/core';
2
+ export { DeviceKey, SIGNING_DOMAIN, canonicalJson, deviceIdFromPublicKey, generateDeviceKey, signPayload, verifyPayload } from '@tangentfeed/core';
3
+
4
+ /**
5
+ * SpaceCipher — PROTOCOL.md §7 reference implementation.
6
+ *
7
+ * Scheme:
8
+ * key = HKDF-SHA256(ikm = space secret, salt = "", info = "tangentfeed/v1/cells", len = 32)
9
+ * nonce = 24 random bytes, fresh per encryption
10
+ * AAD = op id (UTF-8)
11
+ * value = "e1:" + base64( nonce || XChaCha20-Poly1305(plaintext) )
12
+ * plaintext = canonical JSON of the cell value (§8.1)
13
+ *
14
+ * Why AAD = op id: a ciphertext lifted from one op and pasted into another
15
+ * fails authentication instead of silently relocating data between cells.
16
+ * Why random nonces: 192-bit nonces make collisions negligible without any
17
+ * counter state, which matters for a system where devices write offline and
18
+ * can be restored from backups.
19
+ *
20
+ * Passphrase support uses scrypt (interactive parameters) so a human-memorable
21
+ * secret is not directly usable as key material.
22
+ */
23
+
24
+ declare class SpaceCipher implements Cipher {
25
+ private readonly key;
26
+ /** Construct from raw 32-byte key material (the "space secret"). */
27
+ constructor(secret: Uint8Array);
28
+ /**
29
+ * Derive a cipher from a human passphrase. The salt must be identical on
30
+ * every device in the space; the space id is a good, non-secret choice.
31
+ */
32
+ static fromPassphrase(passphrase: string, salt: string): Promise<SpaceCipher>;
33
+ /** Generate a fresh random space secret (to be shared out of band, e.g. by QR). */
34
+ static generateSecret(): Uint8Array;
35
+ encrypt(value: Json, opId: string): string;
36
+ decrypt(value: Json, opId: string): Json;
37
+ }
38
+
39
+ export { SpaceCipher };
package/dist/index.js ADDED
@@ -0,0 +1,108 @@
1
+ // src/index.ts
2
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
3
+ import { hkdf } from "@noble/hashes/hkdf.js";
4
+ import { sha256 } from "@noble/hashes/sha2.js";
5
+ import { scrypt } from "@noble/hashes/scrypt.js";
6
+ import {
7
+ CIPHER_PREFIX,
8
+ DecryptError,
9
+ canonicalJson,
10
+ isEncryptedValue
11
+ } from "@tangentfeed/core";
12
+ import {
13
+ SIGNING_DOMAIN,
14
+ canonicalJson as canonicalJson2,
15
+ deviceIdFromPublicKey,
16
+ generateDeviceKey,
17
+ signPayload,
18
+ verifyPayload
19
+ } from "@tangentfeed/core";
20
+ var CELL_INFO = "tangentfeed/v1/cells";
21
+ var NONCE_BYTES = 24;
22
+ var KEY_BYTES = 32;
23
+ var utf8 = new TextEncoder();
24
+ var fromUtf8 = new TextDecoder();
25
+ var SpaceCipher = class _SpaceCipher {
26
+ key;
27
+ /** Construct from raw 32-byte key material (the "space secret"). */
28
+ constructor(secret) {
29
+ if (secret.length < 16) {
30
+ throw new Error("space secret must be at least 16 bytes; use fromPassphrase for text");
31
+ }
32
+ this.key = hkdf(sha256, secret, new Uint8Array(0), utf8.encode(CELL_INFO), KEY_BYTES);
33
+ }
34
+ /**
35
+ * Derive a cipher from a human passphrase. The salt must be identical on
36
+ * every device in the space; the space id is a good, non-secret choice.
37
+ */
38
+ static async fromPassphrase(passphrase, salt) {
39
+ const secret = await scryptAsync(utf8.encode(passphrase), utf8.encode(salt));
40
+ return new _SpaceCipher(secret);
41
+ }
42
+ /** Generate a fresh random space secret (to be shared out of band, e.g. by QR). */
43
+ static generateSecret() {
44
+ const b = new Uint8Array(KEY_BYTES);
45
+ globalThis.crypto.getRandomValues(b);
46
+ return b;
47
+ }
48
+ encrypt(value, opId) {
49
+ const nonce = new Uint8Array(NONCE_BYTES);
50
+ globalThis.crypto.getRandomValues(nonce);
51
+ const plaintext = utf8.encode(canonicalJson(value));
52
+ const ct = xchacha20poly1305(this.key, nonce, utf8.encode(opId)).encrypt(plaintext);
53
+ const packed = new Uint8Array(nonce.length + ct.length);
54
+ packed.set(nonce, 0);
55
+ packed.set(ct, nonce.length);
56
+ return CIPHER_PREFIX + base64Encode(packed);
57
+ }
58
+ decrypt(value, opId) {
59
+ if (!isEncryptedValue(value)) return value;
60
+ let packed;
61
+ try {
62
+ packed = base64Decode(value.slice(CIPHER_PREFIX.length));
63
+ } catch {
64
+ throw new DecryptError("value is not valid base64");
65
+ }
66
+ if (packed.length <= NONCE_BYTES) throw new DecryptError("ciphertext too short");
67
+ const nonce = packed.subarray(0, NONCE_BYTES);
68
+ const ct = packed.subarray(NONCE_BYTES);
69
+ let pt;
70
+ try {
71
+ pt = xchacha20poly1305(this.key, nonce, utf8.encode(opId)).decrypt(ct);
72
+ } catch {
73
+ throw new DecryptError("authentication failed (wrong key or tampered data)");
74
+ }
75
+ try {
76
+ return JSON.parse(fromUtf8.decode(pt));
77
+ } catch {
78
+ throw new DecryptError("decrypted payload is not valid JSON");
79
+ }
80
+ }
81
+ };
82
+ async function scryptAsync(pw, salt) {
83
+ return scrypt(pw, salt, { N: 2 ** 15, r: 8, p: 1, dkLen: KEY_BYTES });
84
+ }
85
+ function base64Encode(bytes) {
86
+ if (typeof btoa === "function") {
87
+ let bin = "";
88
+ for (const b of bytes) bin += String.fromCharCode(b);
89
+ return btoa(bin);
90
+ }
91
+ return Buffer.from(bytes).toString("base64");
92
+ }
93
+ function base64Decode(s) {
94
+ if (typeof atob === "function") {
95
+ const bin = atob(s);
96
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
97
+ }
98
+ return new Uint8Array(Buffer.from(s, "base64"));
99
+ }
100
+ export {
101
+ SIGNING_DOMAIN,
102
+ SpaceCipher,
103
+ canonicalJson2 as canonicalJson,
104
+ deviceIdFromPublicKey,
105
+ generateDeviceKey,
106
+ signPayload,
107
+ verifyPayload
108
+ };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@tangentfeed/crypto",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "scripts": {
7
+ "test": "vitest run",
8
+ "build": "tsup src/index.ts --format esm --dts --clean",
9
+ "prepack": "npm run build"
10
+ },
11
+ "dependencies": {
12
+ "@noble/ciphers": "^2.0.0",
13
+ "@noble/hashes": "^2.0.0",
14
+ "@tangentfeed/core": "0.2.0"
15
+ },
16
+ "devDependencies": {
17
+ "@types/node": "^20.0.0",
18
+ "fast-check": "^3.19.0",
19
+ "tsup": "^8.5.0",
20
+ "typescript": "^5.5.0",
21
+ "vitest": "^2.0.0"
22
+ },
23
+ "description": "End-to-end encryption for tangentfeed (XChaCha20-Poly1305)",
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/sreerajta/tangentfeed.git",
28
+ "directory": "packages/crypto"
29
+ },
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "engines": {
43
+ "node": ">=20"
44
+ }
45
+ }