@gitpagedocs/tools 1.1.62 → 1.1.64

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 (58) hide show
  1. package/README.md +33 -33
  2. package/package.json +1 -1
  3. package/src/ai/bootstrap.ts +50 -50
  4. package/src/ai/catalog.ts +188 -188
  5. package/src/ai/factory.ts +14 -14
  6. package/src/ai/http/streaming.ts +60 -60
  7. package/src/ai/index.ts +27 -27
  8. package/src/ai/legacy-adapter.ts +33 -33
  9. package/src/ai/model-registry.ts +13 -13
  10. package/src/ai/providers/anthropic-provider.ts +83 -83
  11. package/src/ai/providers/cohere-provider.ts +66 -66
  12. package/src/ai/providers/gemini-provider.ts +84 -84
  13. package/src/ai/providers/ollama-provider.ts +69 -69
  14. package/src/ai/providers/openai-compatible-provider.ts +75 -75
  15. package/src/ai/providers/shared.ts +72 -72
  16. package/src/ai/registry.ts +29 -29
  17. package/src/cache/file-cache.ts +86 -86
  18. package/src/cache/index.ts +9 -9
  19. package/src/cache/memory-cache.ts +47 -47
  20. package/src/cache/web-storage-cache.ts +91 -91
  21. package/src/config/config-loader.ts +59 -59
  22. package/src/config/index.ts +1 -1
  23. package/src/constants/config.ts +8 -8
  24. package/src/constants/index.ts +1 -1
  25. package/src/crypto/doc-access.ts +62 -62
  26. package/src/crypto/index.ts +4 -4
  27. package/src/crypto/node-crypto-service.ts +87 -87
  28. package/src/crypto/web-crypto-service.ts +102 -102
  29. package/src/crypto/web.ts +4 -4
  30. package/src/documentation/doc-generator.ts +74 -74
  31. package/src/documentation/doc-updater.ts +47 -47
  32. package/src/documentation/index.ts +18 -18
  33. package/src/documentation/marker-patcher.ts +33 -33
  34. package/src/documentation/sections.ts +84 -84
  35. package/src/errors/app-error.ts +84 -84
  36. package/src/errors/index.ts +1 -1
  37. package/src/filesystem/file-service.ts +121 -121
  38. package/src/filesystem/index.ts +2 -2
  39. package/src/index.ts +25 -25
  40. package/src/logger/index.ts +2 -2
  41. package/src/logger/logger.ts +73 -73
  42. package/src/logger/redaction.ts +43 -43
  43. package/src/platform/index.ts +1 -1
  44. package/src/platform/user-config-dir.ts +48 -48
  45. package/src/ports/ai.ts +109 -109
  46. package/src/ports/cache.ts +16 -16
  47. package/src/ports/config.ts +21 -21
  48. package/src/ports/crypto.ts +33 -33
  49. package/src/ports/index.ts +15 -15
  50. package/src/ports/logger.ts +23 -23
  51. package/src/ports/security.ts +42 -42
  52. package/src/security/credential-vault.ts +117 -117
  53. package/src/security/file-vault-storage.ts +25 -25
  54. package/src/security/index.ts +8 -8
  55. package/src/security/migrate-plaintext-key.ts +38 -38
  56. package/src/security/password-gate.ts +62 -62
  57. package/src/security/web-storage-vault-storage.ts +23 -23
  58. package/src/security/web.ts +9 -9
