leakshield 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/i18n/en.js CHANGED
@@ -4,6 +4,10 @@ export const en = {
4
4
  "scan.unsafe_summary": "🚨 Found {count} potential sensitive item(s) (HIGH: {high}, MEDIUM: {med}, LOW: {low})",
5
5
  "scan.safe_recommendation": "Content looks safe, but please verify there are no business-logic secrets.",
6
6
  "scan.unsafe_recommendation": "⛔ Please address the above sensitive items before sending to AI services. Use placeholder data or remove sensitive fields, then retry.",
7
+ "scan.warning_encoded": "Encoded content: {types}",
8
+ "scan.warning_truncated": "Content truncated",
9
+ "scan.warning_zero_width": "Zero-width characters",
10
+ "scan.warning_suspicious_unicode": "Suspicious Unicode",
7
11
  // engine — redact
8
12
  "redact.safe_summary": "✅ No sensitive content detected, nothing to redact.",
9
13
  "redact.unsafe_summary": "🔒 Redacted {count} sensitive item(s).",
@@ -4,6 +4,10 @@ export const zhTW = {
4
4
  "scan.unsafe_summary": "🚨 發現 {count} 個潛在敏感項目(HIGH: {high}, MEDIUM: {med}, LOW: {low})",
5
5
  "scan.safe_recommendation": "內容看起來安全,但仍請確認沒有業務邏輯上的機密資訊。",
6
6
  "scan.unsafe_recommendation": "⛔ 建議先處理上述敏感項目後再傳送給 AI 服務。請用假資料、佔位符或移除敏感欄位後再重試。",
7
+ "scan.warning_encoded": "編碼檢測: {types}",
8
+ "scan.warning_truncated": "內容截斷",
9
+ "scan.warning_zero_width": "零寬字符",
10
+ "scan.warning_suspicious_unicode": "可疑 Unicode",
7
11
  // engine — redact
8
12
  "redact.safe_summary": "✅ 未偵測到敏感內容,無需脫敏。",
9
13
  "redact.unsafe_summary": "🔒 已脫敏 {count} 個敏感項目。",
package/dist/index.js CHANGED
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * - OpenCode v2 resolves the package `main` (or `<dir>/index.js` when the dist
5
5
  * directory is configured directly) to this file.
6
- * - The default export is the dual-version plugin definition: v2 hosts read
7
- * `id` + `setup(ctx)`, v1 hosts (1.18.29+) call `server(input, options)`.
6
+ * - The default export is the OpenCode v2 plugin definition (`id` +
7
+ * `setup(ctx)`). Its `server` export is a fail-closed stub for v1 hosts,
8
+ * which are no longer supported.
8
9
  *
9
10
  * The CLI/web entrypoint lives in `./cli.js` (published as the `leakshield`
10
11
  * bin) so importing this module never starts an interactive process.
@@ -78,81 +78,6 @@ function readCompareArgs(input) {
78
78
  ? { left_file_id, left_key, right_file_id, right_key }
79
79
  : undefined;
80
80
  }
81
- // ─── OpenCode v1 ─────────────────────────────────────────────────────────────
82
- /** Builds the v1 tool map for `Hooks["tool"]` when `envQueries` is enabled. */
83
- export async function createV1EnvTools(service) {
84
- // Runtime dependency on the v1 SDK's tool helper; loaded dynamically so a
85
- // v2 host never needs the v1 SDK package. A v1 host always provides it.
86
- const { tool } = await import("@opencode-ai/plugin/tool");
87
- const z = tool.schema;
88
- const guardEnvList = tool({
89
- description: LIST_DESCRIPTION,
90
- args: {},
91
- async execute(_args, context) {
92
- return {
93
- title: "guard_env_list",
94
- output: JSON.stringify(safePayload(() => listPayload(service, context.sessionID))),
95
- };
96
- },
97
- });
98
- const guardEnvInspect = tool({
99
- description: INSPECT_DESCRIPTION,
100
- args: {
101
- file_id: z
102
- .string()
103
- .min(1)
104
- .max(MAX_FILE_ID_LENGTH)
105
- .describe("Session-local file id issued by guard_env_list."),
106
- key: z
107
- .string()
108
- .min(1)
109
- .max(MAX_KEY_NAME_LENGTH)
110
- .describe("Key name as listed by guard_env_list."),
111
- },
112
- async execute(args, context) {
113
- return {
114
- title: "guard_env_inspect",
115
- output: JSON.stringify(safePayload(() => inspectPayload(service, context.sessionID, args.file_id, args.key))),
116
- };
117
- },
118
- });
119
- const guardEnvCompare = tool({
120
- description: COMPARE_DESCRIPTION,
121
- args: {
122
- left_file_id: z
123
- .string()
124
- .min(1)
125
- .max(MAX_FILE_ID_LENGTH)
126
- .describe("Session-local file id of the left operand."),
127
- left_key: z
128
- .string()
129
- .min(1)
130
- .max(MAX_KEY_NAME_LENGTH)
131
- .describe("Key name of the left operand."),
132
- right_file_id: z
133
- .string()
134
- .min(1)
135
- .max(MAX_FILE_ID_LENGTH)
136
- .describe("Session-local file id of the right operand."),
137
- right_key: z
138
- .string()
139
- .min(1)
140
- .max(MAX_KEY_NAME_LENGTH)
141
- .describe("Key name of the right operand."),
142
- },
143
- async execute(args, context) {
144
- return {
145
- title: "guard_env_compare",
146
- output: JSON.stringify(safePayload(() => comparePayload(service, context.sessionID, { fileId: args.left_file_id, key: args.left_key }, { fileId: args.right_file_id, key: args.right_key }))),
147
- };
148
- },
149
- });
150
- return {
151
- guard_env_list: guardEnvList,
152
- guard_env_inspect: guardEnvInspect,
153
- guard_env_compare: guardEnvCompare,
154
- };
155
- }
156
81
  // ─── OpenCode v2 ─────────────────────────────────────────────────────────────
157
82
  /**
158
83
  * Registers the env query tools on an OpenCode v2 plugin context via
@@ -1,78 +1,9 @@
1
- import { ContentHashCache, protectUnknownStrings, } from "./decision/ingress.js";
2
1
  const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
3
- function blockedAttachment(part) {
4
- return {
5
- id: part.id,
6
- sessionID: part.sessionID,
7
- messageID: part.messageID,
8
- type: "text",
9
- text: "[LeakShield blocked an attachment: its content cannot be scanned, so it was not sent.]",
10
- synthetic: true,
11
- };
12
- }
13
- function protectParts(parts, config, mode, protector) {
14
- return parts.map((part) => {
15
- if (part.type === "file")
16
- return blockedAttachment(part);
17
- if (part.type === "text") {
18
- const protectedText = protector(part.text, config, { mode, context: "message text" });
19
- return { ...part, text: protectedText.text };
20
- }
21
- if (part.type === "reasoning") {
22
- const protectedText = protector(part.text, config, { mode, context: "reasoning text" });
23
- return { ...part, text: protectedText.text };
24
- }
25
- if (part.type === "tool") {
26
- return {
27
- ...part,
28
- state: protectUnknownStrings(part.state, config, { mode, context: "tool history" }, protector),
29
- };
30
- }
31
- if (part.type === "subtask") {
32
- const protectedPrompt = protector(part.prompt, config, { mode, context: "subtask prompt" });
33
- const protectedDescription = protector(part.description, config, { mode, context: "subtask description" });
34
- return { ...part, prompt: protectedPrompt.text, description: protectedDescription.text };
35
- }
36
- if (part.type === "retry") {
37
- return {
38
- ...part,
39
- error: protectUnknownStrings(part.error, config, { mode, context: "retry error" }, protector),
40
- };
41
- }
42
- return part;
43
- });
44
- }
45
- export function createHooks(config, mode) {
46
- const cache = new ContentHashCache();
47
- const protectWithCache = (text, currentConfig, options) => cache.protect(text, currentConfig, options);
48
- return {
49
- "chat.message": async (_input, output) => {
50
- output.parts.splice(0, output.parts.length, ...protectParts(output.parts, config, mode, protectWithCache));
51
- },
52
- "tool.execute.after": async (_input, output) => {
53
- const protectedTitle = protectWithCache(output.title, config, { mode, context: "tool title" });
54
- const protectedOutput = protectWithCache(output.output, config, { mode, context: "tool output" });
55
- output.title = protectedTitle.text;
56
- output.output = protectedOutput.text;
57
- output.metadata = protectUnknownStrings(output.metadata, config, { mode, context: "tool metadata" }, protectWithCache);
58
- },
59
- "experimental.chat.messages.transform": async (_input, output) => {
60
- for (const message of output.messages) {
61
- message.parts.splice(0, message.parts.length, ...protectParts(message.parts, config, mode, protectWithCache));
62
- }
63
- },
64
- "experimental.chat.system.transform": async (_input, output) => {
65
- output.system.splice(0, output.system.length, ...output.system.map((text) => protectWithCache(text, config, { mode, context: "system prompt" }).text));
66
- },
67
- "tool.definition": async (_input, output) => {
68
- output.description = protectWithCache(output.description, config, { mode, context: "tool description" }).text;
69
- output.parameters = protectUnknownStrings(output.parameters, config, { mode, context: "tool parameters" }, protectWithCache);
70
- },
71
- };
72
- }
73
- export function createFailClosedHooks() {
2
+ /** Hooks that reject every model request. `message` names the reason shown to
3
+ * the user; the default is the generic initialization failure. */
4
+ export function createFailClosedHooks(message = INITIALIZATION_ERROR) {
74
5
  const blockRequest = async () => {
75
- throw new Error(INITIALIZATION_ERROR);
6
+ throw new Error(message);
76
7
  };
77
8
  return {
78
9
  "chat.message": blockRequest,
@@ -63,6 +63,21 @@ function toolRestoreError(reason) {
63
63
  return TOOL_RESTORE_LIMIT_ERROR;
64
64
  return TOOL_REFUSAL_ERROR;
65
65
  }
66
+ /**
67
+ * Refusal text for a failed masking preparation. The marker stays static —
68
+ * stage plus reason code, never content — because the refused value may be
69
+ * exactly what must not be echoed. `truncated_content` additionally names the
70
+ * scanner bound and the two ways out, so the bound is visible instead of a
71
+ * dead end (issue #47). Masked text is rescanned and tokens can be longer than
72
+ * what they replace, so a string under the bound can still exceed it.
73
+ */
74
+ function prepareMaskError(reason, config) {
75
+ const marker = `${PROTECT_FAILED_ERROR} [stage=prepare.mask reason=${reason}]`;
76
+ if (reason !== "truncated_content")
77
+ return marker;
78
+ const maxChars = config.settings.max_chars;
79
+ return `${marker} A string, before or after masking, exceeded settings.max_chars (${maxChars}). Raise settings.max_chars or split the content.`;
80
+ }
66
81
  /** Shell syntax excluded from unquoted literal words. Known tokens are
67
82
  * removed before this check; a token-shaped prefix alone grants no exemption. */
68
83
  const UNSUPPORTED_SHELL_SYNTAX = /[\x00-\x1f\x7f'"`\\$;|&<>(){}*?\[\]!~#]/;
@@ -1106,7 +1121,7 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1106
1121
  const protectTree = (input) => {
1107
1122
  const masked = pseudonymizer.protectJsonForModel(sessionID, input);
1108
1123
  if (!masked.ok)
1109
- throw new Error(`${PROTECT_FAILED_ERROR} [stage=prepare.mask reason=${masked.reason}]`);
1124
+ throw new Error(prepareMaskError(masked.reason, config));
1110
1125
  if (!isRecordLike(masked.value))
1111
1126
  throw new Error(PROTECT_FAILED_ERROR);
1112
1127
  return masked.value;
package/dist/opencode.js CHANGED
@@ -2,8 +2,7 @@ import { findConfigPath, loadConfigWithFingerprint } from "./config/loader.js";
2
2
  import { createSessionKey } from "./decision/deidentify.js";
3
3
  import { defaultStorePath } from "./decision/mapping-key.js";
4
4
  import { EnvQueryService } from "./env-queries.js";
5
- import { createFailClosedHooks, createHooks } from "./opencode-hooks.js";
6
- import { createV1EnvTools } from "./opencode-env-tools.js";
5
+ import { createFailClosedHooks } from "./opencode-hooks.js";
7
6
  import { createFailClosedV2Setup, createV2Setup } from "./opencode-v2.js";
8
7
  import { createFailClosedTransparentGuard, createTransparentSessionGuard } from "./opencode-transparent.js";
9
8
  import { PluginOptionsSchema, withDefaultMode } from "./plugin-options.js";
@@ -34,27 +33,17 @@ function createEnvQueryService(options, workspaceRoot, loaded) {
34
33
  configFingerprint: loaded.fingerprint,
35
34
  });
36
35
  }
37
- function getWorkspaceRoot(input) {
38
- if (typeof input !== "object" || input === null)
39
- return process.cwd();
40
- const context = input;
41
- if (typeof context.worktree === "string")
42
- return context.worktree;
43
- if (typeof context.directory === "string")
44
- return context.directory;
45
- return process.cwd();
46
- }
47
36
  /** Whether the raw v2 plugin options select transparent mode, explicitly or
48
37
  * by omitting `mode` (the v2 default), even if the options are invalid. */
49
38
  function rawModeIsTransparent(options) {
50
- const resolved = withDefaultMode(options, "v2");
39
+ const resolved = withDefaultMode(options);
51
40
  return (typeof resolved === "object" &&
52
41
  resolved !== null &&
53
42
  resolved.mode === "transparent");
54
43
  }
55
44
  const v2Setup = async (ctx) => {
56
45
  try {
57
- const options = PluginOptionsSchema.parse(withDefaultMode(ctx.options, "v2"));
46
+ const options = PluginOptionsSchema.parse(withDefaultMode(ctx.options));
58
47
  const loaded = loadConfigWithFingerprint(options.configPath, ctx.location.directory);
59
48
  const config = withEncodingDetection(loaded.config);
60
49
  if (options.mode === "transparent") {
@@ -125,47 +114,16 @@ const v2Setup = async (ctx) => {
125
114
  await createFailClosedV2Setup()(ctx);
126
115
  }
127
116
  };
128
- const v1Server = async (input, rawOptions) => {
129
- try {
130
- const options = PluginOptionsSchema.parse(withDefaultMode(rawOptions, "v1"));
131
- if (options.deidentify) {
132
- // v1 has no de-identification pipeline; the shared options schema now
133
- // includes the flag, so v1 must explicitly reject it. The throw lands in
134
- // the catch below → fail-closed hooks.
135
- throw new Error("deidentify is only supported on OpenCode v2");
136
- }
137
- if (options.mode === "transparent") {
138
- // v1 has no native transport hooks to remask the final wire or restore
139
- // responses, so transparent mode cannot honor its contract there. The
140
- // throw lands in the catch below → fail-closed hooks.
141
- throw new Error("transparent mode is only supported on OpenCode v2");
142
- }
143
- const workspaceRoot = getWorkspaceRoot(input);
144
- const loaded = loadConfigWithFingerprint(options.configPath, workspaceRoot);
145
- const config = withEncodingDetection(loaded.config);
146
- const hooks = createHooks(config, options.mode);
147
- const envQueries = createEnvQueryService(options, workspaceRoot, loaded);
148
- if (!envQueries)
149
- return hooks;
150
- try {
151
- return { ...hooks, tool: await createV1EnvTools(envQueries) };
152
- }
153
- catch {
154
- // The opt-in env query tools failed to load on their own (e.g. a
155
- // missing v1 SDK module on an incomplete install). Only the feature
156
- // fails: the full protection hooks above stay exactly as armed as
157
- // they would be with envQueries off — no fail-closed downgrade, no
158
- // protection gap, no env tools.
159
- return hooks;
160
- }
161
- }
162
- catch {
163
- return createFailClosedHooks();
164
- }
165
- };
117
+ const V1_UNSUPPORTED = "LeakShield no longer supports OpenCode v1, so the request was blocked before anything was sent. Upgrade to OpenCode v2.";
118
+ /**
119
+ * OpenCode v1 is not supported. This stub exists only so a v1 host that still
120
+ * loads the package aborts every model request instead of running unprotected.
121
+ * It must not throw: a host could swallow the error and carry on with no guard.
122
+ */
123
+ const v1Server = async () => createFailClosedHooks(V1_UNSUPPORTED);
166
124
  /**
167
- * Dual-version OpenCode plugin entry. OpenCode v2 reads `id` and `setup(ctx)`;
168
- * OpenCode v1 (1.18.29+) calls `server(input, options)` and uses the returned hooks.
125
+ * OpenCode plugin entry. OpenCode v2 reads `id` and `setup(ctx)`. `server` is
126
+ * the fail-closed stub for v1 hosts (1.18.29+), which call `server(input, options)`.
169
127
  */
170
128
  const leakshieldPlugin = {
171
129
  id: "leakshield",
@@ -4,17 +4,18 @@
4
4
  * host loaders) and the install doctor (src/doctor.ts).
5
5
  */
6
6
  import { z } from "zod";
7
- // deidentify is v2-only and valid only in redact mode; an invalid combination
7
+ import { plainObject } from "./config/plain-object.js";
8
+ // deidentify is valid only in redact mode; an invalid combination
8
9
  // makes the parse throw, and every entry path already fails closed on that.
9
- // transparent is the v2-only reversible pseudonymization mode (issue #22):
10
+ // transparent is the reversible pseudonymization mode (issue #22):
10
11
  // it owns its own bounded session service and transport hooks, so combining
11
- // it with the second (deidentify) protection pipeline or the v1/v2 env query
12
+ // it with the second (deidentify) protection pipeline or the env query
12
13
  // tools is rejected here — every entry path fails closed on the parse error.
13
14
  export const PluginOptionsSchema = z
14
15
  .object({
15
- // No schema default: the default depends on the host generation, so
16
- // callers fill it in with withDefaultMode() before parsing. A caller
17
- // that forgets fails the parse, and every entry path fails closed.
16
+ // No schema default: callers fill it in with withDefaultMode() before
17
+ // parsing. A caller that forgets fails the parse, and every entry path
18
+ // fails closed.
18
19
  mode: z.enum(["block", "redact", "transparent"]),
19
20
  configPath: z.string().min(1).optional(),
20
21
  deidentify: z.boolean().default(false),
@@ -44,8 +45,7 @@ export const PluginOptionsSchema = z
44
45
  * the ladder OS keychain → explicit keyfile → memory-only degrade;
45
46
  * conversations are never blocked by a missing key.
46
47
  */
47
- persistence: z
48
- .object({
48
+ persistence: plainObject(z.object({
49
49
  enabled: z.boolean().default(false),
50
50
  /** Session TTL in days; 0 = never expire (manual forget only). */
51
51
  ttlDays: z.number().int().min(0).max(3650).default(7),
@@ -55,8 +55,7 @@ export const PluginOptionsSchema = z
55
55
  keyFile: z.boolean().default(false),
56
56
  /** Overrides the default keyfile location. */
57
57
  keyfilePath: z.string().min(1).optional(),
58
- })
59
- .default({}),
58
+ })).prefault({}),
60
59
  })
61
60
  .refine((options) => !options.deidentify || options.mode === "redact", {
62
61
  message: "deidentify requires mode 'redact'",
@@ -73,24 +72,19 @@ export const PluginOptionsSchema = z
73
72
  .refine((options) => !options.persistence.enabled || options.mode === "transparent", {
74
73
  message: 'persistence requires mode "transparent"',
75
74
  });
76
- /** Mode used when the options omit `mode`: transparent on v2, block on v1
77
- * (transparent is v2-only). */
78
- export function defaultMode(generation) {
79
- return generation === "v2" ? "transparent" : "block";
80
- }
81
- /** Fills in the generation's default mode when the options omit it. Any
75
+ /** Fills in the default mode (transparent) when the options omit `mode`. Any
82
76
  * other non-object input is returned unchanged so the schema rejects it. */
83
- export function withDefaultMode(input, generation) {
77
+ export function withDefaultMode(input) {
84
78
  if (input === undefined || input === null)
85
- return { mode: defaultMode(generation) };
79
+ return { mode: "transparent" };
86
80
  if (typeof input !== "object" || Array.isArray(input))
87
81
  return input;
88
82
  if (input.mode !== undefined)
89
83
  return input;
90
- return { ...input, mode: defaultMode(generation) };
84
+ return { ...input, mode: "transparent" };
91
85
  }
92
- export function validatePluginOptions(input, generation) {
93
- const parsed = PluginOptionsSchema.safeParse(withDefaultMode(input, generation));
86
+ export function validatePluginOptions(input) {
87
+ const parsed = PluginOptionsSchema.safeParse(withDefaultMode(input));
94
88
  if (parsed.success)
95
89
  return { ok: true, options: parsed.data };
96
90
  return {
@@ -71,6 +71,81 @@ function publicIPv4(raw) {
71
71
  return false; // multicast / reserved
72
72
  return true;
73
73
  }
74
+ /**
75
+ * Values on the right of `password:` / `secret =` that are source code, not a
76
+ * literal: environment lookups, a method-call chain, or a member read off a
77
+ * config-like object (issue #49). Only the unquoted branch of generic-secret
78
+ * reaches this, and every form here is narrow on purpose: a bare
79
+ * `word.word` could be a real password, so it is not exempt.
80
+ */
81
+ // Call arguments and bracket keys may hold identifiers, numbers or an
82
+ // ENV_NAME-style string, never another literal: `decrypt("hunter2hunter2")`
83
+ // keeps being reported.
84
+ // Backticks and `=` are excluded too, so a template literal or a keyword
85
+ // argument (`hash(pw=…)`) never qualifies.
86
+ const ARG = `(?:[^()'"\`=\\[\\]]|'[A-Z][A-Z0-9_]*'|"[A-Z][A-Z0-9_]*")*`;
87
+ const IDENT = "[A-Za-z_$][\\w$]*";
88
+ const STEP = `(?:\\??\\.${IDENT}|\\[${ARG}\\]|\\(${ARG}\\))`;
89
+ const TAIL = "[;,)]*$";
90
+ /**
91
+ * A member/call chain: `z.string().min(6)`, `getPassword()`, `os.getenv("DB_PASS")`.
92
+ * Every STEP alternative starts with a different character, so matching is
93
+ * linear; "contains a call" is checked separately rather than with a second
94
+ * quantified group that would backtrack.
95
+ */
96
+ const CODE_CHAIN = new RegExp(`^${IDENT}${STEP}*${TAIL}`);
97
+ /** A member read off an env or config-like root: `process.env.X`, `config.clientSecret`. */
98
+ const CONFIG_MEMBER = new RegExp(`^(?:process\\.env|import\\.meta\\.env|os\\.environ|ENV|this|self|config|cfg|conf|settings|options|opts|props|params|args|req|request|ctx|context|env|secrets)${STEP}+${TAIL}`);
99
+ /** Longer values are not exempted; a real expression on one line is short. */
100
+ const MAX_EXPRESSION_LENGTH = 256;
101
+ function isCodeExpressionValue(match) {
102
+ const value = match.replace(/^[^:=]*[:=]\s*/, "");
103
+ if (value.length > MAX_EXPRESSION_LENGTH)
104
+ return false;
105
+ if (value.startsWith("'") || value.startsWith('"'))
106
+ return false;
107
+ return (value.includes("(") && CODE_CHAIN.test(value)) || CONFIG_MEMBER.test(value);
108
+ }
109
+ /**
110
+ * A whole-token template placeholder that only names a variable:
111
+ * `${pass}`, `${cfg.db.password}`, `{{ password }}`, `<password>`. An
112
+ * interpolation holding a literal (`${"S3cr3tPass"}`) is not a placeholder.
113
+ */
114
+ const PLACEHOLDER = /^(?:\$\{\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\}|\{\{\s*[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*\s*\}\}|<[A-Za-z][\w -]*>)$/;
115
+ /**
116
+ * True when the password part of `user:password@` is a template placeholder,
117
+ * as in `mongodb://${user}:${pass}@host` or `postgres://<user>:<password>@…`.
118
+ * `userinfo` runs from just after `://` to (and possibly including) the `@`.
119
+ */
120
+ function placeholderPassword(userinfo) {
121
+ const at = userinfo.lastIndexOf("@");
122
+ const body = at === -1 ? userinfo : userinfo.slice(0, at);
123
+ const colon = body.indexOf(":");
124
+ if (colon === -1)
125
+ return false;
126
+ return PLACEHOLDER.test(body.slice(colon + 1));
127
+ }
128
+ const UUID_SHAPE = /[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/g;
129
+ /** True when [index, index+length) lies inside a UUID-shaped run in `text`. */
130
+ function insideUuid(text, index, length) {
131
+ const from = Math.max(0, index - 36);
132
+ const window = text.slice(from, index + length + 36);
133
+ for (const uuid of window.matchAll(UUID_SHAPE)) {
134
+ const start = from + uuid.index;
135
+ if (start <= index && index + length <= start + uuid[0].length)
136
+ return true;
137
+ }
138
+ return false;
139
+ }
140
+ /** Luhn plus shape checks: not one repeated digit, not part of a UUID (#49). */
141
+ function creditCardValid(match, context) {
142
+ const digits = match.replace(/[^0-9]/g, "");
143
+ if (/^(\d)\1*$/.test(digits))
144
+ return false;
145
+ if (insideUuid(context.text, context.index, match.length))
146
+ return false;
147
+ return luhnValid(match);
148
+ }
74
149
  export const BUILTIN_RULES = [
75
150
  // ── API Keys / Secrets / Tokens ──────────────────────────────────────────
76
151
  {
@@ -151,6 +226,8 @@ export const BUILTIN_RULES = [
151
226
  // 同時涵蓋有引號(YAML/JSON)與無引號(.env)寫法
152
227
  // (?!\$\{) 排除環境變數參照 ${VAR};(?!\*) 排除遮罩值 ********
153
228
  pattern: /(?:password|passwd|secret|private_key|client_secret)\s*[:=]\s*(?:['"](?!\$\{)[^'"]{8,}['"]|(?!['"\$\*])\S{8,})/gi,
229
+ // 無引號值若是程式碼表達式(process.env.X、z.string()、config.secret)不算機密(#49)
230
+ validate: (match) => !isCodeExpressionValue(match),
154
231
  },
155
232
  {
156
233
  id: "url-userinfo",
@@ -163,6 +240,8 @@ export const BUILTIN_RULES = [
163
240
  // 重掃造成二次方成長。
164
241
  pattern: /:\/\/[^\s/?#:]*:[^\s/?#]*@/gi,
165
242
  skipPrefix: 3,
243
+ // 密碼段是 ${…}/{{…}}/<…> 模板佔位時不是憑證(#49)
244
+ validate: (match) => !placeholderPassword(match),
166
245
  },
167
246
  {
168
247
  id: "jwt",
@@ -269,6 +348,8 @@ export const BUILTIN_RULES = [
269
348
  severity: "HIGH",
270
349
  description: "資料庫連線字串(含密碼)",
271
350
  pattern: /(?:mongodb(?:\+srv)?|postgresql|postgres|mysql|redis|mssql):\/\/[^:\s]+:[^@\s]+@[^\s"']+/gi,
351
+ // 密碼段是模板佔位時不是憑證(#49)
352
+ validate: (match) => !placeholderPassword(match.slice(match.indexOf("://") + 3)),
272
353
  },
273
354
  {
274
355
  id: "db-connection-ado",
@@ -286,7 +367,7 @@ export const BUILTIN_RULES = [
286
367
  description: "信用卡號(Luhn 驗證)",
287
368
  // 13–19 位數字,允許空格或連字號分隔;Luhn 不過由 validate 排除
288
369
  pattern: /\b(?:[0-9][ -]?){12,18}[0-9]\b/g,
289
- validate: luhnValid,
370
+ validate: creditCardValid,
290
371
  },
291
372
  {
292
373
  id: "iban",