@oalo-ai/cli 0.7.0 → 0.9.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.
@@ -0,0 +1,321 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+
6
+ /**
7
+ * Client-side PII anonymization and free-text scrubbing.
8
+ *
9
+ * Everything here runs locally in the CLI process BEFORE any record or
10
+ * transcript line leaves the user's machine.
11
+ *
12
+ * Modes:
13
+ * - pseudonymize (default): deterministic HMAC-SHA256 replacement using a
14
+ * local salt file (0600) so cross-table joins stay intact without raw PII.
15
+ * - mask: shape-preserving redaction (e.g. a***@clinic.org, ***-***-5309).
16
+ * - drop: remove matching PII columns completely before upload.
17
+ * - scrub: redact inline PII (SSN, Luhn credit cards, emails, phones, IPv4)
18
+ * inside free-text fields while leaving structure intact.
19
+ */
20
+
21
+ export const VALID_MODES = ["pseudonymize", "mask", "drop", "scrub"];
22
+
23
+ export const DEFAULT_PII_FIELDS = new Set([
24
+ "email",
25
+ "email_address",
26
+ "phone",
27
+ "phone_number",
28
+ "mobile",
29
+ "ssn",
30
+ "social_security",
31
+ "social_security_number",
32
+ "dob",
33
+ "date_of_birth",
34
+ "birth_date",
35
+ "address",
36
+ "street",
37
+ "street_address",
38
+ "postal_code",
39
+ "zip",
40
+ "zip_code",
41
+ "ip",
42
+ "ip_address",
43
+ "card_number",
44
+ "credit_card",
45
+ "tax_id",
46
+ "tin",
47
+ "ein",
48
+ "national_id",
49
+ "passport",
50
+ "drivers_license",
51
+ ]);
52
+
53
+ const EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
54
+ const SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/g;
55
+ const CARD_RE = /\b(?:\d[ -]*?){13,19}\b/g;
56
+ const PHONE_RE = /(?<!\w)(?:\+?\d{1,3}[\s.-]?)?(?:\(\d{3}\)|\d{3})[\s.-]\d{3}[\s.-]\d{4}(?!\w)/g;
57
+ const IPV4_RE = /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g;
58
+
59
+ /** Standard Luhn checksum validation for credit card numbers. */
60
+ export function isLuhnValid(input) {
61
+ const digits = String(input || "").replace(/\D/g, "");
62
+ if (digits.length < 13 || digits.length > 19) return false;
63
+ let sum = 0;
64
+ let alt = false;
65
+ for (let i = digits.length - 1; i >= 0; i--) {
66
+ let n = digits.charCodeAt(i) - 48;
67
+ if (alt) {
68
+ n *= 2;
69
+ if (n > 9) n -= 9;
70
+ }
71
+ sum += n;
72
+ alt = !alt;
73
+ }
74
+ return sum % 10 === 0;
75
+ }
76
+
77
+ /**
78
+ * Deterministically scrub inline PII spans from free text.
79
+ * Passing the same `vault` across lines keeps token assignments consistent
80
+ * (`[EMAIL_1]` stays `[EMAIL_1]` for the whole call or import).
81
+ */
82
+ export function scrubText(text, vault = null) {
83
+ if (typeof text !== "string" || !text) {
84
+ return { text: text ?? "", vault: vault || createVault(), replacements: 0 };
85
+ }
86
+
87
+ const v = vault || createVault();
88
+ let replacements = 0;
89
+
90
+ const tokenFor = (prefix, raw) => {
91
+ const key = `${prefix}:${raw}`;
92
+ if (v.reverse.has(key)) return v.reverse.get(key);
93
+ const n = (v.counts[prefix] || 0) + 1;
94
+ v.counts[prefix] = n;
95
+ const tok = `[${prefix}_${n}]`;
96
+ v.reverse.set(key, tok);
97
+ v.tokens[tok] = raw;
98
+ return tok;
99
+ };
100
+
101
+ let out = text;
102
+
103
+ // 1. SSNs first (narrow pattern)
104
+ out = out.replace(SSN_RE, (m) => {
105
+ replacements++;
106
+ return tokenFor("SSN", m);
107
+ });
108
+
109
+ // 2. Credit cards (Luhn-validated to avoid redacting order IDs)
110
+ out = out.replace(CARD_RE, (m) => {
111
+ if (!isLuhnValid(m)) return m;
112
+ replacements++;
113
+ return tokenFor("CARD", m);
114
+ });
115
+
116
+ // 3. Emails
117
+ out = out.replace(EMAIL_RE, (m) => {
118
+ replacements++;
119
+ return tokenFor("EMAIL", m);
120
+ });
121
+
122
+ // 4. Phone numbers
123
+ out = out.replace(PHONE_RE, (m) => {
124
+ replacements++;
125
+ return tokenFor("PHONE", m);
126
+ });
127
+
128
+ // 5. IPv4 addresses
129
+ out = out.replace(IPV4_RE, (m) => {
130
+ replacements++;
131
+ return tokenFor("IP", m);
132
+ });
133
+
134
+ return { text: out, vault: v, replacements };
135
+ }
136
+
137
+ export function createVault() {
138
+ return { tokens: {}, reverse: new Map(), counts: {} };
139
+ }
140
+
141
+ /** Restore scrubbed tokens back into original text using a local vault. */
142
+ export function rehydrateText(text, vault) {
143
+ if (typeof text !== "string" || !vault?.tokens) return text;
144
+ let out = text;
145
+ for (const [tok, raw] of Object.entries(vault.tokens)) {
146
+ out = out.split(tok).join(raw);
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /** Default path for the local-only anonymization HMAC salt. */
152
+ export function defaultSaltPath() {
153
+ const base = process.env.OALO_HOME || join(homedir(), ".oalo");
154
+ return join(base, "anonymize.salt");
155
+ }
156
+
157
+ /**
158
+ * Load an existing local HMAC salt, or generate a fresh 32-byte random salt
159
+ * with mode 0600 on disk. The salt never leaves the local machine.
160
+ */
161
+ export function loadOrCreateSalt(saltFile) {
162
+ const p = saltFile || defaultSaltPath();
163
+ if (existsSync(p)) {
164
+ const val = readFileSync(p, "utf8").trim();
165
+ if (val) return { salt: val, path: p, created: false };
166
+ }
167
+ mkdirSync(dirname(p), { recursive: true });
168
+ const salt = randomBytes(32).toString("hex");
169
+ writeFileSync(p, salt + "\n", { mode: 0o600 });
170
+ return { salt, path: p, created: true };
171
+ }
172
+
173
+ /** Deterministic HMAC-SHA256 pseudonym preserving email/phone shape when applicable. */
174
+ export function pseudonymizeValue(value, field, salt) {
175
+ if (value === null || value === undefined || value === "") return value;
176
+ const raw = String(value).trim();
177
+ const normalized = raw.toLowerCase();
178
+ const fieldKey = String(field || "").toLowerCase();
179
+ const digest = createHmac("sha256", salt).update(`${fieldKey}:${normalized}`).digest("hex").slice(0, 12);
180
+
181
+ if (fieldKey.includes("email") || raw.includes("@")) {
182
+ return `anon_${digest}@redacted.local`;
183
+ }
184
+ if (fieldKey.includes("phone") || fieldKey.includes("mobile")) {
185
+ return `phone_${digest}`;
186
+ }
187
+ return `anon_${digest}`;
188
+ }
189
+
190
+ /** Shape-preserving partial mask (irreversible). */
191
+ export function maskValue(value, field) {
192
+ if (value === null || value === undefined || value === "") return value;
193
+ const raw = String(value).trim();
194
+ const fieldKey = String(field || "").toLowerCase();
195
+
196
+ if (fieldKey.includes("email") || raw.includes("@")) {
197
+ const [local, domain] = raw.split("@");
198
+ if (domain) {
199
+ const head = local.length > 0 ? local[0] : "";
200
+ return `${head}***@${domain}`;
201
+ }
202
+ }
203
+ if (fieldKey.includes("phone") || fieldKey.includes("mobile")) {
204
+ const digits = raw.replace(/\D/g, "");
205
+ if (digits.length >= 4) return `***-***-${digits.slice(-4)}`;
206
+ }
207
+ if (raw.length <= 4) return "***";
208
+ return `***${raw.slice(-4)}`;
209
+ }
210
+
211
+ /**
212
+ * Anonymize an array of plain row objects in memory before upload.
213
+ * Supports flat records (`oalo crm import`) and `{ id, document }` rows (`oalo data push`).
214
+ */
215
+ export function anonymizeRows(rows, opts = {}) {
216
+ const mode = opts.mode || "pseudonymize";
217
+ if (!VALID_MODES.includes(mode)) {
218
+ throw new Error(`--anonymize-mode must be one of ${VALID_MODES.join(", ")} (got ${mode})`);
219
+ }
220
+
221
+ const explicitFields =
222
+ Array.isArray(opts.fields) && opts.fields.length > 0
223
+ ? new Set(opts.fields.map((f) => String(f).trim().toLowerCase()).filter(Boolean))
224
+ : null;
225
+
226
+ const salt = mode === "pseudonymize" ? opts.salt || loadOrCreateSalt(opts.saltFile).salt : null;
227
+ const vault = createVault();
228
+ const fieldsTouched = new Set();
229
+ let valuesTransformed = 0;
230
+
231
+ const shouldTransformKey = (key) => {
232
+ const k = key.toLowerCase();
233
+ if (explicitFields) return explicitFields.has(k);
234
+ return DEFAULT_PII_FIELDS.has(k);
235
+ };
236
+
237
+ const transformObj = (obj) => {
238
+ const next = {};
239
+ for (const [k, v] of Object.entries(obj)) {
240
+ if (mode === "scrub") {
241
+ const target = !explicitFields || explicitFields.has(k.toLowerCase());
242
+ if (target && typeof v === "string") {
243
+ const { text, replacements } = scrubText(v, vault);
244
+ if (replacements > 0) {
245
+ fieldsTouched.add(k);
246
+ valuesTransformed += replacements;
247
+ }
248
+ next[k] = text;
249
+ } else {
250
+ next[k] = v;
251
+ }
252
+ continue;
253
+ }
254
+
255
+ if (!shouldTransformKey(k)) {
256
+ next[k] = v;
257
+ continue;
258
+ }
259
+
260
+ if (mode === "drop") {
261
+ fieldsTouched.add(k);
262
+ valuesTransformed++;
263
+ continue;
264
+ }
265
+
266
+ if (mode === "mask") {
267
+ fieldsTouched.add(k);
268
+ valuesTransformed++;
269
+ next[k] = maskValue(v, k);
270
+ continue;
271
+ }
272
+
273
+ // pseudonymize
274
+ fieldsTouched.add(k);
275
+ valuesTransformed++;
276
+ next[k] = pseudonymizeValue(v, k, salt);
277
+ }
278
+ return next;
279
+ };
280
+
281
+ const out = rows.map((row) => {
282
+ if (row && typeof row === "object" && row.document && typeof row.document === "object" && "id" in row) {
283
+ return { ...row, document: transformObj(row.document) };
284
+ }
285
+ return transformObj(row);
286
+ });
287
+
288
+ return {
289
+ rows: out,
290
+ stats: {
291
+ mode,
292
+ rowsProcessed: out.length,
293
+ fieldsTouched: [...fieldsTouched].sort(),
294
+ valuesTransformed,
295
+ },
296
+ };
297
+ }
298
+
299
+ /** Parse `--anonymize`, `--anonymize-mode`, `--anonymize-fields`, `--salt-file` from CLI flags. */
300
+ export function parseAnonymizeFlags(flags) {
301
+ const enabled =
302
+ !!flags.anonymize ||
303
+ typeof flags["anonymize-mode"] === "string" ||
304
+ typeof flags["anonymize-fields"] === "string";
305
+
306
+ if (!enabled) return null;
307
+
308
+ const mode = typeof flags["anonymize-mode"] === "string" ? flags["anonymize-mode"].trim().toLowerCase() : "pseudonymize";
309
+ if (!VALID_MODES.includes(mode)) {
310
+ throw new Error(`--anonymize-mode must be one of ${VALID_MODES.join(", ")} (got ${mode})`);
311
+ }
312
+
313
+ const fields =
314
+ typeof flags["anonymize-fields"] === "string"
315
+ ? flags["anonymize-fields"].split(",").map((s) => s.trim()).filter(Boolean)
316
+ : [];
317
+
318
+ const saltFile = typeof flags["salt-file"] === "string" ? flags["salt-file"] : undefined;
319
+
320
+ return { mode, fields, saltFile };
321
+ }
@@ -187,6 +187,7 @@ export class ModelRequests {
187
187
  method: "POST",
188
188
  headers: upstreamHeaders(h, this.env, stream ? "text/event-stream" : "application/json"),
189
189
  body: JSON.stringify(body),
190
+ redirect: "error",
190
191
  signal: controller.signal,
191
192
  });
192
193
  } catch (e) {
@@ -297,7 +298,12 @@ export async function discoverModels({ baseUrl, server, only, key, fetchImpl = g
297
298
  const headers = { accept: "application/json" };
298
299
  if (key) headers.authorization = `Bearer ${key}`;
299
300
  const get = async (url, init = {}) => {
300
- const r = await fetchImpl(url, { ...init, headers: { ...headers, ...(init.headers || {}) }, signal: AbortSignal.timeout(timeoutMs) });
301
+ const r = await fetchImpl(url, {
302
+ ...init,
303
+ redirect: "error",
304
+ headers: { ...headers, ...(init.headers || {}) },
305
+ signal: AbortSignal.timeout(timeoutMs),
306
+ });
301
307
  const text = await r.text();
302
308
  if (!r.ok) throw Object.assign(new Error(`${r.status}: ${text.slice(0, 200)}`), { status: r.status });
303
309
  return JSON.parse(text);