@sriinnu/fiche 0.0.0-stage → 0.19.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.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +288 -2
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +122 -4
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,49 @@
1
+ import { accessSync, constants, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ const DEFAULT_PATHEXT = '.COM;.EXE;.BAT;.CMD';
4
+ const DIRECT_EXTS = new Set(['.com', '.exe']);
5
+ /** Does this word name a file path rather than a bare command? */
6
+ export const isPathLike = (word, platform = process.platform) => word.includes('/') || (platform === 'win32' && word.includes('\\'));
7
+ /**
8
+ * Minimal `which`: is this bare name an executable on PATH?
9
+ *
10
+ * Windows splits PATH on `;` (a drive letter already contains `:`), and a bare
11
+ * `claude` only exists on disk as `claude.exe`, so PATHEXT has to be tried too.
12
+ */
13
+ export const whichSync = (name, env, platform = process.platform) => {
14
+ if (isPathLike(name, platform))
15
+ return false; // a path, handled by existsSync
16
+ const win = platform === 'win32';
17
+ const p = win ? path.win32 : path.posix;
18
+ // Windows env is case-insensitive, but a copied object is not.
19
+ const pathVar = win ? (env.PATH ?? env.Path ?? '') : (env.PATH ?? '');
20
+ // Only what spawn() can launch without a shell: libuv runs .com/.exe, while
21
+ // .cmd/.bat (npm shims) need cmd.exe and would fail a direct spawn.
22
+ const exts = win
23
+ ? (env.PATHEXT ?? DEFAULT_PATHEXT)
24
+ .split(';')
25
+ .map((ext) => ext.toLowerCase())
26
+ .filter((ext) => DIRECT_EXTS.has(ext))
27
+ : [];
28
+ const hasExt = win && exts.some((ext) => name.toLowerCase().endsWith(ext.toLowerCase()));
29
+ const candidates = win && !hasExt ? exts.map((ext) => name + ext) : [name];
30
+ for (const dir of pathVar.split(p.delimiter)) {
31
+ if (!dir)
32
+ continue;
33
+ for (const candidate of candidates) {
34
+ // Host join, not p.join: win32 only changes how PATH is split, and a
35
+ // backslash path would not exist when tests fake win32 on posix.
36
+ try {
37
+ accessSync(path.join(dir, candidate), win ? constants.F_OK : constants.X_OK);
38
+ return true;
39
+ }
40
+ catch {
41
+ // not here, keep looking
42
+ }
43
+ }
44
+ }
45
+ return false;
46
+ };
47
+ /** Can this word actually be executed: a path that exists, or a name on PATH. */
48
+ export const isRunnable = (word, env, platform = process.platform) => (isPathLike(word, platform) ? existsSync(word) : whichSync(word, env, platform));
49
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Routes re-point a matching request at a different upstream, so inkling can
3
+ * transform it without the agent ever seeing a non-first-party base URL.
4
+ *
5
+ * That indirection is the whole point. Claude Code hides /remote-control the
6
+ * moment ANTHROPIC_BASE_URL is custom (and gates connectors on the same
7
+ * "firstParty" check), so pointing the agent at inkling directly costs you the
8
+ * feature. Under warp the agent still talks to api.anthropic.com; only the one
9
+ * path we rewrite is diverted, and auth, telemetry and the control plane go to
10
+ * the real host untouched.
11
+ *
12
+ * Ported from wardex route.go.
13
+ */
14
+ export interface Route {
15
+ /** Original spec text, for banners and logs. */
16
+ readonly pattern: string;
17
+ /** Anchored matcher against "host/path". */
18
+ readonly re: RegExp;
19
+ /**
20
+ * Host-only matcher, used to decide whether a CONNECT is worth decrypting at
21
+ * all — a CONNECT carries no path.
22
+ */
23
+ readonly hostRe: RegExp;
24
+ /**
25
+ * Whether the pattern named a port. Loopback targets make the port the only
26
+ * thing distinguishing two hosts (127.0.0.1:9090 vs 127.0.0.1:47821), so a
27
+ * pattern that names one must be matched against "host:port" and a pattern
28
+ * that does not must keep matching any port.
29
+ */
30
+ readonly hasPort: boolean;
31
+ readonly target: URL;
32
+ /**
33
+ * Target path prefix, normalized to "" or "/foo" (no trailing slash). Kept
34
+ * separately because URL.pathname cannot represent the empty path: assigning
35
+ * "" to a special-scheme URL silently snaps it back to "/", which would make
36
+ * every rewrite emit a doubled "//v1/messages".
37
+ */
38
+ readonly prefix: string;
39
+ }
40
+ /**
41
+ * parseRoute reads one PATTERN=TARGET rule:
42
+ *
43
+ * api.anthropic.com/v1/messages*=http://127.0.0.1:47821
44
+ * re:^api\.anthropic\.com/v1/messages(/.*)?$=http://127.0.0.1:47821
45
+ *
46
+ * PATTERN matches "host/path" with no scheme and no query. TARGET is
47
+ * scheme://host[:port][/prefix]; the original path and query ride along.
48
+ */
49
+ export declare function parseRoute(spec: string): Route;
50
+ /** Collapse dot-segments and repeated slashes so traversal paths cannot match prefix globs. */
51
+ export declare function normalizeRoutePath(path: string): string;
52
+ /**
53
+ * First match wins, so earlier rules shadow later ones.
54
+ *
55
+ * `hostPort` carries the port so a pattern may select on it; patterns that name
56
+ * no port are matched against the bare host and so still match any port.
57
+ */
58
+ export declare function matchRoute(routes: readonly Route[], hostPort: string, path: string): Route | null;
59
+ /**
60
+ * Whether any rule could match this host. Decryption is decided at CONNECT
61
+ * time, before a path exists, so this is deliberately permissive: guessing
62
+ * "yes" costs a needless MITM, guessing "no" silently breaks the route.
63
+ */
64
+ export declare function hostCouldMatch(routes: readonly Route[], hostPort: string): boolean;
65
+ /**
66
+ * Absolute URL a matched request is sent to. Path and query are preserved so
67
+ * the downstream sees the same request the agent made.
68
+ */
69
+ export declare function rewriteUrl(route: Route, requestUri: string): string;
70
+ export declare function routeDestination(route: Route): string;
71
+ //# sourceMappingURL=route.d.ts.map
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Routes re-point a matching request at a different upstream, so inkling can
3
+ * transform it without the agent ever seeing a non-first-party base URL.
4
+ *
5
+ * That indirection is the whole point. Claude Code hides /remote-control the
6
+ * moment ANTHROPIC_BASE_URL is custom (and gates connectors on the same
7
+ * "firstParty" check), so pointing the agent at inkling directly costs you the
8
+ * feature. Under warp the agent still talks to api.anthropic.com; only the one
9
+ * path we rewrite is diverted, and auth, telemetry and the control plane go to
10
+ * the real host untouched.
11
+ *
12
+ * Ported from wardex route.go.
13
+ */
14
+ function quoteMeta(s) {
15
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
16
+ }
17
+ /**
18
+ * Turn a host/path glob into an anchored regexp. "*" spans anything including
19
+ * "/", matching wardex's semantics.
20
+ */
21
+ function compilePattern(pattern) {
22
+ const withPath = pattern.includes('/') ? pattern : `${pattern}/*`;
23
+ const parts = withPath.toLowerCase().split('*').map(quoteMeta);
24
+ return new RegExp(`^${parts.join('.*')}$`, 'i');
25
+ }
26
+ /**
27
+ * parseRoute reads one PATTERN=TARGET rule:
28
+ *
29
+ * api.anthropic.com/v1/messages*=http://127.0.0.1:47821
30
+ * re:^api\.anthropic\.com/v1/messages(/.*)?$=http://127.0.0.1:47821
31
+ *
32
+ * PATTERN matches "host/path" with no scheme and no query. TARGET is
33
+ * scheme://host[:port][/prefix]; the original path and query ride along.
34
+ */
35
+ export function parseRoute(spec) {
36
+ // The target always ends the spec and always carries a scheme, so split on
37
+ // the scheme rather than on "=" — patterns are regexps and may contain "=".
38
+ let i = spec.lastIndexOf('=http://');
39
+ const j = spec.lastIndexOf('=https://');
40
+ if (j > i)
41
+ i = j;
42
+ if (i < 0)
43
+ throw new Error(`route ${JSON.stringify(spec)}: want PATTERN=http://host:port`);
44
+ const pattern = spec.slice(0, i);
45
+ const rawTarget = spec.slice(i + 1);
46
+ if (!pattern)
47
+ throw new Error(`route ${JSON.stringify(spec)}: empty pattern`);
48
+ let re;
49
+ try {
50
+ re = compilePattern(pattern);
51
+ }
52
+ catch (err) {
53
+ throw new Error(`route ${JSON.stringify(spec)}: bad pattern: ${err.message}`);
54
+ }
55
+ let target;
56
+ try {
57
+ target = new URL(rawTarget);
58
+ }
59
+ catch {
60
+ throw new Error(`route ${JSON.stringify(spec)}: bad target: ${rawTarget}`);
61
+ }
62
+ if (!target.host)
63
+ throw new Error(`route ${JSON.stringify(spec)}: target has no host`);
64
+ if (target.search || target.hash) {
65
+ throw new Error(`route ${JSON.stringify(spec)}: target must not carry a query or fragment`);
66
+ }
67
+ const prefix = target.pathname === '/' ? '' : target.pathname.replace(/\/$/, '');
68
+ const hostGlob = pattern.split('/')[0];
69
+ const hostRe = new RegExp(`^${hostGlob.toLowerCase().split('*').map(quoteMeta).join('.*')}$`, 'i');
70
+ const hasPort = /\]:\d+$|^[^[\]]+:\d+$/.test(hostGlob);
71
+ return { pattern, re, hostRe, hasPort, target, prefix };
72
+ }
73
+ /** Drop a trailing ":port", leaving IPv6 literals intact. */
74
+ function stripPort(hostPort) {
75
+ if (hostPort.startsWith('[')) {
76
+ const end = hostPort.indexOf(']');
77
+ return end > 0 ? hostPort.slice(0, end + 1) : hostPort;
78
+ }
79
+ const firstColon = hostPort.indexOf(':');
80
+ const lastColon = hostPort.lastIndexOf(':');
81
+ // Unbracketed IPv6 literal has 2+ colons and no port suffix.
82
+ if (firstColon !== lastColon)
83
+ return hostPort;
84
+ return lastColon > 0 ? hostPort.slice(0, lastColon) : hostPort;
85
+ }
86
+ /** Collapse dot-segments and repeated slashes so traversal paths cannot match prefix globs. */
87
+ export function normalizeRoutePath(path) {
88
+ const cleaned = path.replaceAll('\\', '/').replace(/^\/+/, '/');
89
+ const safe = cleaned.startsWith('/') ? cleaned : `/${cleaned}`;
90
+ try {
91
+ const u = new URL(`http://route.invalid${safe}`);
92
+ return u.pathname.replace(/\/{2,}/g, '/');
93
+ }
94
+ catch {
95
+ return safe;
96
+ }
97
+ }
98
+ /**
99
+ * First match wins, so earlier rules shadow later ones.
100
+ *
101
+ * `hostPort` carries the port so a pattern may select on it; patterns that name
102
+ * no port are matched against the bare host and so still match any port.
103
+ */
104
+ export function matchRoute(routes, hostPort, path) {
105
+ const lower = hostPort.toLowerCase();
106
+ const bare = stripPort(lower);
107
+ const normalizedPath = normalizeRoutePath(path);
108
+ for (const route of routes) {
109
+ if (route.re.test((route.hasPort ? lower : bare) + normalizedPath))
110
+ return route;
111
+ }
112
+ return null;
113
+ }
114
+ /**
115
+ * Whether any rule could match this host. Decryption is decided at CONNECT
116
+ * time, before a path exists, so this is deliberately permissive: guessing
117
+ * "yes" costs a needless MITM, guessing "no" silently breaks the route.
118
+ */
119
+ export function hostCouldMatch(routes, hostPort) {
120
+ const lower = hostPort.toLowerCase();
121
+ const bare = stripPort(lower);
122
+ return routes.some((route) => route.hostRe.test(route.hasPort ? lower : bare));
123
+ }
124
+ /**
125
+ * Absolute URL a matched request is sent to. Path and query are preserved so
126
+ * the downstream sees the same request the agent made.
127
+ */
128
+ export function rewriteUrl(route, requestUri) {
129
+ return `${route.target.protocol}//${route.target.host}${route.prefix}${requestUri}`;
130
+ }
131
+ export function routeDestination(route) {
132
+ return `${route.target.protocol}//${route.target.host}${route.prefix}`;
133
+ }
134
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Cloudflare Workers entrypoint. Identical proxy logic to the Node build,
3
+ * just wired up through the Worker `fetch` export.
4
+ *
5
+ * Deploy:
6
+ * npx wrangler deploy
7
+ *
8
+ * Dev:
9
+ * npx wrangler dev
10
+ *
11
+ * Config lives in wrangler.toml.
12
+ */
13
+ import type { ExecutionContext } from '@cloudflare/workers-types';
14
+ export interface Env {
15
+ /** Optional single upstream base for every API family. Family-specific env vars override it. */
16
+ FICHE_UPSTREAM?: string;
17
+ INKLING_UPSTREAM?: string;
18
+ ANTHROPIC_UPSTREAM?: string;
19
+ /** Optional override — if set, replaces whatever x-api-key the client sent. */
20
+ ANTHROPIC_API_KEY?: string;
21
+ OPENAI_UPSTREAM?: string;
22
+ /** Optional override — if set, replaces whatever Authorization the client sent. */
23
+ OPENAI_API_KEY?: string;
24
+ OPENAI_MODELS?: string;
25
+ CLOUDFLARE_MODELS?: string;
26
+ CLOUDFLARE_ACCOUNT_ID?: string;
27
+ CLOUDFLARE_API_TOKEN?: string;
28
+ COMPRESS?: string;
29
+ COMPRESS_TOOLS?: string;
30
+ COMPRESS_TOOL_RESULTS?: string;
31
+ MIN_COMPRESS_CHARS?: string;
32
+ MIN_TOOL_RESULT_CHARS?: string;
33
+ COLS?: string;
34
+ /** Comma-separated model bases eligible for compression. */
35
+ FICHE_MODELS?: string;
36
+ INKLING_MODELS?: string;
37
+ /** Ceiling on a buffered inbound request body, in bytes. A Worker is publicly
38
+ * reachable by default, so this is the setting that keeps one caller from
39
+ * choosing the isolate's memory ceiling. Unset uses the core 16 MiB default;
40
+ * a non-numeric or non-positive value is ignored rather than obeyed. */
41
+ FICHE_MAX_REQUEST_BYTES?: string;
42
+ INKLING_MAX_REQUEST_BYTES?: string;
43
+ /** When "0" / "false", disable per-request event JSON logs. Default-on.
44
+ * Cloudflare ingests console.log as Workers Logs; pipe via Logpush to
45
+ * R2/S3 for the same JSONL shape Node writes to disk. */
46
+ FICHE_TRACK?: string;
47
+ INKLING_TRACK?: string;
48
+ /** Max bytes of rendered pages held in memory, or "0" to disable the cache.
49
+ * Unset uses the core edge default (8 MiB), which is deliberately far below
50
+ * the Node default: a Worker isolate has ~128 MiB for the request body, the
51
+ * decoded atlases, the framebuffers and the compressor as well. Bindings are
52
+ * not visible to core at module-init time, so this is applied per request via
53
+ * `setRenderCacheMaxBytes`. A negative or non-numeric value is ignored rather
54
+ * than obeyed; `0` is a real setting and must not be read as "unset". */
55
+ FICHE_RENDER_CACHE_BYTES?: string;
56
+ INKLING_RENDER_CACHE_BYTES?: string;
57
+ /** Shared secret callers must present via the `x-fiche-secret` (or legacy
58
+ * `x-inkling-secret`) header whenever an API-key override is configured.
59
+ * Set with: npx wrangler secret put FICHE_WORKER_SECRET */
60
+ FICHE_WORKER_SECRET?: string;
61
+ INKLING_WORKER_SECRET?: string;
62
+ /** "1" lets history collapse split adjacent tool call/result pairs for every
63
+ * client; "0" never. Unset decides per request from client headers. */
64
+ FICHE_TRUST_ADJACENT_TOOL_ROUNDS?: string;
65
+ INKLING_TRUST_ADJACENT_TOOL_ROUNDS?: string;
66
+ }
67
+ declare const _default: {
68
+ fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
69
+ };
70
+ export default _default;
71
+ //# sourceMappingURL=worker.d.ts.map
package/dist/worker.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Cloudflare Workers entrypoint. Identical proxy logic to the Node build,
3
+ * just wired up through the Worker `fetch` export.
4
+ *
5
+ * Deploy:
6
+ * npx wrangler deploy
7
+ *
8
+ * Dev:
9
+ * npx wrangler dev
10
+ *
11
+ * Config lives in wrangler.toml.
12
+ */
13
+ import { createProxy, resolveTrustAdjacentToolRoundsEnv } from './core/proxy.js';
14
+ import { toTrackEvent, JsonLogTracker, noopTracker } from './core/tracker.js';
15
+ import { setAllowedModelBases } from './core/applicability.js';
16
+ import { setRenderCacheMaxBytes } from './core/render.js';
17
+ import { readBrandEnv } from './core/env.js';
18
+ /** Invalid TRUST_ADJACENT_TOOL_ROUNDS values already warned about in this isolate. */
19
+ const warnedTrustAdjacentRaw = new Set();
20
+ /** Compare SHA-256 digests instead of the raw strings so the comparison
21
+ * can't leak a prefix-match timing signal. */
22
+ async function secretsMatch(a, b) {
23
+ const enc = new TextEncoder();
24
+ const [da, db] = await Promise.all([
25
+ crypto.subtle.digest('SHA-256', enc.encode(a)),
26
+ crypto.subtle.digest('SHA-256', enc.encode(b)),
27
+ ]);
28
+ const va = new Uint8Array(da);
29
+ const vb = new Uint8Array(db);
30
+ let diff = 0;
31
+ for (let i = 0; i < va.length; i++)
32
+ diff |= (va[i] ?? 0) ^ (vb[i] ?? 0);
33
+ return diff === 0;
34
+ }
35
+ const truthy = (v, fallback) => v == null ? fallback : v === '1' || v.toLowerCase() === 'true';
36
+ /** Parse a positive whole number, or undefined for anything else. Used for limits
37
+ * where a broken value must not read as "unlimited". */
38
+ const positiveInt = (v) => {
39
+ const raw = v?.trim();
40
+ if (raw === undefined || raw === '')
41
+ return undefined;
42
+ const n = Number(raw);
43
+ return Number.isSafeInteger(n) && n > 0 ? n : undefined;
44
+ };
45
+ /** Same shape as `positiveInt` but admits 0, because for the render cache budget 0 is
46
+ * a real instruction ("disable") rather than a broken value to fall back from. */
47
+ const nonNegativeInt = (v) => {
48
+ const raw = v?.trim();
49
+ if (raw === undefined || raw === '')
50
+ return undefined;
51
+ const n = Number(raw);
52
+ return Number.isSafeInteger(n) && n >= 0 ? n : undefined;
53
+ };
54
+ export default {
55
+ async fetch(req, env, ctx) {
56
+ const configuredModels = (env.FICHE_MODELS ?? env.INKLING_MODELS)?.trim();
57
+ setAllowedModelBases(configuredModels === undefined || configuredModels === ''
58
+ ? null
59
+ : /^(0|false|no|off|none)$/i.test(configuredModels)
60
+ ? []
61
+ : configuredModels.split(',').map((model) => model.trim()).filter(Boolean));
62
+ // Bindings only exist inside `fetch`, so the render cache budget is applied here
63
+ // rather than at module init the way the Node host does it. Cheap and idempotent:
64
+ // assigning the same value evicts nothing. Left unset, core keeps its edge default.
65
+ const renderCacheBytes = nonNegativeInt(env.FICHE_RENDER_CACHE_BYTES ?? env.INKLING_RENDER_CACHE_BYTES);
66
+ if (renderCacheBytes !== undefined)
67
+ setRenderCacheMaxBytes(renderCacheBytes);
68
+ // ── Caller auth ────────────────────────────────────────────────────
69
+ // If FICHE_WORKER_SECRET is configured, require it unconditionally. Also require
70
+ // it whenever any deployment API-key override is configured so workers.dev URLs
71
+ // never let anonymous callers spend operator credits.
72
+ const workerSecret = env.FICHE_WORKER_SECRET?.trim() || env.INKLING_WORKER_SECRET?.trim();
73
+ const hasConfiguredKey = Boolean(env.ANTHROPIC_API_KEY?.trim() || env.OPENAI_API_KEY?.trim() || env.CLOUDFLARE_API_TOKEN?.trim());
74
+ if (hasConfiguredKey && !workerSecret) {
75
+ return new Response(JSON.stringify({
76
+ error: 'refusing to proxy: an API key override is configured but FICHE_WORKER_SECRET is not, ' +
77
+ 'which would let anyone who finds this URL spend the configured key. ' +
78
+ 'Run `npx wrangler secret put FICHE_WORKER_SECRET` and send the value as the x-fiche-secret header.',
79
+ }), { status: 503, headers: { 'content-type': 'application/json' } });
80
+ }
81
+ if (workerSecret) {
82
+ const presented = req.headers.get('x-fiche-secret') ?? req.headers.get('x-inkling-secret') ?? '';
83
+ if (!(await secretsMatch(presented, workerSecret))) {
84
+ return new Response(JSON.stringify({ error: 'missing or invalid x-fiche-secret header' }), { status: 401, headers: { 'content-type': 'application/json' } });
85
+ }
86
+ }
87
+ // Never forward worker auth headers upstream, even when unauthenticated.
88
+ if (req.headers.has('x-fiche-secret') || req.headers.has('x-inkling-secret')) {
89
+ req = new Request(req);
90
+ req.headers.delete('x-fiche-secret');
91
+ req.headers.delete('x-inkling-secret');
92
+ }
93
+ const parsedMinCompress = env.MIN_COMPRESS_CHARS !== undefined && env.MIN_COMPRESS_CHARS.trim() !== ''
94
+ ? Number(env.MIN_COMPRESS_CHARS)
95
+ : NaN;
96
+ const parsedMinToolResult = env.MIN_TOOL_RESULT_CHARS !== undefined && env.MIN_TOOL_RESULT_CHARS.trim() !== ''
97
+ ? Number(env.MIN_TOOL_RESULT_CHARS)
98
+ : NaN;
99
+ const parsedCols = env.COLS !== undefined && env.COLS.trim() !== ''
100
+ ? Number(env.COLS)
101
+ : NaN;
102
+ const rawTrustAdjacent = env.FICHE_TRUST_ADJACENT_TOOL_ROUNDS ?? env.INKLING_TRUST_ADJACENT_TOOL_ROUNDS;
103
+ const trustAdjacent = resolveTrustAdjacentToolRoundsEnv(rawTrustAdjacent);
104
+ if (trustAdjacent.warning && rawTrustAdjacent !== undefined && !warnedTrustAdjacentRaw.has(rawTrustAdjacent)) {
105
+ if (warnedTrustAdjacentRaw.size < 32)
106
+ warnedTrustAdjacentRaw.add(rawTrustAdjacent);
107
+ console.warn(trustAdjacent.warning);
108
+ }
109
+ const transform = {
110
+ compress: truthy(env.COMPRESS, true),
111
+ compressTools: truthy(env.COMPRESS_TOOLS, true),
112
+ compressToolResults: truthy(env.COMPRESS_TOOL_RESULTS, true),
113
+ minCompressChars: Number.isFinite(parsedMinCompress) && parsedMinCompress >= 0 ? parsedMinCompress : 2000,
114
+ // No floors — the content-aware `isCompressionProfitable()` gate
115
+ // decides per-block based on actual pixel cost vs text cost. Host
116
+ // can still set a floor via env if they want observability buckets
117
+ // (e.g. MIN_TOOL_RESULT_CHARS=200 to skip absurdly small dumps).
118
+ minToolResultChars: Number.isFinite(parsedMinToolResult) && parsedMinToolResult >= 0 ? parsedMinToolResult : 0,
119
+ // Omit by default so OpenAI-shaped requests use their exact model profile;
120
+ // COLS remains an explicit operator override for every family.
121
+ ...(Number.isFinite(parsedCols) && parsedCols > 0 ? { cols: Math.floor(parsedCols) } : {}),
122
+ ...(trustAdjacent.value !== undefined ? { separateAdjacentToolPairs: trustAdjacent.value } : {}),
123
+ };
124
+ const trackingOn = truthy(env.FICHE_TRACK ?? env.INKLING_TRACK, true);
125
+ // Workers Logs ingests stdout as separate log lines. Emit one JSON line
126
+ // per event so downstream (Logpush → R2/S3) reads the same JSONL shape
127
+ // the Node host writes to disk.
128
+ const tracker = trackingOn ? new JsonLogTracker((s) => console.log(s)) : noopTracker;
129
+ const sharedUpstream = env.FICHE_UPSTREAM ?? env.INKLING_UPSTREAM ?? readBrandEnv('UPSTREAM');
130
+ const parseModels = (value) => value === undefined ? undefined : value.split(',').map((model) => model.trim()).filter(Boolean);
131
+ const cfAccount = env.CLOUDFLARE_ACCOUNT_ID?.trim();
132
+ const cfToken = env.CLOUDFLARE_API_TOKEN?.trim();
133
+ const cloudflareUpstream = cfAccount && cfToken
134
+ ? `https://api.cloudflare.com/client/v4/accounts/${cfAccount}/ai/v1`
135
+ : undefined;
136
+ const maxRequestBytes = positiveInt(env.FICHE_MAX_REQUEST_BYTES ?? env.INKLING_MAX_REQUEST_BYTES);
137
+ const config = {
138
+ upstream: env.ANTHROPIC_UPSTREAM?.trim() || sharedUpstream?.trim() || 'https://api.anthropic.com',
139
+ sharedUpstream: sharedUpstream?.trim() || undefined,
140
+ apiKey: env.ANTHROPIC_API_KEY?.trim() || undefined,
141
+ openAIUpstream: env.OPENAI_UPSTREAM?.trim() || sharedUpstream?.trim() || 'https://api.openai.com',
142
+ openAIApiKey: env.OPENAI_API_KEY?.trim() || undefined,
143
+ cloudflareUpstream,
144
+ cloudflareApiKey: cfToken,
145
+ openAIModels: parseModels(env.OPENAI_MODELS),
146
+ cloudflareModels: parseModels(env.CLOUDFLARE_MODELS),
147
+ ...(typeof ctx?.waitUntil === 'function' ? { waitUntil: (promise) => ctx.waitUntil(promise) } : {}),
148
+ // A Worker cannot exit on bad config the way the Node host does, so an
149
+ // unparseable value is dropped here and the core default applies.
150
+ ...(maxRequestBytes !== undefined ? { maxRequestBytes } : {}),
151
+ transform,
152
+ onRequest: (e) => {
153
+ // Terse human-readable line (separate from the JSON event below;
154
+ // shows up in `wrangler tail`).
155
+ const tag = e.info?.compressed
156
+ ? `compressed ${e.info.origChars}ch → ${e.info.imageCount}img/${e.info.imageBytes}B`
157
+ : e.info?.reason
158
+ ? e.info.reason === 'unsupported_model' && e.model
159
+ ? `skip(unsupported=${e.model})`
160
+ : `skip(${e.info.reason})`
161
+ : '';
162
+ const cacheRead = e.usage?.cache_read_input_tokens ?? e.usage?.cached_tokens ?? 0;
163
+ console.log(`${e.method} ${e.path} → ${e.status} (${e.durationMs}ms) ${tag} cache_read=${cacheRead}`);
164
+ if (e.info?.unknownStaticTags && e.info.unknownStaticTags.length > 0) {
165
+ console.warn(`[fiche warn] unknown tag(s) in static slab: ${e.info.unknownStaticTags.join(', ')}`);
166
+ }
167
+ tracker.emit(toTrackEvent(e));
168
+ },
169
+ };
170
+ const handle = createProxy(config);
171
+ return handle(req);
172
+ },
173
+ };
174
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1,84 @@
1
+ # Security Model
2
+
3
+ This document describes `fiche`'s security boundaries and the assumptions that
4
+ deployers and contributors should preserve. It is a living threat model, not a
5
+ claim that the software is free of vulnerabilities.
6
+
7
+ ## Assets
8
+
9
+ - Provider credentials in request headers or deployment configuration.
10
+ - Prompt, system-message, tool-schema, and tool-result contents.
11
+ - Rendered PNGs, export bundles, and factsheets derived from that content.
12
+ - Local event logs, optional diagnostic request bodies, and session metadata.
13
+ - Provider quota and billing attached to configured credentials.
14
+ - The npm package and its release provenance.
15
+
16
+ ## Trust boundaries
17
+
18
+ ```text
19
+ client -> Node proxy or Worker -> configured provider/gateway
20
+ |
21
+ +-> transforms and rendered context
22
+ +-> local logs/dashboard (Node) or Workers Logs
23
+
24
+ maintainer -> GitHub Actions -> npm trusted publishing
25
+ ```
26
+
27
+ The client-to-proxy and proxy-to-provider hops cross network trust boundaries.
28
+ The Node dashboard crosses a separate boundary because it exposes local stats
29
+ and captured context. Dependency installation and publishing cross the
30
+ software supply-chain boundary.
31
+
32
+ ## Security assumptions
33
+
34
+ - The Node process runs as a non-privileged user on a trusted machine.
35
+ - The default `127.0.0.1` listener is reachable only by trusted local users.
36
+ - Operators who set `HOST` to a non-loopback address provide authentication
37
+ and TLS in front of the proxy API. Dashboard routes remain loopback-only.
38
+ - Upstream URLs and gateway headers are trusted operator configuration, not
39
+ attacker-controlled request inputs.
40
+ - Anyone who can read the `fiche` log directory (`~/.fiche/`, or legacy `~/.inkling/`) or Workers Logs may learn
41
+ sensitive metadata. Diagnostic body capture is treated as secret material.
42
+ - Callers that know `FICHE_WORKER_SECRET` (or legacy `INKLING_WORKER_SECRET`) are authorized to spend credentials
43
+ configured in that Worker deployment.
44
+
45
+ ## Threats and controls
46
+
47
+ | Threat | Existing control | Contributor requirement |
48
+ | --- | --- | --- |
49
+ | Public deployment spends a configured API key | Worker requires `FICHE_WORKER_SECRET` (legacy `INKLING_WORKER_SECRET` fallback, presented via `x-fiche-secret` or `x-inkling-secret`) and fails closed | Preserve the fail-closed check and constant-work comparison tests |
50
+ | Provider credential is routed to the wrong upstream | An explicit inbound-credential x route policy (`resolveOpenAIRouteAuth`): Anthropic-shaped credentials never reach an OpenAI upstream, subscription OAuth is preserved rather than substituted, and a host key replaces only ordinary keys. Classification is by header shape; no local token store is read | Extend the policy table, not the call site, for every new route or provider, and keep the full matrix under test |
51
+ | A request reaches a provider it was not meant for | Routing is by path family: `/backend-api/*` goes to the ChatGPT upstream, Google API shapes (`/v1beta/`, `/v1alpha/`, `/v1internal:`, `models/<id>:<method>`) to Google, and `/v1/*` and `/api/*` to Anthropic. On the stock Anthropic upstream any other path answers 404 and is never forwarded with injected keys. A custom upstream keeps forwarding unknown paths | Add a new agent's paths to a family predicate in `proxy.ts`, with a `createProxy` test that checks the upstream URL and the credential that arrives |
52
+ | Prompt or secret leaks through local logs | Full 4xx body capture is opt-in; normal events retain hashes/metadata; local artifacts are owner-only | Do not add raw content to logs; document any new persistence |
53
+ | Dashboard exposes captured context | Dashboard routes require loopback source and host; cross-site mutations are rejected | Treat every dashboard route as sensitive and preserve both checks |
54
+ | A web page spends the local proxy's keys (cross-site request or DNS rebinding) | The Node proxy API refuses any `Origin` that is not loopback (403) and any `Host` that is a public DNS name other than a known provider host (421). Loopback names, IP literals, single-label container names, `*.internal` and the provider hosts `fiche warp` keeps are accepted. `FICHE_ALLOWED_HOSTS` (or legacy `INKLING_ALLOWED_HOSTS`) adds names; `*` turns the check off (`src/core/request-guard.ts`) | Keep the guard ahead of the proxy handler and test Host cases over `node:http`, since `fetch()` drops a caller-set Host |
55
+ | Oversized dashboard request exhausts memory | Dashboard request bodies are bounded | Keep bounds before parsing and add negative tests for new endpoints |
56
+ | Oversized proxy request exhausts memory | Transformable routes refuse past `maxRequestBytes` (`FICHE_MAX_REQUEST_BYTES` / legacy `INKLING_MAX_REQUEST_BYTES`, 16 MiB default) before allocating, using the streamed size rather than the declared one; label-only routes bound their model sniff and stream the remainder untouched | Never read an inbound body to completion before the limit is proven; add exact-boundary, missing-length and under-declared-length tests for new routes |
57
+ | Malicious dependency or compromised release | Frozen lockfile, three-day release-age gate, restricted lifecycle scripts, OIDC trusted publishing, provenance | Keep least-privilege workflow permissions and review lockfile/lifecycle changes |
58
+ | Vulnerable dependency remains installed | Dependabot, CodeQL/GitHub security scanning, a high-severity CI audit gate, targeted overrides | Run `pnpm audit` and remove overrides when direct dependencies adopt fixed ranges |
59
+
60
+ ## Out of scope and residual risks
61
+
62
+ - `fiche` does not authenticate the Node server or dashboard. Non-loopback
63
+ deployment without an authenticated reverse proxy is unsafe by design.
64
+ - `fiche` cannot protect content after it reaches a configured provider,
65
+ gateway, log sink, or a local user with access to its files.
66
+ - A malicious trusted operator can configure an upstream that receives request
67
+ credentials and content. Upstream configuration must not be exposed to
68
+ untrusted callers.
69
+ - Shared-secret authentication does not provide per-user identity, revocation,
70
+ rate limits, or authorization scopes. Internet-facing deployments should
71
+ add these controls at the edge.
72
+
73
+ ## Security review checklist
74
+
75
+ Changes to routing, headers, logging, persistence, dashboard endpoints,
76
+ authentication, dependencies, or release workflows should answer:
77
+
78
+ 1. Can a credential cross into the wrong provider, response, or log?
79
+ 2. Can raw prompt or tool content be persisted or displayed unexpectedly?
80
+ 3. Does an unauthenticated caller gain a new operation or resource-spend path?
81
+ 4. Are request sizes and attacker-controlled collections bounded before work?
82
+ 5. Does the change introduce a new upstream, redirect, or SSRF path?
83
+ 6. Does it broaden GitHub Actions permissions or execute new install scripts?
84
+ 7. Are failure modes fail-closed, and are they covered by regression tests?