leakshield 0.1.3 โ†’ 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 {