@magpie-community/opencode-factory-auth 0.1.34 → 0.1.35

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/README.md CHANGED
@@ -209,8 +209,9 @@ incomplete and hook-owned forms are left alone.
209
209
 
210
210
  Factory can also refuse fixed client phrases quoted in tool results, such as
211
211
  the identity/environment definitions printed when inspecting this plugin's
212
- source, or the compaction opening embedded in a historical session JSONL
213
- record. Those text results are represented as JSON strings with explicit
212
+ source, the compaction opening embedded in a historical session JSONL
213
+ record, or pi's opening sentence in a model snapshot of its own system
214
+ prompt. Those text results are represented as JSON strings with explicit
214
215
  decoding instructions and Unicode escapes for the fixed phrases. Decoding
215
216
  the string recovers the exact original output, including quotes, backslashes
216
217
  and Unicode; the plugin does not delete the output or replace its identities
@@ -0,0 +1,16 @@
1
+ {
2
+ "//": "Fixed client phrases Factory refuses in a request body. Each phrase's first character is a JSON \\uXXXX escape: the file is safe to read (a Droid session reading it does not 403), and JSON.parse yields the real phrase. anywhere: refused in any text (system, user, assistant, tool_use). toolOnly: refused in tool output; the prompt adapters keep them.",
3
+ "anywhere": [
4
+ "\u0059ou are an expert coding assistant operating inside pi, a coding agent harness.",
5
+ "\u0054he conversation history before this point was compacted into the following summary:"
6
+ ],
7
+ "toolOnly": [
8
+ "\u0059ou are Claude Code, Anthropic's official CLI for Claude.",
9
+ "\u0059ou are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.",
10
+ "\u0059ou are a Claude agent, built on Anthropic's Claude Agent SDK.",
11
+ "\u0059ou have been invoked in the following environment:",
12
+ "\u0078-anthropic-billing-header: cc_version=",
13
+ "\u0054his session is being continued from a previous conversation that ran out of context.",
14
+ "\u0028user's private global instructions for all projects)"
15
+ ]
16
+ }
package/index.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
  // built-in Factory account (internal/provider/factory*.go).
5
5
 
6
6
  import { STATUS_CODES } from "node:http"
7
+ import { readFileSync } from "node:fs"
7
8
  import { parseToolJSON, wrapAnthropicTools, unwrapAnthropicTools } from "./anthropic-tools.mjs"
8
9
 
9
10
  const PROVIDER = "factory"
@@ -481,6 +482,48 @@ function piSummary(text) {
481
482
  return text
482
483
  }
483
484
 
485
+ // Factory refuses pi's opening and its compaction opening wherever they
486
+ // appear, not only as the system prompt or the whole summary: a tool result
487
+ // that prints pi's system prompt, or a historical session record, carries
488
+ // them too, and every later turn of that conversation is 403.
489
+ //
490
+ // The list lives in client-phrases.json so the guard and the sanitizer read
491
+ // the same one. Its entries are written with a \uXXXX first character, so the
492
+ // file is safe to read from a Droid session; JSON.parse here yields the real
493
+ // phrase. "anywhere" is refused in any text (pi turns a compaction into one
494
+ // user text), "toolOnly" is refused in tool output while the prompt adapters
495
+ // keep them.
496
+ const FALLBACK_PHRASES = {
497
+ anywhere: [
498
+ "You are an expert coding assistant operating inside pi, a coding agent harness.",
499
+ PI_SUMMARIES[0][0].split("\n\n")[0],
500
+ ],
501
+ toolOnly: [
502
+ "You are Claude Code, Anthropic's official CLI for Claude.",
503
+ "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.",
504
+ "You are a Claude agent, built on Anthropic's Claude Agent SDK.",
505
+ "You have been invoked in the following environment:",
506
+ "x-anthropic-billing-header: cc_version=",
507
+ "This session is being continued from a previous conversation that ran out of context.",
508
+ "(user's private global instructions for all projects)",
509
+ ],
510
+ }
511
+ function loadClientPhrases() {
512
+ try {
513
+ const parsed = JSON.parse(readFileSync(new URL("./client-phrases.json", import.meta.url), "utf8"))
514
+ const anywhere = Array.isArray(parsed?.anywhere) ? parsed.anywhere.filter((p) => typeof p === "string" && p) : []
515
+ const toolOnly = Array.isArray(parsed?.toolOnly) ? parsed.toolOnly.filter((p) => typeof p === "string" && p) : []
516
+ // either group missing would silently drop protection, so use the
517
+ // built-in list instead
518
+ if (anywhere.length === 0 || toolOnly.length === 0) throw new Error("client-phrases.json needs both groups")
519
+ return { anywhere, toolOnly }
520
+ } catch {
521
+ return FALLBACK_PHRASES
522
+ }
523
+ }
524
+ const CLIENT_PHRASES = loadClientPhrases()
525
+ const PI_QUOTED_IN_TOOL = CLIENT_PHRASES.anywhere
526
+
484
527
  // promptOpenings adapts the messages of msgs (chat completions' messages,
