@klickd/core 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,107 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work"). Certain owners wish to
20
+ permanently relinquish those rights to a Work for the purpose of
21
+ contributing to a commons of creative, cultural and scientific works
22
+ ("Commons") that the public can reliably and without fear of later claims
23
+ of infringement build upon, modify, incorporate in other works, convey
24
+ and distribute. These owners may contribute to the Commons to promote the
25
+ ideal of a free culture and the further production of creative, cultural
26
+ and scientific works, or to gain reputation or greater distribution for
27
+ their Work in part through the use and efforts of others.
28
+
29
+ For these and/or other purposes and motivations, and without any
30
+ expectation of additional consideration or compensation, the person
31
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
32
+ is an owner of Copyright and Related Rights in the Work, voluntarily
33
+ elects to apply CC0 to the Work and publicly distribute the Work under its
34
+ terms, with knowledge of his or her Copyright and Related Rights in the
35
+ Work and the meaning and intended legal effect of CC0 on those rights.
36
+
37
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
38
+ protected by copyright and related or neighboring rights ("Copyright and
39
+ Related Rights"). Copyright and Related Rights include, but are not
40
+ limited to, the following:
41
+
42
+ i. the right to reproduce, adapt, distribute, perform, display,
43
+ communicate, and translate a Work;
44
+ ii. moral rights retained by the original author(s) and/or performer(s);
45
+ iii. publicity and privacy rights pertaining to a person's image or
46
+ likeness depicted in a Work;
47
+ iv. rights protecting against unfair competition in regards to a Work,
48
+ subject to the limitations in paragraph 4(a), below;
49
+ v. rights protecting the extraction, dissemination, use and reuse of data
50
+ in a Work;
51
+ vi. database rights (such as those arising under Directive 96/9/EC of the
52
+ European Parliament and of the Council of 11 March 1996 on the legal
53
+ protection of databases, and under any national implementation
54
+ thereof, including any amended or updated version of such directive);
55
+ and
56
+ vii. other similar, equivalent or corresponding rights throughout the
57
+ world based on applicable law or treaty.
58
+
59
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
60
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
61
+ irrevocably and unconditionally waives, abandons, and surrenders all of
62
+ Affirmer's Copyright and Related Rights and associated claims and causes
63
+ of action, whether now known or unknown (including existing as well as
64
+ future claims and causes of action), in the Work (i) in all territories
65
+ worldwide, (ii) for the maximum duration provided by applicable law or
66
+ treaty (including future time extensions), (iii) in any current or future
67
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
68
+ including without limitation commercial, advertising or promotional
69
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
70
+ member of the public at large and to the detriment of Affirmer's heirs and
71
+ successors, fully intending that such Waiver shall not be subject to
72
+ revocation, rescission, cancellation, termination, or any other legal or
73
+ equitable action to disrupt the quiet enjoyment of the Work by the public
74
+ as contemplated by Affirmer's express Statement of Purpose.
75
+
76
+ 3. Public License Fallback. Should any part of the Waiver for any reason
77
+ be judged legally invalid or ineffective under applicable law, then the
78
+ Waiver shall be preserved to the maximum extent permitted taking into
79
+ account Affirmer's express Statement of Purpose. In addition, to the
80
+ extent the Waiver is so judged Affirmer hereby grants to each affected
81
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
82
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
83
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
84
+ maximum duration provided by applicable law or treaty (including future
85
+ time extensions), (iii) in any current or future medium and for any number
86
+ of copies, and (iv) for any purpose whatsoever, including without
87
+ limitation commercial, advertising or promotional purposes.
88
+
89
+ 4. Limitations and Disclaimers.
90
+
91
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
92
+ surrendered, licensed or otherwise affected by this document.
93
+ b. Affirmer offers the Work as-is and makes no representations or
94
+ warranties of any kind concerning the Work, whether express, implied,
95
+ statutory or otherwise, including without limitation warranties of
96
+ title, merchantability, fitness for a particular purpose, non
97
+ infringement, or the absence of latent or other defects, accuracy, or
98
+ the present or absence of errors, whether or not discoverable, all to
99
+ the greatest extent permissible under applicable law.
100
+ c. Affirmer disclaims responsibility for clearing rights of other persons
101
+ that may apply to the Work or any use thereof, including without
102
+ limitation any person's Copyright and Related Rights in the Work.
103
+ Further, Affirmer disclaims responsibility for obtaining any necessary
104
+ consents, permissions or other rights required for any use of the Work.
105
+ d. Affirmer understands and acknowledges that Creative Commons is not a
106
+ party to this document and has no duty or obligation with respect to
107
+ this CC0 or use of the Work.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # @klickd/core
2
+
3
+ Official JavaScript/TypeScript library for reading and writing `.klickd` portable AI context files.
4
+
5
+ **One soul. Any model. Any body.**
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@klickd/core)](https://www.npmjs.com/package/@klickd/core)
8
+ [![License: CC0-1.0](https://img.shields.io/badge/License-CC0_1.0-lightgrey.svg)](https://creativecommons.org/publicdomain/zero/1.0/)
9
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.20262530.svg)](https://doi.org/10.5281/zenodo.20262530)
10
+
11
+ ---
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @klickd/core
17
+ ```
18
+
19
+ ### Argon2id dependency
20
+
21
+ The v3 format uses **Argon2id** for key derivation. Install the appropriate package for your environment:
22
+
23
+ - **Node.js**: `npm install argon2`
24
+ - **Browser / bundler**: `npm install argon2-browser`
25
+
26
+ ---
27
+
28
+ ## Quick start
29
+
30
+ ### Load (decrypt) a `.klickd` file
31
+
32
+ ```typescript
33
+ import { loadKlickd } from '@klickd/core';
34
+ import { readFileSync } from 'node:fs';
35
+
36
+ const fileBytes = readFileSync('context.klickd');
37
+ const payload = await loadKlickd(fileBytes, { passphrase: 'my-passphrase' });
38
+
39
+ console.log(payload.identity?.name);
40
+ console.log(payload.memory);
41
+ ```
42
+
43
+ ### Save (encrypt) a `.klickd` file
44
+
45
+ ```typescript
46
+ import { saveKlickd } from '@klickd/core';
47
+ import { writeFileSync } from 'node:fs';
48
+ import type { KlickdPayload } from '@klickd/core';
49
+
50
+ const payload: KlickdPayload = {
51
+ payload_schema_version: '3.0.0',
52
+ domain_schema_version: '1.0.0',
53
+ identity: { name: 'Alice', language: 'en', timezone: 'Europe/Luxembourg' },
54
+ agent_instructions: 'Be concise.',
55
+ memory: [],
56
+ };
57
+
58
+ const envelope = await saveKlickd(payload, {
59
+ passphrase: 'my-passphrase',
60
+ domain: 'education',
61
+ });
62
+
63
+ writeFileSync('context.klickd', envelope, 'utf8');
64
+ ```
65
+
66
+ ### Legacy v2.x files (PBKDF2)
67
+
68
+ To read files created with the v2.x PBKDF2-SHA256/600k KDF, pass `legacy: true`:
69
+
70
+ ```typescript
71
+ const payload = await loadKlickd(fileBytes, {
72
+ passphrase: 'my-passphrase',
73
+ legacy: true,
74
+ });
75
+ ```
76
+
77
+ ---
78
+
79
+ ## Cryptographic specification (v3.0)
80
+
81
+ | Parameter | Value |
82
+ |---------------|-----------------------------------------|
83
+ | KDF (default) | Argon2id — m=65536, t=3, p=1 |
84
+ | KDF (legacy) | PBKDF2-SHA256 / 600 000 iterations |
85
+ | Cipher | AES-256-GCM |
86
+ | AAD | RFC 8785 JCS over 6 canonical fields |
87
+ | Base64 | RFC 4648 §4 standard padded |
88
+ | Salt | 16 bytes (CSPRNG) |
89
+ | IV | 12 bytes (CSPRNG) |
90
+
91
+ ---
92
+
93
+ ## Error codes
94
+
95
+ | Code | HTTP | Meaning |
96
+ |---------------------|------|------------------------------------------|
97
+ | `KLICKD_E_AUTH` | 401 | Wrong passphrase / GCM tag mismatch |
98
+ | `KLICKD_E_VERSION` | 400 | Unsupported `klickd_version` major |
99
+ | `KLICKD_E_FORMAT` | 400 | Malformed JSON envelope / missing fields |
100
+ | `KLICKD_E_KDF` | 400 | Unknown or unavailable KDF |
101
+ | `KLICKD_E_WEAK_PASS`| 422 | Passphrase shorter than 8 characters |
102
+ | `KLICKD_E_SCHEMA` | 400 | Missing `payload_schema_version` |
103
+
104
+ ---
105
+
106
+ ## Links
107
+
108
+ - Specification: [SPEC.md](https://github.com/Davincc77/klickdskill/blob/main/SPEC.md)
109
+ - Repository: [github.com/Davincc77/klickdskill](https://github.com/Davincc77/klickdskill)
110
+ - DOI: [10.5281/zenodo.20262530](https://doi.org/10.5281/zenodo.20262530)
111
+ - Homepage: [klickd.app](https://klickd.app)
112
+
113
+ ---
114
+
115
+ ## License
116
+
117
+ [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) — Public Domain Dedication.
118
+ Author: Vince C. (Luxlearn, Luxembourg)
package/dist/index.cjs ADDED
@@ -0,0 +1,326 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ HTTP_STATUS: () => HTTP_STATUS,
34
+ KlickdError: () => KlickdError,
35
+ loadKlickd: () => loadKlickd,
36
+ saveKlickd: () => saveKlickd
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+
40
+ // src/errors.ts
41
+ var KlickdError = class _KlickdError extends Error {
42
+ constructor(code, message, httpStatus) {
43
+ super(`${code}: ${message}`);
44
+ this.code = code;
45
+ this.httpStatus = httpStatus;
46
+ this.name = "KlickdError";
47
+ if (Error.captureStackTrace) {
48
+ Error.captureStackTrace(this, _KlickdError);
49
+ }
50
+ }
51
+ };
52
+ var HTTP_STATUS = {
53
+ KLICKD_E_AUTH: 401,
54
+ KLICKD_E_VERSION: 400,
55
+ KLICKD_E_FORMAT: 400,
56
+ KLICKD_E_KDF: 400,
57
+ KLICKD_E_WEAK_PASS: 422,
58
+ KLICKD_E_SCHEMA: 400
59
+ };
60
+
61
+ // src/encode.ts
62
+ var import_node_crypto = require("crypto");
63
+ var import_canonicalize = __toESM(require("canonicalize"), 1);
64
+ var KLICKD_VERSION = "3.0";
65
+ function toBase64(buf) {
66
+ return Buffer.from(buf).toString("base64");
67
+ }
68
+ async function deriveKeyArgon2id(passphrase, salt, m, t, p) {
69
+ try {
70
+ const argon2 = await import("argon2");
71
+ const hash = await argon2.hash(passphrase, {
72
+ type: argon2.argon2id,
73
+ memoryCost: m,
74
+ timeCost: t,
75
+ parallelism: p,
76
+ salt: Buffer.from(salt),
77
+ hashLength: 32,
78
+ raw: true
79
+ });
80
+ return new Uint8Array(hash);
81
+ } catch {
82
+ try {
83
+ const argon2browser = await import("argon2-browser");
84
+ const result = await argon2browser.hash({
85
+ pass: passphrase,
86
+ salt,
87
+ type: argon2browser.ArgonType.Argon2id,
88
+ mem: m,
89
+ time: t,
90
+ parallelism: p,
91
+ hashLen: 32
92
+ });
93
+ return result.hash;
94
+ } catch {
95
+ throw new KlickdError(
96
+ "KLICKD_E_KDF",
97
+ 'Argon2id is unavailable. Install "argon2" (Node.js) or "argon2-browser" (browser).',
98
+ HTTP_STATUS["KLICKD_E_KDF"]
99
+ );
100
+ }
101
+ }
102
+ }
103
+ async function saveKlickd(payload, options) {
104
+ const { passphrase, domain = "education", kdfParams = { m: 65536, t: 3, p: 1 } } = options;
105
+ if (!passphrase || passphrase.length < 8) {
106
+ throw new KlickdError(
107
+ "KLICKD_E_WEAK_PASS",
108
+ "Passphrase must be at least 8 characters.",
109
+ HTTP_STATUS["KLICKD_E_WEAK_PASS"]
110
+ );
111
+ }
112
+ if (!payload.payload_schema_version) {
113
+ throw new KlickdError(
114
+ "KLICKD_E_SCHEMA",
115
+ "payload.payload_schema_version is required.",
116
+ HTTP_STATUS["KLICKD_E_SCHEMA"]
117
+ );
118
+ }
119
+ const salt = (0, import_node_crypto.randomBytes)(16);
120
+ const iv = (0, import_node_crypto.randomBytes)(12);
121
+ const keyBytes = await deriveKeyArgon2id(passphrase, salt, kdfParams.m, kdfParams.t, kdfParams.p);
122
+ const created_at = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
123
+ const envelopeForAad = {
124
+ klickd_version: KLICKD_VERSION,
125
+ encrypted: true,
126
+ domain,
127
+ created_at,
128
+ kdf: {
129
+ name: "argon2id",
130
+ params: kdfParams,
131
+ salt: toBase64(salt)
132
+ },
133
+ cipher: {
134
+ name: "AES-256-GCM",
135
+ iv: toBase64(iv)
136
+ }
137
+ };
138
+ const aadString = (0, import_canonicalize.default)(envelopeForAad);
139
+ if (!aadString) {
140
+ throw new KlickdError("KLICKD_E_FORMAT", "Failed to canonicalize AAD.", 400);
141
+ }
142
+ const aad = Buffer.from(aadString, "utf8");
143
+ const plaintext = Buffer.from(JSON.stringify(payload), "utf8");
144
+ const cipher = (0, import_node_crypto.createCipheriv)("aes-256-gcm", (0, import_node_crypto.createSecretKey)(keyBytes), iv);
145
+ cipher.setAAD(aad);
146
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
147
+ const authTag = cipher.getAuthTag();
148
+ const ciphertext = toBase64(Buffer.concat([encrypted, authTag]));
149
+ const envelope = {
150
+ ...envelopeForAad,
151
+ ciphertext
152
+ };
153
+ return JSON.stringify(envelope);
154
+ }
155
+
156
+ // src/decode.ts
157
+ var import_node_crypto2 = require("crypto");
158
+ var import_node_util = require("util");
159
+ var import_canonicalize2 = __toESM(require("canonicalize"), 1);
160
+ var pbkdf2 = (0, import_node_util.promisify)(import_node_crypto2.pbkdf2);
161
+ var SUPPORTED_MAJOR = 3;
162
+ function fromBase64(s) {
163
+ return Buffer.from(s, "base64");
164
+ }
165
+ async function deriveKeyArgon2id2(passphrase, salt, m, t, p) {
166
+ try {
167
+ const argon2 = await import("argon2");
168
+ const hash = await argon2.hash(passphrase, {
169
+ type: argon2.argon2id,
170
+ memoryCost: m,
171
+ timeCost: t,
172
+ parallelism: p,
173
+ salt,
174
+ hashLength: 32,
175
+ raw: true
176
+ });
177
+ return new Uint8Array(hash);
178
+ } catch {
179
+ try {
180
+ const argon2browser = await import("argon2-browser");
181
+ const result = await argon2browser.hash({
182
+ pass: passphrase,
183
+ salt: new Uint8Array(salt),
184
+ type: argon2browser.ArgonType.Argon2id,
185
+ mem: m,
186
+ time: t,
187
+ parallelism: p,
188
+ hashLen: 32
189
+ });
190
+ return result.hash;
191
+ } catch {
192
+ throw new KlickdError(
193
+ "KLICKD_E_KDF",
194
+ 'Argon2id is unavailable. Install "argon2" (Node.js) or "argon2-browser" (browser).',
195
+ HTTP_STATUS["KLICKD_E_KDF"]
196
+ );
197
+ }
198
+ }
199
+ }
200
+ async function deriveKeyPbkdf2(passphrase, salt, iterations) {
201
+ const key = await pbkdf2(passphrase, salt, iterations, 32, "sha256");
202
+ return new Uint8Array(key);
203
+ }
204
+ async function loadKlickd(input, options = {}) {
205
+ const { passphrase, legacy = false } = options;
206
+ let envelope;
207
+ try {
208
+ const raw = typeof input === "string" ? input : new TextDecoder().decode(input);
209
+ envelope = JSON.parse(raw);
210
+ } catch {
211
+ throw new KlickdError("KLICKD_E_FORMAT", "Invalid JSON envelope.", HTTP_STATUS["KLICKD_E_FORMAT"]);
212
+ }
213
+ const requiredFields = ["klickd_version", "encrypted", "domain", "created_at", "kdf", "cipher", "ciphertext"];
214
+ for (const field of requiredFields) {
215
+ if (!(field in envelope)) {
216
+ throw new KlickdError(
217
+ "KLICKD_E_FORMAT",
218
+ `Missing required envelope field: ${field}`,
219
+ HTTP_STATUS["KLICKD_E_FORMAT"]
220
+ );
221
+ }
222
+ }
223
+ const major = parseInt(envelope.klickd_version.split(".")[0], 10);
224
+ if (isNaN(major) || major !== SUPPORTED_MAJOR) {
225
+ throw new KlickdError(
226
+ "KLICKD_E_VERSION",
227
+ `Unsupported klickd_version major: ${envelope.klickd_version}. This library supports v${SUPPORTED_MAJOR}.x.`,
228
+ HTTP_STATUS["KLICKD_E_VERSION"]
229
+ );
230
+ }
231
+ const envelopeForAad = {
232
+ klickd_version: envelope.klickd_version,
233
+ encrypted: envelope.encrypted,
234
+ domain: envelope.domain,
235
+ created_at: envelope.created_at,
236
+ kdf: envelope.kdf,
237
+ cipher: envelope.cipher
238
+ };
239
+ const aadString = (0, import_canonicalize2.default)(envelopeForAad);
240
+ if (!aadString) {
241
+ throw new KlickdError("KLICKD_E_FORMAT", "Failed to canonicalize AAD.", 400);
242
+ }
243
+ const aad = Buffer.from(aadString, "utf8");
244
+ if (!passphrase) {
245
+ throw new KlickdError(
246
+ "KLICKD_E_AUTH",
247
+ "A passphrase is required to decrypt this file.",
248
+ HTTP_STATUS["KLICKD_E_AUTH"]
249
+ );
250
+ }
251
+ let keyBytes;
252
+ const kdf = envelope.kdf;
253
+ if (kdf.name === "argon2id") {
254
+ const salt = fromBase64(kdf.salt);
255
+ const { m, t, p } = kdf.params;
256
+ if (!m || m < 65536) throw new KlickdError("KLICKD_E_KDF", `kdf.params.m=${m} below minimum 65536`, HTTP_STATUS["KLICKD_E_KDF"]);
257
+ if (!t || t < 3) throw new KlickdError("KLICKD_E_KDF", `kdf.params.t=${t} below minimum 3`, HTTP_STATUS["KLICKD_E_KDF"]);
258
+ if (!p || p < 1) throw new KlickdError("KLICKD_E_KDF", `kdf.params.p=${p} below minimum 1`, HTTP_STATUS["KLICKD_E_KDF"]);
259
+ keyBytes = await deriveKeyArgon2id2(passphrase, salt, m, t, p);
260
+ } else if (kdf.name === "pbkdf2-sha256") {
261
+ if (!legacy) {
262
+ throw new KlickdError(
263
+ "KLICKD_E_KDF",
264
+ "Legacy PBKDF2 KDF detected. Set options.legacy = true to enable reading legacy v2.x files.",
265
+ HTTP_STATUS["KLICKD_E_KDF"]
266
+ );
267
+ }
268
+ const salt = fromBase64(kdf.salt);
269
+ keyBytes = await deriveKeyPbkdf2(passphrase, salt, kdf.params.iterations);
270
+ } else {
271
+ throw new KlickdError(
272
+ "KLICKD_E_KDF",
273
+ `Unknown KDF: ${kdf.name}`,
274
+ HTTP_STATUS["KLICKD_E_KDF"]
275
+ );
276
+ }
277
+ const cipherName = envelope.cipher.name;
278
+ if (cipherName !== "AES-256-GCM") {
279
+ throw new KlickdError(
280
+ "KLICKD_E_FORMAT",
281
+ `Unsupported cipher: ${cipherName}. Only AES-256-GCM is supported in v3.0.`,
282
+ HTTP_STATUS["KLICKD_E_FORMAT"]
283
+ );
284
+ }
285
+ const ciphertextWithTag = fromBase64(envelope.ciphertext);
286
+ if (ciphertextWithTag.length < 16) {
287
+ throw new KlickdError("KLICKD_E_FORMAT", "Ciphertext too short.", HTTP_STATUS["KLICKD_E_FORMAT"]);
288
+ }
289
+ const authTag = ciphertextWithTag.subarray(ciphertextWithTag.length - 16);
290
+ const ciphertextBytes = ciphertextWithTag.subarray(0, ciphertextWithTag.length - 16);
291
+ const iv = fromBase64(envelope.cipher.iv);
292
+ let plaintext;
293
+ try {
294
+ const decipher = (0, import_node_crypto2.createDecipheriv)("aes-256-gcm", (0, import_node_crypto2.createSecretKey)(keyBytes), iv);
295
+ decipher.setAAD(aad);
296
+ decipher.setAuthTag(authTag);
297
+ plaintext = Buffer.concat([decipher.update(ciphertextBytes), decipher.final()]);
298
+ } catch {
299
+ throw new KlickdError(
300
+ "KLICKD_E_AUTH",
301
+ "Decryption failed: wrong passphrase or corrupted file.",
302
+ HTTP_STATUS["KLICKD_E_AUTH"]
303
+ );
304
+ }
305
+ let payload;
306
+ try {
307
+ payload = JSON.parse(plaintext.toString("utf8"));
308
+ } catch {
309
+ throw new KlickdError("KLICKD_E_FORMAT", "Decrypted data is not valid JSON.", HTTP_STATUS["KLICKD_E_FORMAT"]);
310
+ }
311
+ if (!payload.payload_schema_version) {
312
+ throw new KlickdError(
313
+ "KLICKD_E_SCHEMA",
314
+ "Decrypted payload is missing payload_schema_version.",
315
+ HTTP_STATUS["KLICKD_E_SCHEMA"]
316
+ );
317
+ }
318
+ return payload;
319
+ }
320
+ // Annotate the CommonJS export names for ESM import in node:
321
+ 0 && (module.exports = {
322
+ HTTP_STATUS,
323
+ KlickdError,
324
+ loadKlickd,
325
+ saveKlickd
326
+ });
@@ -0,0 +1,127 @@
1
+ type KdfName = 'argon2id' | 'pbkdf2-sha256';
2
+ type CipherName = 'AES-256-GCM';
3
+ type KlickdDomain = 'education' | 'work' | 'finance' | 'legal' | 'creative' | 'health' | 'research' | 'robotics' | string;
4
+ type MemoryRole = 'user' | 'assistant' | 'system';
5
+ type MemoryModality = 'text' | 'image' | 'audio' | 'tool_call';
6
+ interface KlickdKdfArgon2id {
7
+ name: 'argon2id';
8
+ /** Argon2id memory (KiB), time, parallelism params */
9
+ params: {
10
+ m: number;
11
+ t: number;
12
+ p: number;
13
+ };
14
+ /** RFC 4648 §4 standard base64-padded 16-byte salt */
15
+ salt: string;
16
+ }
17
+ interface KlickdKdfPbkdf2 {
18
+ name: 'pbkdf2-sha256';
19
+ /** PBKDF2 iteration count */
20
+ params: {
21
+ iterations: number;
22
+ };
23
+ /** RFC 4648 §4 standard base64-padded 16-byte salt */
24
+ salt: string;
25
+ }
26
+ type KlickdKdf = KlickdKdfArgon2id | KlickdKdfPbkdf2;
27
+ interface KlickdCipher {
28
+ name: CipherName;
29
+ /** RFC 4648 §4 standard base64-padded 12-byte IV */
30
+ iv: string;
31
+ }
32
+ /**
33
+ * The outer .klickd envelope (JSON root object).
34
+ * AAD is JCS (RFC 8785) over the 6 canonical fields:
35
+ * klickd_version, encrypted, domain, created_at, kdf, cipher
36
+ */
37
+ interface KlickdEnvelope {
38
+ klickd_version: string;
39
+ encrypted: boolean;
40
+ domain: KlickdDomain;
41
+ created_at: string;
42
+ kdf: KlickdKdf;
43
+ cipher: KlickdCipher;
44
+ ciphertext: string;
45
+ }
46
+ interface KlickdMemoryEntry {
47
+ /** UUID v4 */
48
+ id: string;
49
+ /** RFC 3339 UTC with Z suffix */
50
+ ts: string;
51
+ role: MemoryRole;
52
+ content: string;
53
+ modality: MemoryModality;
54
+ tags?: string[];
55
+ }
56
+ interface KlickdIdentity {
57
+ name?: string;
58
+ language?: string;
59
+ timezone?: string;
60
+ communication_style?: string;
61
+ }
62
+ interface KlickdContext {
63
+ current_state?: string;
64
+ decisions_locked?: string[];
65
+ artifacts?: unknown[];
66
+ summary?: string;
67
+ }
68
+ interface KlickdKnowledge {
69
+ mastered?: string[];
70
+ gaps?: string[];
71
+ next_steps?: string[];
72
+ }
73
+ interface KlickdPayload {
74
+ payload_schema_version: string;
75
+ domain_schema_version: string;
76
+ identity?: KlickdIdentity;
77
+ agent_instructions?: string;
78
+ user_preferences?: Record<string, unknown>;
79
+ context?: KlickdContext;
80
+ knowledge?: KlickdKnowledge;
81
+ memory?: KlickdMemoryEntry[];
82
+ /** Domain extension fields */
83
+ [key: string]: unknown;
84
+ }
85
+ interface LoadKlickdOptions {
86
+ passphrase?: string;
87
+ /** Enable legacy v2.x PBKDF2-SHA256/600k reading. Default: false */
88
+ legacy?: boolean;
89
+ }
90
+ interface SaveKlickdOptions {
91
+ passphrase: string;
92
+ domain?: KlickdDomain;
93
+ /** Argon2id params override. Default: { m: 65536, t: 3, p: 1 } */
94
+ kdfParams?: {
95
+ m: number;
96
+ t: number;
97
+ p: number;
98
+ };
99
+ }
100
+
101
+ type KlickdErrorCode = 'KLICKD_E_AUTH' | 'KLICKD_E_VERSION' | 'KLICKD_E_FORMAT' | 'KLICKD_E_KDF' | 'KLICKD_E_WEAK_PASS' | 'KLICKD_E_SCHEMA';
102
+ declare class KlickdError extends Error {
103
+ readonly code: KlickdErrorCode;
104
+ readonly httpStatus?: number | undefined;
105
+ constructor(code: KlickdErrorCode, message: string, httpStatus?: number | undefined);
106
+ }
107
+ declare const HTTP_STATUS: Record<KlickdErrorCode, number>;
108
+
109
+ /**
110
+ * Save a KlickdPayload as an encrypted .klickd envelope JSON string.
111
+ *
112
+ * @param payload - The plaintext payload to encrypt.
113
+ * @param options - Passphrase, domain, and optional Argon2id param overrides.
114
+ * @returns - The complete .klickd JSON string (UTF-8).
115
+ */
116
+ declare function saveKlickd(payload: KlickdPayload, options: SaveKlickdOptions): Promise<string>;
117
+
118
+ /**
119
+ * Load and decrypt a .klickd envelope.
120
+ *
121
+ * @param input - Raw .klickd JSON (string or UTF-8 bytes).
122
+ * @param options - Passphrase and optional legacy mode.
123
+ * @returns - The decrypted KlickdPayload.
124
+ */
125
+ declare function loadKlickd(input: string | Uint8Array, options?: LoadKlickdOptions): Promise<KlickdPayload>;
126
+
127
+ export { type CipherName, HTTP_STATUS, type KdfName, type KlickdCipher, type KlickdContext, type KlickdDomain, type KlickdEnvelope, KlickdError, type KlickdErrorCode, type KlickdIdentity, type KlickdKdf, type KlickdKdfArgon2id, type KlickdKdfPbkdf2, type KlickdKnowledge, type KlickdMemoryEntry, type KlickdPayload, type LoadKlickdOptions, type MemoryModality, type MemoryRole, type SaveKlickdOptions, loadKlickd, saveKlickd };
@@ -0,0 +1,127 @@
1
+ type KdfName = 'argon2id' | 'pbkdf2-sha256';
2
+ type CipherName = 'AES-256-GCM';
3
+ type KlickdDomain = 'education' | 'work' | 'finance' | 'legal' | 'creative' | 'health' | 'research' | 'robotics' | string;
4
+ type MemoryRole = 'user' | 'assistant' | 'system';
5
+ type MemoryModality = 'text' | 'image' | 'audio' | 'tool_call';
6
+ interface KlickdKdfArgon2id {
7
+ name: 'argon2id';
8
+ /** Argon2id memory (KiB), time, parallelism params */
9
+ params: {
10
+ m: number;
11
+ t: number;
12
+ p: number;
13
+ };
14
+ /** RFC 4648 §4 standard base64-padded 16-byte salt */
15
+ salt: string;
16
+ }
17
+ interface KlickdKdfPbkdf2 {
18
+ name: 'pbkdf2-sha256';
19
+ /** PBKDF2 iteration count */
20
+ params: {
21
+ iterations: number;
22
+ };
23
+ /** RFC 4648 §4 standard base64-padded 16-byte salt */
24
+ salt: string;
25
+ }
26
+ type KlickdKdf = KlickdKdfArgon2id | KlickdKdfPbkdf2;
27
+ interface KlickdCipher {
28
+ name: CipherName;
29
+ /** RFC 4648 §4 standard base64-padded 12-byte IV */
30
+ iv: string;
31
+ }
32
+ /**
33
+ * The outer .klickd envelope (JSON root object).
34
+ * AAD is JCS (RFC 8785) over the 6 canonical fields:
35
+ * klickd_version, encrypted, domain, created_at, kdf, cipher
36
+ */
37
+ interface KlickdEnvelope {
38
+ klickd_version: string;
39
+ encrypted: boolean;
40
+ domain: KlickdDomain;
41
+ created_at: string;
42
+ kdf: KlickdKdf;
43
+ cipher: KlickdCipher;
44
+ ciphertext: string;
45
+ }
46
+ interface KlickdMemoryEntry {
47
+ /** UUID v4 */
48
+ id: string;
49
+ /** RFC 3339 UTC with Z suffix */
50
+ ts: string;
51
+ role: MemoryRole;
52
+ content: string;
53
+ modality: MemoryModality;
54
+ tags?: string[];
55
+ }
56
+ interface KlickdIdentity {
57
+ name?: string;
58
+ language?: string;
59
+ timezone?: string;
60
+ communication_style?: string;
61
+ }
62
+ interface KlickdContext {
63
+ current_state?: string;
64
+ decisions_locked?: string[];
65
+ artifacts?: unknown[];
66
+ summary?: string;
67
+ }
68
+ interface KlickdKnowledge {
69
+ mastered?: string[];
70
+ gaps?: string[];
71
+ next_steps?: string[];
72
+ }
73
+ interface KlickdPayload {
74
+ payload_schema_version: string;
75
+ domain_schema_version: string;
76
+ identity?: KlickdIdentity;
77
+ agent_instructions?: string;
78
+ user_preferences?: Record<string, unknown>;
79
+ context?: KlickdContext;
80
+ knowledge?: KlickdKnowledge;
81
+ memory?: KlickdMemoryEntry[];
82
+ /** Domain extension fields */
83
+ [key: string]: unknown;
84
+ }
85
+ interface LoadKlickdOptions {
86
+ passphrase?: string;
87
+ /** Enable legacy v2.x PBKDF2-SHA256/600k reading. Default: false */
88
+ legacy?: boolean;
89
+ }
90
+ interface SaveKlickdOptions {
91
+ passphrase: string;
92
+ domain?: KlickdDomain;
93
+ /** Argon2id params override. Default: { m: 65536, t: 3, p: 1 } */
94
+ kdfParams?: {
95
+ m: number;
96
+ t: number;
97
+ p: number;
98
+ };
99
+ }
100
+
101
+ type KlickdErrorCode = 'KLICKD_E_AUTH' | 'KLICKD_E_VERSION' | 'KLICKD_E_FORMAT' | 'KLICKD_E_KDF' | 'KLICKD_E_WEAK_PASS' | 'KLICKD_E_SCHEMA';
102
+ declare class KlickdError extends Error {
103
+ readonly code: KlickdErrorCode;
104
+ readonly httpStatus?: number | undefined;
105
+ constructor(code: KlickdErrorCode, message: string, httpStatus?: number | undefined);
106
+ }
107
+ declare const HTTP_STATUS: Record<KlickdErrorCode, number>;
108
+
109
+ /**
110
+ * Save a KlickdPayload as an encrypted .klickd envelope JSON string.
111
+ *
112
+ * @param payload - The plaintext payload to encrypt.
113
+ * @param options - Passphrase, domain, and optional Argon2id param overrides.
114
+ * @returns - The complete .klickd JSON string (UTF-8).
115
+ */
116
+ declare function saveKlickd(payload: KlickdPayload, options: SaveKlickdOptions): Promise<string>;
117
+
118
+ /**
119
+ * Load and decrypt a .klickd envelope.
120
+ *
121
+ * @param input - Raw .klickd JSON (string or UTF-8 bytes).
122
+ * @param options - Passphrase and optional legacy mode.
123
+ * @returns - The decrypted KlickdPayload.
124
+ */
125
+ declare function loadKlickd(input: string | Uint8Array, options?: LoadKlickdOptions): Promise<KlickdPayload>;
126
+
127
+ export { type CipherName, HTTP_STATUS, type KdfName, type KlickdCipher, type KlickdContext, type KlickdDomain, type KlickdEnvelope, KlickdError, type KlickdErrorCode, type KlickdIdentity, type KlickdKdf, type KlickdKdfArgon2id, type KlickdKdfPbkdf2, type KlickdKnowledge, type KlickdMemoryEntry, type KlickdPayload, type LoadKlickdOptions, type MemoryModality, type MemoryRole, type SaveKlickdOptions, loadKlickd, saveKlickd };
package/dist/index.js ADDED
@@ -0,0 +1,286 @@
1
+ // src/errors.ts
2
+ var KlickdError = class _KlickdError extends Error {
3
+ constructor(code, message, httpStatus) {
4
+ super(`${code}: ${message}`);
5
+ this.code = code;
6
+ this.httpStatus = httpStatus;
7
+ this.name = "KlickdError";
8
+ if (Error.captureStackTrace) {
9
+ Error.captureStackTrace(this, _KlickdError);
10
+ }
11
+ }
12
+ };
13
+ var HTTP_STATUS = {
14
+ KLICKD_E_AUTH: 401,
15
+ KLICKD_E_VERSION: 400,
16
+ KLICKD_E_FORMAT: 400,
17
+ KLICKD_E_KDF: 400,
18
+ KLICKD_E_WEAK_PASS: 422,
19
+ KLICKD_E_SCHEMA: 400
20
+ };
21
+
22
+ // src/encode.ts
23
+ import { randomBytes, createCipheriv, createSecretKey } from "crypto";
24
+ import canonicalize from "canonicalize";
25
+ var KLICKD_VERSION = "3.0";
26
+ function toBase64(buf) {
27
+ return Buffer.from(buf).toString("base64");
28
+ }
29
+ async function deriveKeyArgon2id(passphrase, salt, m, t, p) {
30
+ try {
31
+ const argon2 = await import("argon2");
32
+ const hash = await argon2.hash(passphrase, {
33
+ type: argon2.argon2id,
34
+ memoryCost: m,
35
+ timeCost: t,
36
+ parallelism: p,
37
+ salt: Buffer.from(salt),
38
+ hashLength: 32,
39
+ raw: true
40
+ });
41
+ return new Uint8Array(hash);
42
+ } catch {
43
+ try {
44
+ const argon2browser = await import("argon2-browser");
45
+ const result = await argon2browser.hash({
46
+ pass: passphrase,
47
+ salt,
48
+ type: argon2browser.ArgonType.Argon2id,
49
+ mem: m,
50
+ time: t,
51
+ parallelism: p,
52
+ hashLen: 32
53
+ });
54
+ return result.hash;
55
+ } catch {
56
+ throw new KlickdError(
57
+ "KLICKD_E_KDF",
58
+ 'Argon2id is unavailable. Install "argon2" (Node.js) or "argon2-browser" (browser).',
59
+ HTTP_STATUS["KLICKD_E_KDF"]
60
+ );
61
+ }
62
+ }
63
+ }
64
+ async function saveKlickd(payload, options) {
65
+ const { passphrase, domain = "education", kdfParams = { m: 65536, t: 3, p: 1 } } = options;
66
+ if (!passphrase || passphrase.length < 8) {
67
+ throw new KlickdError(
68
+ "KLICKD_E_WEAK_PASS",
69
+ "Passphrase must be at least 8 characters.",
70
+ HTTP_STATUS["KLICKD_E_WEAK_PASS"]
71
+ );
72
+ }
73
+ if (!payload.payload_schema_version) {
74
+ throw new KlickdError(
75
+ "KLICKD_E_SCHEMA",
76
+ "payload.payload_schema_version is required.",
77
+ HTTP_STATUS["KLICKD_E_SCHEMA"]
78
+ );
79
+ }
80
+ const salt = randomBytes(16);
81
+ const iv = randomBytes(12);
82
+ const keyBytes = await deriveKeyArgon2id(passphrase, salt, kdfParams.m, kdfParams.t, kdfParams.p);
83
+ const created_at = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
84
+ const envelopeForAad = {
85
+ klickd_version: KLICKD_VERSION,
86
+ encrypted: true,
87
+ domain,
88
+ created_at,
89
+ kdf: {
90
+ name: "argon2id",
91
+ params: kdfParams,
92
+ salt: toBase64(salt)
93
+ },
94
+ cipher: {
95
+ name: "AES-256-GCM",
96
+ iv: toBase64(iv)
97
+ }
98
+ };
99
+ const aadString = canonicalize(envelopeForAad);
100
+ if (!aadString) {
101
+ throw new KlickdError("KLICKD_E_FORMAT", "Failed to canonicalize AAD.", 400);
102
+ }
103
+ const aad = Buffer.from(aadString, "utf8");
104
+ const plaintext = Buffer.from(JSON.stringify(payload), "utf8");
105
+ const cipher = createCipheriv("aes-256-gcm", createSecretKey(keyBytes), iv);
106
+ cipher.setAAD(aad);
107
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
108
+ const authTag = cipher.getAuthTag();
109
+ const ciphertext = toBase64(Buffer.concat([encrypted, authTag]));
110
+ const envelope = {
111
+ ...envelopeForAad,
112
+ ciphertext
113
+ };
114
+ return JSON.stringify(envelope);
115
+ }
116
+
117
+ // src/decode.ts
118
+ import { createDecipheriv, createSecretKey as createSecretKey2, pbkdf2 as pbkdf2Cb } from "crypto";
119
+ import { promisify } from "util";
120
+ import canonicalize2 from "canonicalize";
121
+ var pbkdf2 = promisify(pbkdf2Cb);
122
+ var SUPPORTED_MAJOR = 3;
123
+ function fromBase64(s) {
124
+ return Buffer.from(s, "base64");
125
+ }
126
+ async function deriveKeyArgon2id2(passphrase, salt, m, t, p) {
127
+ try {
128
+ const argon2 = await import("argon2");
129
+ const hash = await argon2.hash(passphrase, {
130
+ type: argon2.argon2id,
131
+ memoryCost: m,
132
+ timeCost: t,
133
+ parallelism: p,
134
+ salt,
135
+ hashLength: 32,
136
+ raw: true
137
+ });
138
+ return new Uint8Array(hash);
139
+ } catch {
140
+ try {
141
+ const argon2browser = await import("argon2-browser");
142
+ const result = await argon2browser.hash({
143
+ pass: passphrase,
144
+ salt: new Uint8Array(salt),
145
+ type: argon2browser.ArgonType.Argon2id,
146
+ mem: m,
147
+ time: t,
148
+ parallelism: p,
149
+ hashLen: 32
150
+ });
151
+ return result.hash;
152
+ } catch {
153
+ throw new KlickdError(
154
+ "KLICKD_E_KDF",
155
+ 'Argon2id is unavailable. Install "argon2" (Node.js) or "argon2-browser" (browser).',
156
+ HTTP_STATUS["KLICKD_E_KDF"]
157
+ );
158
+ }
159
+ }
160
+ }
161
+ async function deriveKeyPbkdf2(passphrase, salt, iterations) {
162
+ const key = await pbkdf2(passphrase, salt, iterations, 32, "sha256");
163
+ return new Uint8Array(key);
164
+ }
165
+ async function loadKlickd(input, options = {}) {
166
+ const { passphrase, legacy = false } = options;
167
+ let envelope;
168
+ try {
169
+ const raw = typeof input === "string" ? input : new TextDecoder().decode(input);
170
+ envelope = JSON.parse(raw);
171
+ } catch {
172
+ throw new KlickdError("KLICKD_E_FORMAT", "Invalid JSON envelope.", HTTP_STATUS["KLICKD_E_FORMAT"]);
173
+ }
174
+ const requiredFields = ["klickd_version", "encrypted", "domain", "created_at", "kdf", "cipher", "ciphertext"];
175
+ for (const field of requiredFields) {
176
+ if (!(field in envelope)) {
177
+ throw new KlickdError(
178
+ "KLICKD_E_FORMAT",
179
+ `Missing required envelope field: ${field}`,
180
+ HTTP_STATUS["KLICKD_E_FORMAT"]
181
+ );
182
+ }
183
+ }
184
+ const major = parseInt(envelope.klickd_version.split(".")[0], 10);
185
+ if (isNaN(major) || major !== SUPPORTED_MAJOR) {
186
+ throw new KlickdError(
187
+ "KLICKD_E_VERSION",
188
+ `Unsupported klickd_version major: ${envelope.klickd_version}. This library supports v${SUPPORTED_MAJOR}.x.`,
189
+ HTTP_STATUS["KLICKD_E_VERSION"]
190
+ );
191
+ }
192
+ const envelopeForAad = {
193
+ klickd_version: envelope.klickd_version,
194
+ encrypted: envelope.encrypted,
195
+ domain: envelope.domain,
196
+ created_at: envelope.created_at,
197
+ kdf: envelope.kdf,
198
+ cipher: envelope.cipher
199
+ };
200
+ const aadString = canonicalize2(envelopeForAad);
201
+ if (!aadString) {
202
+ throw new KlickdError("KLICKD_E_FORMAT", "Failed to canonicalize AAD.", 400);
203
+ }
204
+ const aad = Buffer.from(aadString, "utf8");
205
+ if (!passphrase) {
206
+ throw new KlickdError(
207
+ "KLICKD_E_AUTH",
208
+ "A passphrase is required to decrypt this file.",
209
+ HTTP_STATUS["KLICKD_E_AUTH"]
210
+ );
211
+ }
212
+ let keyBytes;
213
+ const kdf = envelope.kdf;
214
+ if (kdf.name === "argon2id") {
215
+ const salt = fromBase64(kdf.salt);
216
+ const { m, t, p } = kdf.params;
217
+ if (!m || m < 65536) throw new KlickdError("KLICKD_E_KDF", `kdf.params.m=${m} below minimum 65536`, HTTP_STATUS["KLICKD_E_KDF"]);
218
+ if (!t || t < 3) throw new KlickdError("KLICKD_E_KDF", `kdf.params.t=${t} below minimum 3`, HTTP_STATUS["KLICKD_E_KDF"]);
219
+ if (!p || p < 1) throw new KlickdError("KLICKD_E_KDF", `kdf.params.p=${p} below minimum 1`, HTTP_STATUS["KLICKD_E_KDF"]);
220
+ keyBytes = await deriveKeyArgon2id2(passphrase, salt, m, t, p);
221
+ } else if (kdf.name === "pbkdf2-sha256") {
222
+ if (!legacy) {
223
+ throw new KlickdError(
224
+ "KLICKD_E_KDF",
225
+ "Legacy PBKDF2 KDF detected. Set options.legacy = true to enable reading legacy v2.x files.",
226
+ HTTP_STATUS["KLICKD_E_KDF"]
227
+ );
228
+ }
229
+ const salt = fromBase64(kdf.salt);
230
+ keyBytes = await deriveKeyPbkdf2(passphrase, salt, kdf.params.iterations);
231
+ } else {
232
+ throw new KlickdError(
233
+ "KLICKD_E_KDF",
234
+ `Unknown KDF: ${kdf.name}`,
235
+ HTTP_STATUS["KLICKD_E_KDF"]
236
+ );
237
+ }
238
+ const cipherName = envelope.cipher.name;
239
+ if (cipherName !== "AES-256-GCM") {
240
+ throw new KlickdError(
241
+ "KLICKD_E_FORMAT",
242
+ `Unsupported cipher: ${cipherName}. Only AES-256-GCM is supported in v3.0.`,
243
+ HTTP_STATUS["KLICKD_E_FORMAT"]
244
+ );
245
+ }
246
+ const ciphertextWithTag = fromBase64(envelope.ciphertext);
247
+ if (ciphertextWithTag.length < 16) {
248
+ throw new KlickdError("KLICKD_E_FORMAT", "Ciphertext too short.", HTTP_STATUS["KLICKD_E_FORMAT"]);
249
+ }
250
+ const authTag = ciphertextWithTag.subarray(ciphertextWithTag.length - 16);
251
+ const ciphertextBytes = ciphertextWithTag.subarray(0, ciphertextWithTag.length - 16);
252
+ const iv = fromBase64(envelope.cipher.iv);
253
+ let plaintext;
254
+ try {
255
+ const decipher = createDecipheriv("aes-256-gcm", createSecretKey2(keyBytes), iv);
256
+ decipher.setAAD(aad);
257
+ decipher.setAuthTag(authTag);
258
+ plaintext = Buffer.concat([decipher.update(ciphertextBytes), decipher.final()]);
259
+ } catch {
260
+ throw new KlickdError(
261
+ "KLICKD_E_AUTH",
262
+ "Decryption failed: wrong passphrase or corrupted file.",
263
+ HTTP_STATUS["KLICKD_E_AUTH"]
264
+ );
265
+ }
266
+ let payload;
267
+ try {
268
+ payload = JSON.parse(plaintext.toString("utf8"));
269
+ } catch {
270
+ throw new KlickdError("KLICKD_E_FORMAT", "Decrypted data is not valid JSON.", HTTP_STATUS["KLICKD_E_FORMAT"]);
271
+ }
272
+ if (!payload.payload_schema_version) {
273
+ throw new KlickdError(
274
+ "KLICKD_E_SCHEMA",
275
+ "Decrypted payload is missing payload_schema_version.",
276
+ HTTP_STATUS["KLICKD_E_SCHEMA"]
277
+ );
278
+ }
279
+ return payload;
280
+ }
281
+ export {
282
+ HTTP_STATUS,
283
+ KlickdError,
284
+ loadKlickd,
285
+ saveKlickd
286
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@klickd/core",
3
+ "version": "3.0.1",
4
+ "description": "Official JavaScript/TypeScript library for reading and writing .klickd portable AI context files",
5
+ "keywords": [
6
+ "klickd",
7
+ "ai-context",
8
+ "portable",
9
+ "memory",
10
+ "encrypted"
11
+ ],
12
+ "homepage": "https://klickd.app",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/Davincc77/klickdskill"
16
+ },
17
+ "license": "CC0-1.0",
18
+ "author": "Vince C. <Luxlearn@pm.me> (https://klickd.app)",
19
+ "type": "module",
20
+ "main": "./dist/index.cjs",
21
+ "module": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "import": "./dist/index.js",
26
+ "require": "./dist/index.cjs",
27
+ "types": "./dist/index.d.ts"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "scripts": {
36
+ "build": "tsup src/index.ts --format esm,cjs --dts --external argon2 --external argon2-browser",
37
+ "test": "node --experimental-vm-modules node_modules/.bin/jest",
38
+ "prepublishOnly": "npm run build"
39
+ },
40
+ "dependencies": {
41
+ "canonicalize": "^2.0.0",
42
+ "hash-wasm": "^4.11.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/jest": "^29.0.0",
46
+ "@types/node": "^20.0.0",
47
+ "argon2": "^0.44.0",
48
+ "argon2-browser": "^1.18.0",
49
+ "jest": "^29.0.0",
50
+ "ts-jest": "^29.0.0",
51
+ "tsup": "^8.0.0",
52
+ "typescript": "^5.4.0"
53
+ },
54
+ "engines": {
55
+ "node": ">=18"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
60
+ }