@@ -1,62 +1,62 @@
1
- /**
2
- * Documentation password-gate key scheme (runtime-agnostic).
3
- *
4
- * Double-hash so config.json can ship a non-reversible verifier while the user
5
- * keeps a copyable credential:
6
- * privateKey = sha256(password) // printed by the CLI, shareable
7
- * publicKey = sha256(privateKey) // stored in config.json
8
- * Unlock succeeds when the supplied input is the password OR the private key.
9
- *
10
- * Pure: depends only on a { sha256 } service, so the SAME code runs in the CLI
11
- * (NodeCryptoService) and the browser (WebCryptoService). It must NOT import
12
- * node:crypto (e.g. safeHexEqual) so it stays safe to bundle for the web.
13
- */
14
-
15
- /** Minimal hashing surface — satisfied by both Node and Web CryptoService. */
16
- export interface Sha256Service {
17
- sha256(input: string): Promise<string>;
18
- }
19
-
20
- export interface DocAccessKeys {
21
- /** sha256(password) — printed for the user to copy/share. */
22
- readonly privateKey: string;
23
- /** sha256(privateKey) — safe to commit in config.json. */
24
- readonly publicKey: string;
25
- }
26
-
27
- /** Derive the { privateKey, publicKey } pair from a plaintext password. */
28
- export async function deriveDocAccessKeys(
29
- password: string,
30
- crypto: Sha256Service,
31
- ): Promise<DocAccessKeys> {
32
- const privateKey = await crypto.sha256(password);
33
- const publicKey = await crypto.sha256(privateKey);
34
- return { privateKey, publicKey };
35
- }
36
-
37
- /**
38
- * Verify a user-supplied credential (password OR private key) against the stored
39
- * public key. Returns false when either side is empty.
40
- */
41
- export async function verifyDocAccess(
42
- input: string,
43
- publicKey: string,
44
- crypto: Sha256Service,
45
- ): Promise<boolean> {
46
- if (!input || !publicKey) return false;
47
- const once = await crypto.sha256(input);
48
- if (hexEqual(once, publicKey)) return true; // input is the private key
49
- const twice = await crypto.sha256(once);
50
- return hexEqual(twice, publicKey); // input is the password
51
- }
52
-
53
- /**
54
- * Length-checked, constant-time hex comparison. Local (not safeHexEqual) so this
55
- * module never imports node:crypto and stays browser-bundle-safe.
56
- */
57
- function hexEqual(a: string, b: string): boolean {
58
- if (a.length !== b.length) return false;
59
- let diff = 0;
60
- for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
61
- return diff === 0;
62
- }
1
+ /**
2
+ * Documentation password-gate key scheme (runtime-agnostic).
3
+ *
4
+ * Double-hash so config.json can ship a non-reversible verifier while the user
5
+ * keeps a copyable credential:
6
+ * privateKey = sha256(password) // printed by the CLI, shareable
7
+ * publicKey = sha256(privateKey) // stored in config.json
8
+ * Unlock succeeds when the supplied input is the password OR the private key.
9
+ *
10
+ * Pure: depends only on a { sha256 } service, so the SAME code runs in the CLI
11
+ * (NodeCryptoService) and the browser (WebCryptoService). It must NOT import
12
+ * node:crypto (e.g. safeHexEqual) so it stays safe to bundle for the web.
13
+ */
14
+
15
+ /** Minimal hashing surface — satisfied by both Node and Web CryptoService. */
16
+ export interface Sha256Service {
17
+ sha256(input: string): Promise<string>;
18
+ }
19
+
20
+ export interface DocAccessKeys {
21
+ /** sha256(password) — printed for the user to copy/share. */
22
+ readonly privateKey: string;
23
+ /** sha256(privateKey) — safe to commit in config.json. */
24
+ readonly publicKey: string;
25
+ }
26
+
27
+ /** Derive the { privateKey, publicKey } pair from a plaintext password. */
28
+ export async function deriveDocAccessKeys(
29
+ password: string,
30
+ crypto: Sha256Service,
31
+ ): Promise<DocAccessKeys> {
32
+ const privateKey = await crypto.sha256(password);
33
+ const publicKey = await crypto.sha256(privateKey);
34
+ return { privateKey, publicKey };
35
+ }
36
+
37
+ /**
38
+ * Verify a user-supplied credential (password OR private key) against the stored
39
+ * public key. Returns false when either side is empty.
40
+ */
41
+ export async function verifyDocAccess(
42
+ input: string,
43
+ publicKey: string,
44
+ crypto: Sha256Service,
45
+ ): Promise<boolean> {
46
+ if (!input || !publicKey) return false;
47
+ const once = await crypto.sha256(input);
48
+ if (hexEqual(once, publicKey)) return true; // input is the private key
49
+ const twice = await crypto.sha256(once);
50
+ return hexEqual(twice, publicKey); // input is the password
51
+ }
52
+
53
+ /**
54
+ * Length-checked, constant-time hex comparison. Local (not safeHexEqual) so this
55
+ * module never imports node:crypto and stays browser-bundle-safe.
56
+ */
57
+ function hexEqual(a: string, b: string): boolean {
58
+ if (a.length !== b.length) return false;
59
+ let diff = 0;
60
+ for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
61
+ return diff === 0;
62
+ }
@@ -1,4 +1,4 @@
1
- export { NodeCryptoService, safeHexEqual } from "./node-crypto-service";
2
- export { WebCryptoService } from "./web-crypto-service";
3
- export { deriveDocAccessKeys, verifyDocAccess } from "./doc-access";
4
- export type { DocAccessKeys, Sha256Service } from "./doc-access";
1
+ export { NodeCryptoService, safeHexEqual } from "./node-crypto-service";
2
+ export { WebCryptoService } from "./web-crypto-service";
3
+ export { deriveDocAccessKeys, verifyDocAccess } from "./doc-access";
4
+ export type { DocAccessKeys, Sha256Service } from "./doc-access";
@@ -1,87 +1,87 @@
1
- import {
2
- createHash,
3
- pbkdf2Sync,
4
- randomBytes,
5
- createCipheriv,
6
- createDecipheriv,
7
- timingSafeEqual,
8
- } from "node:crypto";
9
- import type { CryptoService, EncryptedPayload, KeyDerivationParams } from "../ports/crypto";
10
- import { SecurityError } from "../errors/app-error";
11
-
12
- const KEY_LENGTH = 32; // AES-256
13
- const IV_LENGTH = 12; // GCM nonce
14
- const DEFAULT_ITERATIONS = 210_000; // OWASP PBKDF2-SHA256 guidance
15
- const DIGEST = "sha256";
16
-
17
- /** Node.js implementation of the CryptoService port (CLI + MCP). */
18
- export class NodeCryptoService implements CryptoService {
19
- constructor(private readonly iterations: number = DEFAULT_ITERATIONS) {}
20
-
21
- async sha256(input: string): Promise<string> {
22
- return createHash("sha256").update(input, "utf8").digest("hex");
23
- }
24
-
25
- async deriveKey(password: string, params: KeyDerivationParams): Promise<Uint8Array> {
26
- const salt = Buffer.from(params.salt, "base64");
27
- return new Uint8Array(pbkdf2Sync(password, salt, params.iterations, KEY_LENGTH, DIGEST));
28
- }
29
-
30
- async encrypt(plaintext: string, password: string): Promise<EncryptedPayload> {
31
- const kdf: KeyDerivationParams = {
32
- salt: randomBytes(16).toString("base64"),
33
- iterations: this.iterations,
34
- };
35
- const key = await this.deriveKey(password, kdf);
36
- const iv = randomBytes(IV_LENGTH);
37
- const cipher = createCipheriv("aes-256-gcm", key, iv);
38
- const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
39
- const authTag = cipher.getAuthTag();
40
- this.wipe(key);
41
- return {
42
- ciphertext: encrypted.toString("base64"),
43
- iv: iv.toString("base64"),
44
- authTag: authTag.toString("base64"),
45
- kdf,
46
- };
47
- }
48
-
49
- async decrypt(payload: EncryptedPayload, password: string): Promise<string> {
50
- if (!payload.authTag) {
51
- throw new SecurityError("Missing authentication tag for AES-256-GCM payload.");
52
- }
53
- const key = await this.deriveKey(password, payload.kdf);
54
- try {
55
- const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(payload.iv, "base64"));
56
- decipher.setAuthTag(Buffer.from(payload.authTag, "base64"));
57
- const decrypted = Buffer.concat([
58
- decipher.update(Buffer.from(payload.ciphertext, "base64")),
59
- decipher.final(),
60
- ]);
61
- return decrypted.toString("utf8");
62
- } catch (cause) {
63
- // Wrong password or tampered ciphertext both surface here.
64
- throw new SecurityError("Failed to decrypt payload (wrong password or corrupted data).", { cause });
65
- } finally {
66
- this.wipe(key);
67
- }
68
- }
69
-
70
- mask(secret: string): string {
71
- if (!secret) return "";
72
- if (secret.length <= 8) return "…";
73
- return `${secret.slice(0, 3)}…${secret.slice(-4)}`;
74
- }
75
-
76
- wipe(buffer: Uint8Array): void {
77
- buffer.fill(0);
78
- }
79
- }
80
-
81
- /** Constant-time comparison of two hex digests. */
82
- export function safeHexEqual(a: string, b: string): boolean {
83
- const bufA = Buffer.from(a, "hex");
84
- const bufB = Buffer.from(b, "hex");
85
- if (bufA.length !== bufB.length) return false;
86
- return timingSafeEqual(bufA, bufB);
87
- }
1
+ import {
2
+ createHash,
3
+ pbkdf2Sync,
4
+ randomBytes,
5
+ createCipheriv,
6
+ createDecipheriv,
7
+ timingSafeEqual,
8
+ } from "node:crypto";
9
+ import type { CryptoService, EncryptedPayload, KeyDerivationParams } from "../ports/crypto";
10
+ import { SecurityError } from "../errors/app-error";
11
+
12
+ const KEY_LENGTH = 32; // AES-256
13
+ const IV_LENGTH = 12; // GCM nonce
14
+ const DEFAULT_ITERATIONS = 210_000; // OWASP PBKDF2-SHA256 guidance
15
+ const DIGEST = "sha256";
16
+
17
+ /** Node.js implementation of the CryptoService port (CLI + MCP). */
18
+ export class NodeCryptoService implements CryptoService {
19
+ constructor(private readonly iterations: number = DEFAULT_ITERATIONS) {}
20
+
21
+ async sha256(input: string): Promise<string> {
22
+ return createHash("sha256").update(input, "utf8").digest("hex");
23
+ }
24
+
25
+ async deriveKey(password: string, params: KeyDerivationParams): Promise<Uint8Array> {
26
+ const salt = Buffer.from(params.salt, "base64");
27
+ return new Uint8Array(pbkdf2Sync(password, salt, params.iterations, KEY_LENGTH, DIGEST));
28
+ }
29
+
30
+ async encrypt(plaintext: string, password: string): Promise<EncryptedPayload> {
31
+ const kdf: KeyDerivationParams = {
32
+ salt: randomBytes(16).toString("base64"),
33
+ iterations: this.iterations,
34
+ };
35
+ const key = await this.deriveKey(password, kdf);
36
+ const iv = randomBytes(IV_LENGTH);
37
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
38
+ const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
39
+ const authTag = cipher.getAuthTag();
40
+ this.wipe(key);
41
+ return {
42
+ ciphertext: encrypted.toString("base64"),
43
+ iv: iv.toString("base64"),
44
+ authTag: authTag.toString("base64"),
45
+ kdf,
46
+ };
47
+ }
48
+
49
+ async decrypt(payload: EncryptedPayload, password: string): Promise<string> {
50
+ if (!payload.authTag) {
51
+ throw new SecurityError("Missing authentication tag for AES-256-GCM payload.");
52
+ }
53
+ const key = await this.deriveKey(password, payload.kdf);
54
+ try {
55
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(payload.iv, "base64"));
56
+ decipher.setAuthTag(Buffer.from(payload.authTag, "base64"));
57
+ const decrypted = Buffer.concat([
58
+ decipher.update(Buffer.from(payload.ciphertext, "base64")),
59
+ decipher.final(),
60
+ ]);
61
+ return decrypted.toString("utf8");
62
+ } catch (cause) {
63
+ // Wrong password or tampered ciphertext both surface here.
64
+ throw new SecurityError("Failed to decrypt payload (wrong password or corrupted data).", { cause });
65
+ } finally {
66
+ this.wipe(key);
67
+ }
68
+ }
69
+
70
+ mask(secret: string): string {
71
+ if (!secret) return "";
72
+ if (secret.length <= 8) return "…";
73
+ return `${secret.slice(0, 3)}…${secret.slice(-4)}`;
74
+ }
75
+
76
+ wipe(buffer: Uint8Array): void {
77
+ buffer.fill(0);
78
+ }
79
+ }
80
+
81
+ /** Constant-time comparison of two hex digests. */
82
+ export function safeHexEqual(a: string, b: string): boolean {
83
+ const bufA = Buffer.from(a, "hex");
84
+ const bufB = Buffer.from(b, "hex");
85
+ if (bufA.length !== bufB.length) return false;
86
+ return timingSafeEqual(bufA, bufB);
87
+ }
@@ -1,102 +1,102 @@
1
- import type { CryptoService, EncryptedPayload, KeyDerivationParams } from "../ports/crypto";
2
- import { SecurityError } from "../errors/app-error";
3
-
4
- const KEY_BITS = 256;
5
- const IV_LENGTH = 12;
6
- const DEFAULT_ITERATIONS = 210_000;
7
-
8
- function toBase64(bytes: Uint8Array): string {
9
- let binary = "";
10
- for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
11
- return btoa(binary);
12
- }
13
-
14
- function fromBase64(b64: string): Uint8Array<ArrayBuffer> {
15
- const binary = atob(b64);
16
- const out = new Uint8Array(binary.length);
17
- for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
18
- return out;
19
- }
20
-
21
- // Web Crypto args must be ArrayBuffer-backed (BufferSource) under DOM lib; the
22
- // cast keeps this file valid under both the Node-typed and DOM-typed programs.
23
- function enc(text: string): Uint8Array<ArrayBuffer> {
24
- return new TextEncoder().encode(text) as Uint8Array<ArrayBuffer>;
25
- }
26
-
27
- /**
28
- * Web Crypto (SubtleCrypto) implementation of CryptoService for the browser.
29
- * Also runs under Node 22 (globalThis.crypto). AES-GCM keeps the auth tag inside
30
- * the ciphertext, so a payload encrypted here is decrypted here.
31
- */
32
- export class WebCryptoService implements CryptoService {
33
- constructor(private readonly iterations: number = DEFAULT_ITERATIONS) {}
34
-
35
- // Return type is inferred (SubtleCrypto) to avoid pulling DOM lib type names
36
- // into this Node-typed package.
37
- private get subtle() {
38
- const c = globalThis.crypto;
39
- if (!c?.subtle) throw new SecurityError("Web Crypto API is unavailable in this runtime.");
40
- return c.subtle;
41
- }
42
-
43
- async sha256(input: string): Promise<string> {
44
- const digest = await this.subtle.digest("SHA-256", enc(input));
45
- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
46
- }
47
-
48
- async deriveKey(password: string, params: KeyDerivationParams): Promise<Uint8Array> {
49
- const bits = await this.deriveBits(password, params);
50
- return new Uint8Array(bits);
51
- }
52
-
53
- private async deriveBits(password: string, params: KeyDerivationParams): Promise<ArrayBuffer> {
54
- const baseKey = await this.subtle.importKey("raw", enc(password), "PBKDF2", false, ["deriveBits"]);
55
- return this.subtle.deriveBits(
56
- { name: "PBKDF2", salt: fromBase64(params.salt), iterations: params.iterations, hash: "SHA-256" },
57
- baseKey,
58
- KEY_BITS,
59
- );
60
- }
61
-
62
- // Returns an AES-GCM CryptoKey (type inferred to avoid DOM lib names).
63
- private async aesKey(password: string, params: KeyDerivationParams) {
64
- const bits = await this.deriveBits(password, params);
65
- return this.subtle.importKey("raw", bits, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
66
- }
67
-
68
- async encrypt(plaintext: string, password: string): Promise<EncryptedPayload> {
69
- const kdf: KeyDerivationParams = {
70
- salt: toBase64(globalThis.crypto.getRandomValues(new Uint8Array(16))),
71
- iterations: this.iterations,
72
- };
73
- const iv: Uint8Array<ArrayBuffer> = globalThis.crypto.getRandomValues(new Uint8Array(IV_LENGTH));
74
- const key = await this.aesKey(password, kdf);
75
- const encrypted = await this.subtle.encrypt({ name: "AES-GCM", iv }, key, enc(plaintext));
76
- return { ciphertext: toBase64(new Uint8Array(encrypted)), iv: toBase64(iv), kdf };
77
- }
78
-
79
- async decrypt(payload: EncryptedPayload, password: string): Promise<string> {
80
- const key = await this.aesKey(password, payload.kdf);
81
- try {
82
- const decrypted = await this.subtle.decrypt(
83
- { name: "AES-GCM", iv: fromBase64(payload.iv) },
84
- key,
85
- fromBase64(payload.ciphertext),
86
- );
87
- return new TextDecoder().decode(decrypted);
88
- } catch (cause) {
89
- throw new SecurityError("Failed to decrypt payload (wrong password or corrupted data).", { cause });
90
- }
91
- }
92
-
93
- mask(secret: string): string {
94
- if (!secret) return "";
95
- if (secret.length <= 8) return "…";
96
- return `${secret.slice(0, 3)}…${secret.slice(-4)}`;
97
- }
98
-
99
- wipe(buffer: Uint8Array): void {
100
- buffer.fill(0);
101
- }
102
- }
1
+ import type { CryptoService, EncryptedPayload, KeyDerivationParams } from "../ports/crypto";
2
+ import { SecurityError } from "../errors/app-error";
3
+
4
+ const KEY_BITS = 256;
5
+ const IV_LENGTH = 12;
6
+ const DEFAULT_ITERATIONS = 210_000;
7
+
8
+ function toBase64(bytes: Uint8Array): string {
9
+ let binary = "";
10
+ for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
11
+ return btoa(binary);
12
+ }
13
+
14
+ function fromBase64(b64: string): Uint8Array<ArrayBuffer> {
15
+ const binary = atob(b64);
16
+ const out = new Uint8Array(binary.length);
17
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
18
+ return out;
19
+ }
20
+
21
+ // Web Crypto args must be ArrayBuffer-backed (BufferSource) under DOM lib; the
22
+ // cast keeps this file valid under both the Node-typed and DOM-typed programs.
23
+ function enc(text: string): Uint8Array<ArrayBuffer> {
24
+ return new TextEncoder().encode(text) as Uint8Array<ArrayBuffer>;
25
+ }
26
+
27
+ /**
28
+ * Web Crypto (SubtleCrypto) implementation of CryptoService for the browser.
29
+ * Also runs under Node 22 (globalThis.crypto). AES-GCM keeps the auth tag inside
30
+ * the ciphertext, so a payload encrypted here is decrypted here.
31
+ */
32
+ export class WebCryptoService implements CryptoService {
33
+ constructor(private readonly iterations: number = DEFAULT_ITERATIONS) {}
34
+
35
+ // Return type is inferred (SubtleCrypto) to avoid pulling DOM lib type names
36
+ // into this Node-typed package.
37
+ private get subtle() {
38
+ const c = globalThis.crypto;
39
+ if (!c?.subtle) throw new SecurityError("Web Crypto API is unavailable in this runtime.");
40
+ return c.subtle;
41
+ }
42
+
43
+ async sha256(input: string): Promise<string> {
44
+ const digest = await this.subtle.digest("SHA-256", enc(input));
45
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
46
+ }
47
+
48
+ async deriveKey(password: string, params: KeyDerivationParams): Promise<Uint8Array> {
49
+ const bits = await this.deriveBits(password, params);
50
+ return new Uint8Array(bits);
51
+ }
52
+
53
+ private async deriveBits(password: string, params: KeyDerivationParams): Promise<ArrayBuffer> {
54
+ const baseKey = await this.subtle.importKey("raw", enc(password), "PBKDF2", false, ["deriveBits"]);
55
+ return this.subtle.deriveBits(
56
+ { name: "PBKDF2", salt: fromBase64(params.salt), iterations: params.iterations, hash: "SHA-256" },
57
+ baseKey,
58
+ KEY_BITS,
59
+ );
60
+ }
61
+
62
+ // Returns an AES-GCM CryptoKey (type inferred to avoid DOM lib names).
63
+ private async aesKey(password: string, params: KeyDerivationParams) {
64
+ const bits = await this.deriveBits(password, params);
65
+ return this.subtle.importKey("raw", bits, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
66
+ }
67
+
68
+ async encrypt(plaintext: string, password: string): Promise<EncryptedPayload> {
69
+ const kdf: KeyDerivationParams = {
70
+ salt: toBase64(globalThis.crypto.getRandomValues(new Uint8Array(16))),
71
+ iterations: this.iterations,
72
+ };
73
+ const iv: Uint8Array<ArrayBuffer> = globalThis.crypto.getRandomValues(new Uint8Array(IV_LENGTH));
74
+ const key = await this.aesKey(password, kdf);
75
+ const encrypted = await this.subtle.encrypt({ name: "AES-GCM", iv }, key, enc(plaintext));
76
+ return { ciphertext: toBase64(new Uint8Array(encrypted)), iv: toBase64(iv), kdf };
77
+ }
78
+
79
+ async decrypt(payload: EncryptedPayload, password: string): Promise<string> {
80
+ const key = await this.aesKey(password, payload.kdf);
81
+ try {
82
+ const decrypted = await this.subtle.decrypt(
83
+ { name: "AES-GCM", iv: fromBase64(payload.iv) },
84
+ key,
85
+ fromBase64(payload.ciphertext),
86
+ );
87
+ return new TextDecoder().decode(decrypted);
88
+ } catch (cause) {
89
+ throw new SecurityError("Failed to decrypt payload (wrong password or corrupted data).", { cause });
90
+ }
91
+ }
92
+
93
+ mask(secret: string): string {
94
+ if (!secret) return "";
95
+ if (secret.length <= 8) return "…";
96
+ return `${secret.slice(0, 3)}…${secret.slice(-4)}`;
97
+ }
98
+
99
+ wipe(buffer: Uint8Array): void {
100
+ buffer.fill(0);
101
+ }
102
+ }
package/src/crypto/web.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Browser-safe crypto entry: Web Crypto only (no node:crypto).
2
- export { WebCryptoService } from "./web-crypto-service";
3
- export { deriveDocAccessKeys, verifyDocAccess } from "./doc-access";
4
- export type { DocAccessKeys, Sha256Service } from "./doc-access";
1
+ // Browser-safe crypto entry: Web Crypto only (no node:crypto).
2
+ export { WebCryptoService } from "./web-crypto-service";
3
+ export { deriveDocAccessKeys, verifyDocAccess } from "./doc-access";
4
+ export type { DocAccessKeys, Sha256Service } from "./doc-access";