485
528
  // Responses' input) as anthropicBody adapts a Messages request's: pi's
486
529
  // opening and Claude Code's fixed phrases in the system and developer
@@ -632,6 +675,9 @@ function geminiBody(model, body) {
632
675
  si.parts = [{ text: joined.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + joined }, ...rest]
633
676
  }
634
677
  m.systemInstruction = si
678
+ // Gemini's route has no tool-output adaptation: escape every refused
679
+ // phrase in its parts (functionResponse, systemInstruction) here.
680
+ escapeDeep(m, REFUSED_PHRASES)
635
681
  return JSON.stringify(m)
636
682
  }
637
683
 
@@ -1332,19 +1378,89 @@ function changedFileContext(text) {
1332
1378
  // rather than deleting or rewriting the file's contents. Other output and
1333
1379
  // the tool's id, error/cache markers and non-text blocks stay untouched.
1334
1380
  const QUOTED_TOOL_PREFIX = "Tool output encoded as a JSON string. Decode the JSON string to recover the exact original text before using it:\n"
1381
+ // the phrases Factory refuses wherever they appear
1382
+ const REFUSED_PHRASES = [
1383
+ ...CLIENT_PHRASES.anywhere,
1384
+ ...CLIENT_PHRASES.toolOnly,
1385
+ ]
1386
+ // The substrings whose first character is escaped in tool output: every
1387
+ // refused phrase from the list, plus the shorter prefixes the old loop
1388
+ // escaped and the reminder marker. Longest first, so a full sentence is
1389
+ // escaped before its own prefix (escaping the prefix first would hide it).
1390
+ const ESCAPE_IN_TOOL = [...new Set([...REFUSED_PHRASES, COMPACT_OPENING, GLOBAL_INSTRUCTIONS, "system-reminder", "You have", "You are", "x-anthropic-billing-header"])]
1391
+ .sort((a, b) => b.length - a.length)
1335
1392
  function quotedToolText(text, prefix = QUOTED_TOOL_PREFIX) {
1336
- if (![...CLAUDE_IDENTITIES].some((identity) => text.includes(identity)) &&
1337
- !text.includes("You have been invoked in the following environment:") &&
1338
- !text.includes("x-anthropic-billing-header: cc_version=") &&
1339
- !text.includes(COMPACT_OPENING) &&
1340
- !text.includes(GLOBAL_INSTRUCTIONS)) return text
1393
+ if (!REFUSED_PHRASES.some((phrase) => text.includes(phrase))) return text
1341
1394
  let encoded = JSON.stringify(text)
1342
- for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder", COMPACT_OPENING, GLOBAL_INSTRUCTIONS]) {
1395
+ for (const phrase of ESCAPE_IN_TOOL) {
1343
1396
  encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
1344
1397
  }
1345
1398
  return prefix + encoded
1346
1399
  }
1347
1400
 
1401
+ // Factory refuses these phrases anywhere in the body, not only in tool
1402
+ // output: pi turns a compaction into one user text, and an assistant
1403
+ // message or a tool_use argument can quote a file too. escapePhrases
1404
+ // rewrites the first character of each phrase as \uXXXX without wrapping the
1405
+ // text, so a poisoned conversation can still be compacted or replayed.
1406
+ // Tool output keeps the JSON-wrapped, lossless form above.
1407
+ function escapePhrases(text, phrases = PI_QUOTED_IN_TOOL) {
1408
+ let out = text
1409
+ // By default only the phrases proven to be refused outside tool output
1410
+ // (pi's opening and its compaction opening): escaping generated reminders
1411
+ // such as GLOBAL_INSTRUCTIONS or Claude Code's environment line would
1412
+ // rewrite text the adapters deliberately keep. Gemini's route passes the
1413
+ // full list, because its tool output has no quotedToolText of its own.
1414
+ for (const phrase of phrases) {
1415
+ if (out.includes(phrase)) out = out.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
1416
+ }
1417
+ return out
1418
+ }
1419
+
1420
+ // escapeDeep applies escapePhrases to every string in a JSON body, in place.
1421
+ // true when something changed. Tool results are already escaped, so a
1422
+ // second pass changes nothing.
1423
+ function escapeDeep(value, phrases = PI_QUOTED_IN_TOOL) {
1424
+ if (typeof value === "string") return false // strings are replaced by their parent
1425
+ if (Array.isArray(value)) {
1426
+ let changed = false
1427
+ for (let i = 0; i < value.length; i++) {
1428
+ if (typeof value[i] === "string") {
1429
+ const out = escapePhrases(value[i], phrases)
1430
+ if (out !== value[i]) (value[i] = out), (changed = true)
1431
+ } else if (escapeDeep(value[i], phrases)) changed = true
1432
+ }
1433
+ return changed
1434
+ }
1435
+ if (value && typeof value === "object") {
1436
+ let changed = false
1437
+ for (const key of Object.keys(value)) {
1438
+ const v = value[key]
1439
+ if (typeof v === "string") {
1440
+ const out = escapePhrases(v, phrases)
1441
+ if (out !== v) (value[key] = out), (changed = true)
1442
+ } else if (escapeDeep(v, phrases)) changed = true
1443
+ }
1444
+ return changed
1445
+ }
1446
+ return false
1447
+ }
1448
+
1449
+ // sanitizeBody is the last pass before a request leaves: every string in the
1450
+ // body gets escapePhrases. Handles Messages, Responses, chat and Gemini.
1451
+ function sanitizeBody(body) {
1452
+ const text = bodyText(body)
1453
+ if (text == null) return body
1454
+ let parsed
1455
+ try {
1456
+ parsed = JSON.parse(text)
1457
+ } catch {
1458
+ return body
1459
+ }
1460
+ if (!escapeDeep(parsed)) return body
1461
+ return JSON.stringify(parsed)
1462
+ }
1463
+
1348
1464
  // The adapters below are shared by both of Factory's routes. Claude Code's
1349
1465
  // request reaches /api/llm/a as Messages, but a model Factory serves on
1350
1466
  // /api/llm/o (GLM, Kimi and other chat models) gets it translated by magpie
@@ -1864,7 +1980,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
1864
1980
  // another agent's request opens as droid's does (droidBody)
1865
1981
  const anthropic = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
1866
1982
  const adapted = anthropic ? wrapAnthropicTools(anthropicBody(body)) : { body: droidBody(path, body), names: new Set() }
1867
- const out = adapted.body
1983
+ const out = sanitizeBody(adapted.body)
1868
1984
  // the caller's length is of the body it sent, not of this one
1869
1985
  if (out !== init?.body) h.delete("content-length")
1870
1986
  const res = await fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.34",
3
+ "version": "0.1.35",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
- "files": ["index.mjs", "anthropic-tools.mjs", "README.md"],
7
+ "files": ["index.mjs", "anthropic-tools.mjs", "client-phrases.json", "README.md"],
8
8
  "keywords": ["opencode", "opencode-plugin", "magpie", "factory", "droid"],
9
9
  "license": "MIT",
10
10
  "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/factory" }