beans-memory 0.0.0-stage → 0.1.5

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/src/mcp.ts ADDED
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env bun
2
+ import { basename, join } from "node:path";
3
+ import { createInterface } from "node:readline";
4
+ import { openDb, resolveDbPath } from "./db";
5
+ import { localDate, localStamp } from "./time";
6
+ import {
7
+ addObservation,
8
+ getObservations,
9
+ recentObservations,
10
+ searchObservations,
11
+ stats,
12
+ } from "./repo";
13
+
14
+ const packageJson = (await Bun.file(join(import.meta.dir, "..", "package.json")).json()) as {
15
+ version?: string;
16
+ };
17
+ const VERSION = packageJson.version ?? "0.0.0";
18
+
19
+ const db = openDb(resolveDbPath());
20
+ const project = process.env.MEMORY_PROJECT || basename(process.cwd());
21
+
22
+ const TOOLS = [
23
+ {
24
+ name: "memory_search",
25
+ description:
26
+ "Cari catatan memory project ini. Mengembalikan index ringkas (id, tanggal, tipe, judul). Pakai memory_get untuk isi lengkap.",
27
+ inputSchema: {
28
+ type: "object",
29
+ properties: {
30
+ query: { type: "string", description: "Kata kunci pencarian." },
31
+ limit: { type: "number", description: "Jumlah hasil, default 10, maksimal 50." },
32
+ type: { type: "string", description: "Filter tipe, misalnya decision atau bugfix." },
33
+ },
34
+ required: ["query"],
35
+ additionalProperties: false,
36
+ },
37
+ },
38
+ {
39
+ name: "memory_get",
40
+ description: "Ambil isi lengkap catatan memory berdasarkan id hasil memory_search.",
41
+ inputSchema: {
42
+ type: "object",
43
+ properties: {
44
+ ids: { type: "array", items: { type: "number" }, description: "Daftar id catatan." },
45
+ },
46
+ required: ["ids"],
47
+ additionalProperties: false,
48
+ },
49
+ },
50
+ {
51
+ name: "memory_note",
52
+ description:
53
+ "Simpan catatan permanen untuk project ini: keputusan, bugfix, aturan bisnis, atau temuan wiring.",
54
+ inputSchema: {
55
+ type: "object",
56
+ properties: {
57
+ title: { type: "string" },
58
+ body: { type: "string" },
59
+ type: {
60
+ type: "string",
61
+ enum: ["decision", "bugfix", "feature", "refactor", "security_note", "note"],
62
+ },
63
+ files: { type: "array", items: { type: "string" } },
64
+ concepts: { type: "array", items: { type: "string" } },
65
+ },
66
+ required: ["title", "body"],
67
+ additionalProperties: false,
68
+ },
69
+ },
70
+ {
71
+ name: "memory_stats",
72
+ description: "Ringkasan isi memory project ini.",
73
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
74
+ },
75
+ ];
76
+
77
+ function text(value: string): { content: Array<{ type: "text"; text: string }> } {
78
+ return { content: [{ type: "text", text: value }] };
79
+ }
80
+
81
+ function callTool(name: string, args: any): string {
82
+ if (name === "memory_search") {
83
+ const rows = searchObservations(db, {
84
+ project,
85
+ query: String(args?.query ?? ""),
86
+ limit: Number(args?.limit ?? 10),
87
+ type: typeof args?.type === "string" ? args.type : undefined,
88
+ });
89
+ if (rows.length === 0) return "Tidak ada catatan yang cocok.";
90
+ return rows
91
+ .map((row) => {
92
+ const snip = row.snip ? ` | ${row.snip.replace(/\s+/g, " ").slice(0, 160)}` : "";
93
+ return `#${row.id} · ${localDate(row.created_at)} · ${row.type} · ${row.title}${snip}`;
94
+ })
95
+ .join("\n");
96
+ }
97
+
98
+ if (name === "memory_get") {
99
+ const ids = Array.isArray(args?.ids)
100
+ ? args.ids.map((id: unknown) => Number(id)).filter(Number.isFinite)
101
+ : [];
102
+ const rows = getObservations(db, ids);
103
+ if (rows.length === 0) return "Catatan tidak ditemukan.";
104
+ return rows
105
+ .map((row) =>
106
+ [
107
+ `# ${row.title} (#${row.id})`,
108
+ `Tanggal: ${localStamp(row.created_at)} · Tipe: ${row.type}`,
109
+ row.files.length > 0 ? `File: ${row.files.join(", ")}` : "",
110
+ "",
111
+ row.body,
112
+ ]
113
+ .filter(Boolean)
114
+ .join("\n"),
115
+ )
116
+ .join("\n\n---\n\n");
117
+ }
118
+
119
+ if (name === "memory_note") {
120
+ const result = addObservation(db, {
121
+ project,
122
+ title: String(args?.title ?? ""),
123
+ body: String(args?.body ?? ""),
124
+ type: typeof args?.type === "string" ? args.type : "note",
125
+ files: Array.isArray(args?.files) ? args.files.map(String) : [],
126
+ concepts: Array.isArray(args?.concepts) ? args.concepts.map(String) : [],
127
+ source: "agent",
128
+ });
129
+ return result.inserted
130
+ ? `Catatan tersimpan sebagai #${result.id}.`
131
+ : `Catatan identik sudah ada sebagai #${result.id}.`;
132
+ }
133
+
134
+ if (name === "memory_stats") {
135
+ const value = stats(db, project);
136
+ return `Project ${project}: ${value.observations} catatan, ${value.prompts} prompt, ${value.sessions} sesi. Catatan terakhir: ${value.lastObservation ? localStamp(value.lastObservation) : "belum ada"}.`;
137
+ }
138
+
139
+ throw new Error(`Tool tidak dikenal: ${name}`);
140
+ }
141
+
142
+ const SUPPORTED_PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"];
143
+
144
+ function send(message: unknown): void {
145
+ process.stdout.write(`${JSON.stringify(message)}\n`);
146
+ }
147
+
148
+ function reply(id: unknown, result: unknown): void {
149
+ send({ jsonrpc: "2.0", id, result });
150
+ }
151
+
152
+ function fail(id: unknown, code: number, message: string): void {
153
+ send({ jsonrpc: "2.0", id, error: { code, message } });
154
+ }
155
+
156
+ const rl = createInterface({ input: process.stdin });
157
+ rl.on("line", (line) => {
158
+ const trimmed = line.trim();
159
+ if (!trimmed) return;
160
+
161
+ let message: any;
162
+ try {
163
+ message = JSON.parse(trimmed);
164
+ } catch {
165
+ fail(null, -32700, "Parse error");
166
+ return;
167
+ }
168
+
169
+ const { id, method, params } = message ?? {};
170
+ const hasId = Object.prototype.hasOwnProperty.call(message ?? {}, "id");
171
+ const isNotification = !hasId;
172
+
173
+ if (typeof method !== "string") {
174
+ if (hasId) fail(id ?? null, -32600, "Invalid Request");
175
+ return;
176
+ }
177
+
178
+ try {
179
+ if (method === "initialize") {
180
+ const requested = params?.protocolVersion;
181
+ const protocolVersion =
182
+ typeof requested === "string" && SUPPORTED_PROTOCOLS.includes(requested)
183
+ ? requested
184
+ : SUPPORTED_PROTOCOLS[0];
185
+ reply(id, {
186
+ protocolVersion,
187
+ capabilities: { tools: {} },
188
+ serverInfo: { name: "beans-memory", version: VERSION },
189
+ });
190
+ return;
191
+ }
192
+
193
+ if (method === "notifications/initialized" || method === "initialized") return;
194
+ if (method === "ping") {
195
+ if (!isNotification) reply(id, {});
196
+ return;
197
+ }
198
+
199
+ if (method === "tools/list") {
200
+ if (!isNotification) reply(id, { tools: TOOLS });
201
+ return;
202
+ }
203
+
204
+ if (method === "tools/call") {
205
+ if (isNotification) return;
206
+ const name = String(params?.name ?? "");
207
+ try {
208
+ reply(id, text(callTool(name, params?.arguments)));
209
+ } catch (error) {
210
+ reply(id, {
211
+ content: [
212
+ { type: "text", text: error instanceof Error ? error.message : String(error) },
213
+ ],
214
+ isError: true,
215
+ });
216
+ }
217
+ return;
218
+ }
219
+
220
+ if (!isNotification) fail(id, -32601, `Method not found: ${method}`);
221
+ } catch (error) {
222
+ if (!isNotification) fail(id, -32603, error instanceof Error ? error.message : String(error));
223
+ }
224
+ });
225
+
226
+ function shutdown(): void {
227
+ try {
228
+ db.close();
229
+ } catch {
230
+ // ignore
231
+ }
232
+ process.exit(0);
233
+ }
234
+
235
+ process.on("SIGINT", shutdown);
236
+ process.on("SIGTERM", shutdown);
@@ -0,0 +1,72 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { openDb, resolveDbPath } from "./db";
3
+ import { addObservation } from "./repo";
4
+
5
+ const args = process.argv.slice(2);
6
+ function arg(name: string, fallback: string): string {
7
+ const index = args.indexOf(`--${name}`);
8
+ const value = args[index + 1];
9
+ return index >= 0 && value ? value : fallback;
10
+ }
11
+
12
+ const fromPath = arg("from", "");
13
+ const dbPath = arg("db", resolveDbPath());
14
+
15
+ if (!fromPath) {
16
+ console.error("Usage: bun migrate-legacy-db.ts --from <old/memory.db> [--db <new/memory.db>]");
17
+ process.exit(1);
18
+ }
19
+
20
+ const source = new Database(fromPath, { readonly: true });
21
+ source.run("PRAGMA busy_timeout = 5000");
22
+ const target = openDb(dbPath);
23
+
24
+ const rows = source
25
+ .query<
26
+ {
27
+ project: string;
28
+ type: string;
29
+ title: string;
30
+ body: string | null;
31
+ files: string;
32
+ concepts: string;
33
+ source: string;
34
+ created_at: string;
35
+ },
36
+ []
37
+ >(
38
+ `SELECT project, type, title, coalesce(body, '') AS body, files, concepts, source, created_at
39
+ FROM observations ORDER BY created_at`,
40
+ )
41
+ .all();
42
+
43
+ function parseArray(value: string): string[] {
44
+ try {
45
+ const parsed = JSON.parse(value);
46
+ return Array.isArray(parsed) ? parsed.map(String) : [];
47
+ } catch {
48
+ return [];
49
+ }
50
+ }
51
+
52
+ let inserted = 0;
53
+ let dup = 0;
54
+ for (const row of rows) {
55
+ const result = addObservation(target, {
56
+ project: row.project,
57
+ type: row.type,
58
+ title: row.title,
59
+ body: row.body ?? "",
60
+ files: parseArray(row.files),
61
+ concepts: parseArray(row.concepts),
62
+ source: row.source === "agent" ? "agent" : "import",
63
+ createdAt: row.created_at,
64
+ });
65
+ if (result.inserted) inserted += 1;
66
+ else dup += 1;
67
+ }
68
+
69
+ source.close();
70
+ target.close();
71
+
72
+ console.log(JSON.stringify({ from: fromPath, to: dbPath, rows: rows.length, inserted, dup }, null, 2));
package/src/plugin.ts ADDED
@@ -0,0 +1,335 @@
1
+ import { basename } from "node:path";
2
+ import { localDate, localStamp } from "./time";
3
+ import { openDb, resolveDbPath } from "./db";
4
+ import {
5
+ addObservation,
6
+ addPrompt,
7
+ ensureSession,
8
+ getObservations,
9
+ recentObservations,
10
+ searchObservations,
11
+ stats,
12
+ touchSessionFiles,
13
+ } from "./repo";
14
+
15
+ type AnyContext = {
16
+ location?: { directory?: string; workspaceID?: string };
17
+ event?: { subscribe(options: { signal: AbortSignal }): AsyncIterable<any> };
18
+ session?: { hook(name: string, handler: (event: any) => unknown): Promise<unknown> };
19
+ tool?: {
20
+ transform(callback: (editor: any) => void): Promise<unknown>;
21
+ hook?(name: string, handler: (event: any) => unknown): Promise<unknown>;
22
+ };
23
+ };
24
+
25
+ const EDIT_TOOLS = new Set(["edit", "write", "patch", "multiedit", "apply_patch"]);
26
+
27
+ function collectFiles(input: unknown): string[] {
28
+ if (!input || typeof input !== "object") return [];
29
+ const record = input as Record<string, unknown>;
30
+ const files: string[] = [];
31
+ for (const key of ["filePath", "file_path", "path", "filename"]) {
32
+ const value = record[key];
33
+ if (typeof value === "string" && value.length > 0) files.push(value);
34
+ }
35
+ if (Array.isArray(record.edits)) {
36
+ for (const edit of record.edits) {
37
+ if (edit && typeof edit === "object") {
38
+ const value = (edit as Record<string, unknown>).filePath;
39
+ if (typeof value === "string" && value.length > 0) files.push(value);
40
+ }
41
+ }
42
+ }
43
+ return [...new Set(files)];
44
+ }
45
+
46
+ function formatContext(project: string, rows: ReturnType<typeof recentObservations>): string {
47
+ if (rows.length === 0) return "";
48
+ const lines = rows.map((row) => {
49
+ let files: string[] = [];
50
+ try {
51
+ const parsed = JSON.parse(row.files);
52
+ if (Array.isArray(parsed)) files = parsed.map((file) => basename(String(file))).slice(0, 3);
53
+ } catch {
54
+ files = [];
55
+ }
56
+ const suffix = files.length > 0 ? ` — ${files.join(", ")}` : "";
57
+ return `- ${localDate(row.created_at)} [${row.type}] ${row.title}${suffix}`;
58
+ });
59
+ return [
60
+ `<memory project="${project}">`,
61
+ "Catatan tersimpan dari sesi sebelumnya. Pakai memory_search untuk mencari, memory_get untuk teks lengkap.",
62
+ ...lines,
63
+ "</memory>",
64
+ ].join("\n");
65
+ }
66
+
67
+ export default {
68
+ id: "memory",
69
+ async setup(ctx: AnyContext) {
70
+ const directory = ctx.location?.directory ?? process.cwd();
71
+ const project = process.env.MEMORY_PROJECT || basename(directory);
72
+
73
+ let db: ReturnType<typeof openDb>;
74
+ try {
75
+ db = openDb(resolveDbPath(directory));
76
+ } catch (error) {
77
+ console.error("[memory] gagal membuka database:", error);
78
+ return () => {};
79
+ }
80
+
81
+ const delivered = new Set<string>();
82
+ const controller = new AbortController();
83
+
84
+ const safe = async <T>(label: string, run: () => T | Promise<T>, fallback: T): Promise<T> => {
85
+ try {
86
+ return await run();
87
+ } catch (error) {
88
+ console.error(`[memory] ${label}:`, error);
89
+ return fallback;
90
+ }
91
+ };
92
+
93
+ if (ctx.tool?.transform && process.env.MEMORY_TOOLS !== "off") {
94
+ const registered = await safe<unknown>(
95
+ "register tools",
96
+ () =>
97
+ ctx.tool!.transform((editor) => {
98
+ editor.add({
99
+ name: "memory_note",
100
+ description:
101
+ "Simpan catatan permanen untuk project ini: keputusan, bugfix, aturan bisnis, atau temuan wiring. Tulis singkat dan spesifik. Panggil setelah tugas selesai atau saat menemukan hal yang layak diingat sesi berikutnya.",
102
+ input: {
103
+ type: "object",
104
+ properties: {
105
+ title: { type: "string", description: "Judul satu baris, maksimal 120 karakter." },
106
+ body: {
107
+ type: "string",
108
+ description: "Penjelasan: masalah, keputusan, alasan, dan file terkait.",
109
+ },
110
+ type: {
111
+ type: "string",
112
+ enum: [
113
+ "decision",
114
+ "bugfix",
115
+ "feature",
116
+ "refactor",
117
+ "security_note",
118
+ "note",
119
+ ],
120
+ description: "Jenis catatan. Default note.",
121
+ },
122
+ files: {
123
+ type: "array",
124
+ items: { type: "string" },
125
+ description: "Path file yang relevan.",
126
+ },
127
+ concepts: {
128
+ type: "array",
129
+ items: { type: "string" },
130
+ description: "Tag konsep singkat.",
131
+ },
132
+ },
133
+ required: ["title", "body"],
134
+ additionalProperties: false,
135
+ },
136
+ execute: async (input: any) => {
137
+ const result = addObservation(db, {
138
+ project,
139
+ title: String(input?.title ?? ""),
140
+ body: String(input?.body ?? ""),
141
+ type: typeof input?.type === "string" ? input.type : "note",
142
+ files: Array.isArray(input?.files) ? input.files.map(String) : [],
143
+ concepts: Array.isArray(input?.concepts) ? input.concepts.map(String) : [],
144
+ source: "agent",
145
+ });
146
+ return {
147
+ content: result.inserted
148
+ ? `Catatan tersimpan sebagai #${result.id}.`
149
+ : `Catatan identik sudah ada sebagai #${result.id}.`,
150
+ };
151
+ },
152
+ });
153
+
154
+ editor.add({
155
+ name: "memory_search",
156
+ description:
157
+ "Cari catatan memory project ini dengan FTS. Mengembalikan index ringkas berisi id, tanggal, tipe, dan judul. Pakai memory_get untuk isi lengkap.",
158
+ input: {
159
+ type: "object",
160
+ properties: {
161
+ query: { type: "string", description: "Kata kunci pencarian." },
162
+ limit: { type: "number", description: "Jumlah hasil, default 10, maksimal 50." },
163
+ type: {
164
+ type: "string",
165
+ description: "Filter tipe, misalnya decision atau bugfix.",
166
+ },
167
+ },
168
+ required: ["query"],
169
+ additionalProperties: false,
170
+ },
171
+ execute: async (input: any) => {
172
+ const rows = searchObservations(db, {
173
+ project,
174
+ query: String(input?.query ?? ""),
175
+ limit: Number(input?.limit ?? 10),
176
+ type: typeof input?.type === "string" ? input.type : undefined,
177
+ });
178
+ if (rows.length === 0) return { content: "Tidak ada catatan yang cocok." };
179
+ const lines = rows.map((row) => {
180
+ const snip = row.snip ? ` | ${row.snip.replace(/\s+/g, " ").slice(0, 160)}` : "";
181
+ return `#${row.id} · ${localDate(row.created_at)} · ${row.type} · ${row.title}${snip}`;
182
+ });
183
+ return { content: lines.join("\n") };
184
+ },
185
+ });
186
+
187
+ editor.add({
188
+ name: "memory_get",
189
+ description:
190
+ "Ambil isi lengkap satu atau beberapa catatan memory berdasarkan id hasil memory_search.",
191
+ input: {
192
+ type: "object",
193
+ properties: {
194
+ ids: {
195
+ type: "array",
196
+ items: { type: "number" },
197
+ description: "Daftar id catatan.",
198
+ },
199
+ },
200
+ required: ["ids"],
201
+ additionalProperties: false,
202
+ },
203
+ execute: async (input: any) => {
204
+ const ids = Array.isArray(input?.ids)
205
+ ? input.ids.map((id: unknown) => Number(id)).filter(Number.isFinite)
206
+ : [];
207
+ const rows = getObservations(db, ids);
208
+ if (rows.length === 0) return { content: "Catatan tidak ditemukan." };
209
+ const blocks = rows.map((row) =>
210
+ [
211
+ `# ${row.title} (#${row.id})`,
212
+ `Tanggal: ${localStamp(row.created_at)} · Tipe: ${row.type}`,
213
+ row.files.length > 0 ? `File: ${row.files.join(", ")}` : "",
214
+ "",
215
+ row.body,
216
+ ]
217
+ .filter(Boolean)
218
+ .join("\n"),
219
+ );
220
+ return { content: blocks.join("\n\n---\n\n") };
221
+ },
222
+ });
223
+
224
+ editor.add({
225
+ name: "memory_stats",
226
+ description: "Ringkasan isi memory project ini: jumlah catatan, prompt, sesi, dan tanggal catatan terakhir.",
227
+ input: { type: "object", properties: {}, additionalProperties: false },
228
+ execute: async () => {
229
+ const value = stats(db, project);
230
+ return {
231
+ content: `Project ${project}: ${value.observations} catatan, ${value.prompts} prompt, ${value.sessions} sesi. Catatan terakhir: ${value.lastObservation ? localStamp(value.lastObservation) : "belum ada"}.`,
232
+ };
233
+ },
234
+ });
235
+ }),
236
+ null,
237
+ );
238
+ if (registered === null) {
239
+ try {
240
+ db.close();
241
+ } catch {
242
+ // ignore
243
+ }
244
+ return () => {};
245
+ }
246
+ }
247
+
248
+ if (ctx.session?.hook) {
249
+ await safe(
250
+ "context hook",
251
+ () =>
252
+ ctx.session!.hook("context", async (event: any) => {
253
+ const sessionID = String(event?.sessionID ?? "");
254
+ if (!sessionID || delivered.has(sessionID)) return;
255
+ try {
256
+ const rows = recentObservations(db, project, 8);
257
+ const text = formatContext(project, rows);
258
+ if (!text || !Array.isArray(event.system)) return;
259
+ event.system.push({ type: "text", text });
260
+ delivered.add(sessionID);
261
+ } catch (error) {
262
+ console.error("[memory] context gagal:", error);
263
+ }
264
+ }),
265
+ null,
266
+ );
267
+
268
+ await safe(
269
+ "prompt hook",
270
+ () =>
271
+ ctx.session!.hook("prompt", async (event: any) => {
272
+ const sessionID = String(event?.sessionID ?? "");
273
+ const text = typeof event?.prompt?.text === "string" ? event.prompt.text : "";
274
+ if (!sessionID || !text) return;
275
+ try {
276
+ ensureSession(db, { id: sessionID, project, directory });
277
+ addPrompt(db, { sessionID, project, body: text });
278
+ } catch (error) {
279
+ console.error("[memory] prompt gagal:", error);
280
+ }
281
+ }),
282
+ null,
283
+ );
284
+ }
285
+
286
+ if (ctx.tool?.hook) {
287
+ await safe(
288
+ "tool hook",
289
+ () =>
290
+ ctx.tool!.hook!("execute.after", async (event: any) => {
291
+ const sessionID = String(event?.sessionID ?? "");
292
+ if (!sessionID || event?.status !== "completed") return;
293
+ const tool = String(event?.tool ?? "");
294
+ if (!EDIT_TOOLS.has(tool)) return;
295
+ try {
296
+ const files = collectFiles(event?.input);
297
+ touchSessionFiles(db, sessionID, files);
298
+ } catch (error) {
299
+ console.error("[memory] tool hook gagal:", error);
300
+ }
301
+ }),
302
+ null,
303
+ );
304
+ }
305
+
306
+ if (ctx.event?.subscribe) {
307
+ void (async () => {
308
+ try {
309
+ for await (const event of ctx.event!.subscribe({ signal: controller.signal })) {
310
+ const sessionID = event?.data?.sessionID;
311
+ if (typeof sessionID !== "string" || !sessionID) continue;
312
+ if (event.type === "session.created") {
313
+ ensureSession(db, { id: sessionID, project, directory });
314
+ } else if (event.type === "session.deleted") {
315
+ delivered.delete(sessionID);
316
+ } else if (event.type === "session.compaction.ended" || event.type === "session.compacted") {
317
+ delivered.delete(sessionID);
318
+ }
319
+ }
320
+ } catch {
321
+ // stream closed; nothing to do
322
+ }
323
+ })();
324
+ }
325
+
326
+ return () => {
327
+ controller.abort();
328
+ try {
329
+ db.close();
330
+ } catch {
331
+ // ignore
332
+ }
333
+ };
334
+ },
335
+ };
@@ -0,0 +1,27 @@
1
+ import { openDb, resolveDbPath } from "./db";
2
+ import { redactSecrets } from "./redact";
3
+
4
+ const db = openDb(process.argv[2] ?? resolveDbPath());
5
+
6
+ const rows = db
7
+ .query<{ id: number; body: string }, []>("SELECT id, body FROM prompts")
8
+ .all();
9
+
10
+ let updated = 0;
11
+ db.transaction(() => {
12
+ for (const row of rows) {
13
+ const next = redactSecrets(row.body);
14
+ if (next === row.body) continue;
15
+ db.run("UPDATE prompts SET body = ? WHERE id = ?", [next, row.id]);
16
+ updated += 1;
17
+ }
18
+ })();
19
+
20
+ console.log(
21
+ JSON.stringify(
22
+ { db: process.argv[2] ?? resolveDbPath(), scanned: rows.length, redacted: updated },
23
+ null,
24
+ 2,
25
+ ),
26
+ );
27
+ db.close();
package/src/redact.ts ADDED
@@ -0,0 +1,26 @@
1
+ const PATTERNS: Array<[RegExp, string]> = [
2
+ [/sk-[A-Za-z0-9_-]{20,}/g, "sk-***"],
3
+ [/gh[pousr]_[A-Za-z0-9]{20,}/g, "gh*_***"],
4
+ [/AKIA[0-9A-Z]{16}/g, "AKIA***"],
5
+ [/https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/]+/g, "https://hooks.slack.com/services/***"],
6
+ [/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g, "https://discord.com/api/webhooks/***"],
7
+ [/xox[baprs]-[A-Za-z0-9-]+/g, "xox*-***"],
8
+ [/AIza[0-9A-Za-z_-]{35}/g, "AIza***"],
9
+ [/Authorization:\s*Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Authorization: Bearer ***"],
10
+ [
11
+ /(\b[A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|ACCESS_KEY|PRIVATE_KEY)[A-Z0-9_]*\s*[:=]\s*["']?)[^\s"',]{6,}/gi,
12
+ "$1***",
13
+ ],
14
+ [
15
+ /(?<=\b(password|passwd|secret|token|api[_-]?key)\b\s*[:=]\s*["']?)[^\s"',]{6,}/gi,
16
+ "***",
17
+ ],
18
+ ];
19
+
20
+ export function redactSecrets(text: string): string {
21
+ let value = text;
22
+ for (const [pattern, replacement] of PATTERNS) {
23
+ value = value.replace(pattern, replacement);
24
+ }
25
+ return value;
26
+ }