tokensafe 4.16.1 → 4.16.2

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.16.1",
2
+ "version": "4.16.2",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.16.1",
3
+ "version": "4.16.2",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.16.1",
4
+ "version": "4.16.2",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.16.1",
4
+ "version": "4.16.2",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
7
7
  "logo": "assets/logo.png",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.16.1",
6
+ "version": "4.16.2",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.16.1",
26
+ "version": "4.16.2",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.16.1",
42
+ "version": "4.16.2",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -1,6 +1,6 @@
1
1
  """Automatic, reversible OUMV adapter wiring ("works out of the box").
2
2
 
3
- Two very different injection strategies live here, because the runtimes differ:
3
+ Several injection strategies live here, because the runtimes differ:
4
4
 
5
5
  * **Frontend (React/Vue + Vite)** — nothing is written into the repository. The
6
6
  bridge is served by ``tokensafe dev`` (a zero-footprint Vite server with an
@@ -17,6 +17,12 @@ Two very different injection strategies live here, because the runtimes differ:
17
17
  failed build reverts automatically. ``net/http`` has no anchor line to patch
18
18
  (the adapter constructs the mux), so its plan is an explicit manual recipe;
19
19
  Echo has no adapter yet and is reported as planned.
20
+ * **Spring / PHP (sidecars)** — the sidecar stays a single downloaded file, but the
21
+ dry-run sandbox behind ``verify.sandboxRollback`` has to run inside the
22
+ application: inject writes the pinned middleware (Spring filter plus an
23
+ ``@Configuration`` in the component-scan root, Laravel middleware plus one
24
+ ``->append(...)`` line in ``bootstrap/app.php``) and ``--revert`` removes only
25
+ the files it created.
20
26
 
21
27
  Every detected app gets its own manifest (``manifests/<kind>--<app>.json``), so a
22
28
  monorepo is wired app by app and one ``--revert`` undoes all of them.
@@ -1948,6 +1954,25 @@ _SIDECARS = {
1948
1954
  ),
1949
1955
  }
1950
1956
 
1957
+ # The in-process dry-run sandbox is what turns `verify.sandboxRollback` from a
1958
+ # structural claim into an observed rollback: the sidecar sends the dry-run
1959
+ # request, the middleware rolls it back on the application's own connection and
1960
+ # reports what it saw. Same release, same content addressing — `tokensafe inject`
1961
+ # copies the certified bytes into the project instead of asking the user to
1962
+ # hand-copy a file whose exact content is the thing being certified.
1963
+ _MIDDLEWARE = {
1964
+ "spring": (
1965
+ "java/src/dev/tokensafe/oumv/OumvSandboxFilter.java",
1966
+ "OumvSandboxFilter.java",
1967
+ "79e44394cd27aeef06e8578053de14cec6bbffa7f9044a461b1e197d5027eff7",
1968
+ ),
1969
+ "php": (
1970
+ "php/laravel/OumvSandbox.php",
1971
+ "OumvSandbox.php",
1972
+ "74b18bd9c6d3bd2aed2410810e40a15f6b545fb37227e0ff66ed9edb7b04f497",
1973
+ ),
1974
+ }
1975
+
1951
1976
 
1952
1977
  def _sha256_file(path: str) -> str:
1953
1978
  digest = hashlib.sha256()
@@ -1999,7 +2024,25 @@ def sidecar_cached(kind: str) -> Tuple[Optional[str], str]:
1999
2024
 
2000
2025
 
2001
2026
  def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
2002
- """Caches OumvSpring.java / oumv-php at the pinned release and verifies SHA-256.
2027
+ """Caches OumvSpring.java / oumv-php at the pinned release and verifies SHA-256."""
2028
+ if kind not in _SIDECARS:
2029
+ return None, f"unknown sidecar {kind!r}"
2030
+ rel_source, filename, expected_sha = _SIDECARS[kind]
2031
+ return _ensure_pinned(rel_source, filename, expected_sha, kind, executable=kind == "php")
2032
+
2033
+
2034
+ def ensure_middleware(kind: str) -> Tuple[Optional[str], str]:
2035
+ """Caches OumvSandboxFilter.java / OumvSandbox.php at the pinned release."""
2036
+ if kind not in _MIDDLEWARE:
2037
+ return None, f"unknown sandbox middleware {kind!r}"
2038
+ rel_source, filename, expected_sha = _MIDDLEWARE[kind]
2039
+ return _ensure_pinned(rel_source, filename, expected_sha, kind)
2040
+
2041
+
2042
+ def _ensure_pinned(
2043
+ rel_source: str, filename: str, expected_sha: str, kind: str, executable: bool = False
2044
+ ) -> Tuple[Optional[str], str]:
2045
+ """Pinned-file cache shared by the sidecars and the sandbox middleware.
2003
2046
 
2004
2047
  Order: a valid cache → a local checkout whose bytes match the pin (developer
2005
2048
  flow, no network) → download from the release tag. A hash mismatch is never
@@ -2007,16 +2050,13 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
2007
2050
  different file under the certified name. An explicit `OUMV_BACKEND_REPO` is
2008
2051
  the only way to use unpinned local bytes, and the note says so.
2009
2052
  """
2010
- if kind not in _SIDECARS:
2011
- return None, f"unknown sidecar {kind!r}"
2012
- rel_source, filename, expected_sha = _SIDECARS[kind]
2013
2053
  cache_dir = _sidecar_cache_dir()
2014
2054
  target = os.path.join(cache_dir, filename)
2015
2055
 
2016
2056
  def adopt(source: str, note: str) -> Tuple[str, str]:
2017
2057
  os.makedirs(cache_dir, exist_ok=True)
2018
2058
  shutil.copy2(source, target)
2019
- if kind == "php":
2059
+ if executable:
2020
2060
  os.chmod(target, 0o755)
2021
2061
  return target, note
2022
2062
 
@@ -2081,11 +2121,523 @@ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
2081
2121
  os.makedirs(cache_dir, exist_ok=True)
2082
2122
  with open(target, "wb") as handle:
2083
2123
  handle.write(payload)
2084
- if kind == "php":
2124
+ if executable:
2085
2125
  os.chmod(target, 0o755)
2086
2126
  return target, f"downloaded from {_SIDECAR_RELEASE_TAG}"
2087
2127
 
2088
2128
 
2129
+ # --------------------------------------------------------------------------- #
2130
+ # Sandbox middleware (verify.sandboxRollback)
2131
+ # --------------------------------------------------------------------------- #
2132
+ #
2133
+ # Both runtimes dispatch `verify` over HTTP, so a rollback on the sidecar's own
2134
+ # connection proves nothing: the write happens in the application's transaction.
2135
+ # The middleware is the side that can observe it. Java is dropped where Spring
2136
+ # Boot's component scan already looks (the entry class's package) as a filter plus
2137
+ # an `@Configuration` that registers it; PHP is written into the Laravel skeleton
2138
+ # and appended to the global middleware stack in `bootstrap/app.php`.
2139
+
2140
+ _SPRING_FILTER_CLASS = "OumvSandboxFilter"
2141
+ _SPRING_CONFIG_CLASS = "TokenSafeSandboxConfig"
2142
+ _SPRING_CONFIG_TEMPLATE = '''package {package};
2143
+
2144
+ import org.springframework.boot.web.servlet.FilterRegistrationBean;
2145
+ import org.springframework.context.annotation.Bean;
2146
+ import org.springframework.context.annotation.Configuration;
2147
+
2148
+ /**
2149
+ * Generated by `tokensafe inject` (revert with `tokensafe inject --revert`).
2150
+ *
2151
+ * Registers the OUMV dry-run filter for the whole application. The filter only
2152
+ * acts on requests carrying the X-TokenSafe-Dry-Run header, so leaving it mounted
2153
+ * in every profile changes nothing else. It needs a PlatformTransactionManager
2154
+ * bean; without one it answers not_applicable instead of inventing a rollback.
2155
+ */
2156
+ @Configuration
2157
+ public class {config} {{
2158
+
2159
+ @Bean
2160
+ public FilterRegistrationBean<{filter}> tokenSafeSandboxFilter() {{
2161
+ FilterRegistrationBean<{filter}> registration = new FilterRegistrationBean<>();
2162
+ registration.setFilter(new {filter}());
2163
+ registration.addUrlPatterns("/*");
2164
+ registration.setOrder(1);
2165
+ return registration;
2166
+ }}
2167
+ }}
2168
+ '''
2169
+
2170
+ _PHP_MIDDLEWARE_REL = os.path.join("app", "Http", "Middleware", "OumvSandbox.php")
2171
+ _PHP_MIDDLEWARE_FQCN = "\\App\\Http\\Middleware\\OumvSandbox"
2172
+ _PHP_KERNEL_REL = os.path.join("app", "Http", "Kernel.php")
2173
+ _PHP_BOOTSTRAP_REL = os.path.join("bootstrap", "app.php")
2174
+
2175
+
2176
+ def _spring_entry_package(app_root: str) -> Optional[Tuple[str, str]]:
2177
+ """(package, directory) of the `@SpringBootApplication` class, or None.
2178
+
2179
+ Spring Boot scans the entry class's package and everything below it, so a
2180
+ component dropped there is picked up without patching the application's own
2181
+ configuration files — the only reversible way to mount a filter in a project
2182
+ whose bootstrap we do not otherwise understand.
2183
+ """
2184
+ pattern = os.path.join(app_root, "src", "main", "java", "**", "*.java")
2185
+ fallback: Optional[Tuple[str, str]] = None
2186
+ for path in sorted(glob.glob(pattern, recursive=True)):
2187
+ try:
2188
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
2189
+ text = handle.read()
2190
+ except OSError:
2191
+ continue
2192
+ if "@SpringBootApplication" not in text:
2193
+ continue
2194
+ match = re.search(r"(?m)^\s*package\s+([\w.]+)\s*;", text)
2195
+ if not match:
2196
+ continue
2197
+ found = (match.group(1), os.path.dirname(path))
2198
+ if os.path.basename(path).endswith("Application.java"):
2199
+ return found
2200
+ fallback = fallback or found
2201
+ return fallback
2202
+
2203
+
2204
+ def _spring_jakarta(app_root: str) -> Optional[bool]:
2205
+ """True for Spring Boot 3+ (jakarta.servlet), False for Boot 2, None if unknown.
2206
+
2207
+ The pinned filter imports `jakarta.servlet`; writing it into a Boot 2 project
2208
+ would break their build, so an unproven version is treated as "do not write".
2209
+ """
2210
+ candidates = [
2211
+ os.path.join(app_root, "pom.xml"),
2212
+ os.path.join(app_root, "build.gradle"),
2213
+ os.path.join(app_root, "build.gradle.kts"),
2214
+ ]
2215
+ for path in candidates:
2216
+ if not os.path.isfile(path):
2217
+ continue
2218
+ try:
2219
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
2220
+ text = handle.read()
2221
+ except OSError:
2222
+ continue
2223
+ versions = re.findall(
2224
+ r"(?:(?:spring-boot-starter-parent|spring-boot-dependencies|spring-boot-starter-web)"
2225
+ r"</artifactId>\s*<version>|"
2226
+ r"(?:springBootVersion|spring-boot\.version)\s*[=:]\s*['\"]|"
2227
+ r"id\s*\(?\s*['\"]org\.springframework\.boot['\"]\s*\)?\s*version\s*['\"])([0-9][^'\"<\s]*)",
2228
+ text,
2229
+ )
2230
+ for version in versions:
2231
+ major = version.split(".")[0]
2232
+ if major == "2":
2233
+ return False
2234
+ if major.isdigit() and int(major) >= 3:
2235
+ return True
2236
+ return None
2237
+
2238
+
2239
+ def _spring_targets(app_root: str) -> Optional[List[str]]:
2240
+ found = _spring_entry_package(app_root)
2241
+ if not found:
2242
+ return None
2243
+ package, directory = found
2244
+ target_dir = os.path.join(directory, "tokensafe")
2245
+ return [
2246
+ os.path.join(target_dir, _SPRING_FILTER_CLASS + ".java"),
2247
+ os.path.join(target_dir, _SPRING_CONFIG_CLASS + ".java"),
2248
+ ]
2249
+
2250
+
2251
+ def _already_present(app_root: str, relative_root: str, filename: str, targets: List[str]) -> Optional[str]:
2252
+ """A copy of the middleware outside our target paths: inject must not mount it twice."""
2253
+ pattern = os.path.join(app_root, relative_root, "**", filename)
2254
+ wanted = {os.path.abspath(path) for path in targets}
2255
+ for path in sorted(glob.glob(pattern, recursive=True)):
2256
+ if os.path.abspath(path) not in wanted:
2257
+ return os.path.relpath(path, app_root)
2258
+ return None
2259
+
2260
+
2261
+ def _php_register_in_bootstrap(text: str) -> Optional[str]:
2262
+ """Adds the append line to `bootstrap/app.php`, or None when there is no anchor.
2263
+
2264
+ An existing `->withMiddleware(...)` closure is preferred: the line goes inside
2265
+ it and reuses the closure's own parameter name. Otherwise a whole
2266
+ `->withMiddleware(...)` call is inserted before `->create()`. Returning None
2267
+ means the file is shaped in a way we refuse to guess about.
2268
+ """
2269
+ if re.search(r"append\s*\([^)]*OumvSandbox", text):
2270
+ return text
2271
+ match = re.search(
2272
+ r"->withMiddleware\s*\(\s*(?:static\s+)?function\s*\(([^)]*)\)[^{]*\{", text
2273
+ )
2274
+ if match:
2275
+ params = re.findall(r"\$(\w+)", match.group(1))
2276
+ variable = params[-1] if params else "middleware"
2277
+ line_start = text.rfind("\n", 0, match.start()) + 1
2278
+ indent = re.match(r"[ \t]*", text[line_start:]).group(0) + " "
2279
+ line = f"\n{indent}${variable}->append({_PHP_MIDDLEWARE_FQCN}::class);"
2280
+ return text[: match.end()] + line + text[match.end():]
2281
+ create = text.rfind("->create()")
2282
+ if create < 0:
2283
+ return None
2284
+ line_start = text.rfind("\n", 0, create) + 1
2285
+ indent = text[line_start:create]
2286
+ if indent.strip():
2287
+ # `->create()` shares a line with other calls: there is no clean anchor.
2288
+ return None
2289
+ block = (
2290
+ f"{indent}->withMiddleware(function "
2291
+ f"(\\Illuminate\\Foundation\\Configuration\\Middleware $middleware): void {{\n"
2292
+ f"{indent} $middleware->append({_PHP_MIDDLEWARE_FQCN}::class);\n"
2293
+ f"{indent}}})\n"
2294
+ )
2295
+ return text[:line_start] + block + text[line_start:]
2296
+
2297
+
2298
+ def plan_middleware(workspace: str, provider: str, app_root: str) -> Dict[str, Any]:
2299
+ """What injecting the sandbox middleware would write (no network, no writes)."""
2300
+ if provider == "spring":
2301
+ targets = _spring_targets(app_root)
2302
+ if not targets:
2303
+ return {
2304
+ "status": "manual",
2305
+ "writes_repo": False,
2306
+ "reason": (
2307
+ "no @SpringBootApplication class under src/main/java — mount "
2308
+ "OumvSandboxFilter by hand (Spring adapter docs)"
2309
+ ),
2310
+ }
2311
+ elsewhere = _already_present(
2312
+ app_root, os.path.join("src", "main", "java"), _SPRING_FILTER_CLASS + ".java", targets
2313
+ )
2314
+ if elsewhere:
2315
+ return {
2316
+ "status": "already_present",
2317
+ "writes_repo": False,
2318
+ "files": [elsewhere],
2319
+ "reason": (
2320
+ f"the filter already exists at {elsewhere}; nothing is written "
2321
+ "(a second mount would roll the same request back twice)"
2322
+ ),
2323
+ }
2324
+ jakarta = _spring_jakarta(app_root)
2325
+ if jakarta is False:
2326
+ return {
2327
+ "status": "skipped",
2328
+ "writes_repo": False,
2329
+ "reason": "Spring Boot 2 uses javax.servlet; the pinned filter targets Jakarta (Boot 3+)",
2330
+ }
2331
+ if jakarta is None:
2332
+ return {
2333
+ "status": "manual",
2334
+ "writes_repo": False,
2335
+ "auto": False,
2336
+ "reason": "could not confirm Spring Boot 3+ (jakarta.servlet) — add the filter by hand",
2337
+ }
2338
+ return {
2339
+ "status": "ready",
2340
+ "writes_repo": True,
2341
+ "auto": True,
2342
+ "files": [os.path.relpath(path, workspace) for path in targets],
2343
+ "registration": "component scan (@Configuration next to the entry class)",
2344
+ "description": (
2345
+ "OumvSandboxFilter.java plus a TokenSafeSandboxConfig that registers it for /*; "
2346
+ "the filter is inert without X-TokenSafe-Dry-Run"
2347
+ ),
2348
+ }
2349
+ if provider == "php":
2350
+ bootstrap = os.path.join(app_root, _PHP_BOOTSTRAP_REL)
2351
+ target = os.path.join(app_root, _PHP_MIDDLEWARE_REL)
2352
+ relative = os.path.relpath(target, workspace)
2353
+ elsewhere = _already_present(app_root, "app", os.path.basename(_PHP_MIDDLEWARE_REL), [target])
2354
+ if elsewhere:
2355
+ return {
2356
+ "status": "already_present",
2357
+ "writes_repo": False,
2358
+ "files": [elsewhere],
2359
+ "reason": f"the middleware already exists at {elsewhere}; nothing is written",
2360
+ }
2361
+ if os.path.isfile(bootstrap):
2362
+ try:
2363
+ with open(bootstrap, "r", encoding="utf-8", errors="replace") as handle:
2364
+ text = handle.read()
2365
+ except OSError:
2366
+ text = ""
2367
+ if "Application::configure" in text and _php_register_in_bootstrap(text) is not None:
2368
+ return {
2369
+ "status": "ready",
2370
+ "writes_repo": True,
2371
+ "auto": True,
2372
+ "files": [relative],
2373
+ "registration": _PHP_BOOTSTRAP_REL,
2374
+ "registered": bool(re.search(r"append\s*\([^)]*OumvSandbox", text)),
2375
+ "description": (
2376
+ "Laravel middleware plus one $middleware->append(...) line in bootstrap/app.php; "
2377
+ "inert without X-TokenSafe-Dry-Run"
2378
+ ),
2379
+ }
2380
+ if os.path.isfile(os.path.join(app_root, _PHP_KERNEL_REL)):
2381
+ return {
2382
+ "status": "manual",
2383
+ "writes_repo": True,
2384
+ "auto": True,
2385
+ "files": [relative],
2386
+ "reason": "Laravel 10 kernel: the file is written, the one-line registration is manual",
2387
+ "snippet": (
2388
+ "// app/Http/Kernel.php, in protected $middleware = [\n"
2389
+ f"{_PHP_MIDDLEWARE_FQCN}::class,"
2390
+ ),
2391
+ }
2392
+ return {
2393
+ "status": "skipped",
2394
+ "writes_repo": False,
2395
+ "reason": (
2396
+ "not a Laravel skeleton (no bootstrap/app.php or app/Http/Kernel.php); "
2397
+ "Symfony wiring stays manual"
2398
+ ),
2399
+ }
2400
+ return {"status": "skipped", "writes_repo": False, "reason": f"no sandbox middleware for {provider!r}"}
2401
+
2402
+
2403
+ def apply_middleware(
2404
+ workspace: str, app_root: str, provider: str, dry_run: bool = False
2405
+ ) -> Dict[str, Any]:
2406
+ """Writes the pinned sandbox middleware into `app_root`; revertible per file."""
2407
+ plan = plan_middleware(workspace, provider, app_root)
2408
+ if dry_run:
2409
+ return {**plan, "status": "would-write" if plan.get("auto") else plan["status"]}
2410
+ if not plan.get("auto"):
2411
+ return plan
2412
+
2413
+ cached, note = ensure_middleware(provider)
2414
+ if not cached:
2415
+ return {"status": "needs-source", "note": note, "reason": "middleware source is not cached"}
2416
+
2417
+ if provider == "spring":
2418
+ return _apply_spring_middleware(workspace, app_root, cached)
2419
+ return _apply_php_middleware(workspace, app_root, cached, plan)
2420
+
2421
+
2422
+ def _write_bytes(path: str, payload: bytes) -> None:
2423
+ os.makedirs(os.path.dirname(path), exist_ok=True)
2424
+ with open(path, "wb") as handle:
2425
+ handle.write(payload)
2426
+
2427
+
2428
+ def _existing_bytes(path: str) -> Optional[bytes]:
2429
+ if not os.path.isfile(path):
2430
+ return None
2431
+ try:
2432
+ with open(path, "rb") as handle:
2433
+ return handle.read()
2434
+ except OSError:
2435
+ return None
2436
+
2437
+
2438
+ def _missing_dirs(app_root: str, paths: List[str]) -> List[str]:
2439
+ """Directories a write would create, so revert can remove the empty ones."""
2440
+ created: List[str] = []
2441
+ for path in paths:
2442
+ directory = os.path.dirname(path)
2443
+ while os.path.abspath(directory).startswith(os.path.abspath(app_root)):
2444
+ if not os.path.isdir(directory):
2445
+ created.append(os.path.relpath(directory, app_root))
2446
+ directory = os.path.dirname(directory)
2447
+ continue
2448
+ break
2449
+ return sorted(set(created))
2450
+
2451
+
2452
+ def _apply_spring_middleware(workspace: str, app_root: str, cached: str) -> Dict[str, Any]:
2453
+ found = _spring_entry_package(app_root)
2454
+ if not found:
2455
+ return {"status": "manual", "reason": "the entry class disappeared between plan and apply"}
2456
+ package = found[0] + ".tokensafe"
2457
+ targets = _spring_targets(app_root) or []
2458
+ with open(cached, "r", encoding="utf-8") as handle:
2459
+ filter_source = handle.read()
2460
+ rewritten = re.sub(
2461
+ r"(?m)^\s*package\s+[\w.]+\s*;", f"package {package};", filter_source, count=1
2462
+ )
2463
+ if rewritten == filter_source and f"package {package};" not in filter_source:
2464
+ # The pin guarantees the bytes, but a file without a package line cannot be
2465
+ # moved into the scan root: refuse instead of writing code that will not compile.
2466
+ return {"status": "error", "reason": "the pinned filter has no package declaration to rewrite"}
2467
+ config_source = _SPRING_CONFIG_TEMPLATE.format(
2468
+ package=package, config=_SPRING_CONFIG_CLASS, filter=_SPRING_FILTER_CLASS
2469
+ )
2470
+ payloads = [
2471
+ (targets[0], rewritten.encode("utf-8")),
2472
+ (targets[1], config_source.encode("utf-8")),
2473
+ ]
2474
+
2475
+ conflicts = [
2476
+ os.path.relpath(path, workspace)
2477
+ for path, payload in payloads
2478
+ if _existing_bytes(path) not in (None, payload)
2479
+ ]
2480
+ if conflicts:
2481
+ return {
2482
+ "status": "conflict",
2483
+ "kept": [{"path": path, "reason": "exists with different content"} for path in conflicts],
2484
+ "reason": "refusing to overwrite an existing file that is not the pinned middleware",
2485
+ }
2486
+
2487
+ created = []
2488
+ dirs = _missing_dirs(workspace, [path for path, _ in payloads])
2489
+ for path, payload in payloads:
2490
+ if _existing_bytes(path) == payload:
2491
+ continue
2492
+ _write_bytes(path, payload)
2493
+ created.append({"path": os.path.relpath(path, workspace), "sha": hashlib.sha256(payload).hexdigest()})
2494
+
2495
+ app_rel = os.path.relpath(app_root, workspace)
2496
+ if created:
2497
+ _write_manifest(workspace, "spring_middleware", {
2498
+ "kind": "spring_middleware",
2499
+ "app": app_rel,
2500
+ "provider": "spring",
2501
+ "package": package,
2502
+ "created": created,
2503
+ "dirs": dirs,
2504
+ })
2505
+ return {
2506
+ "status": "patched" if created else "already_patched",
2507
+ "files": [entry["path"] for entry in created] or [os.path.relpath(path, workspace) for path, _ in payloads],
2508
+ "registration": "component scan (@Configuration next to the entry class)",
2509
+ "note": "verify.sandboxRollback reports not_applicable until the app exposes a PlatformTransactionManager",
2510
+ }
2511
+
2512
+
2513
+ def _apply_php_middleware(
2514
+ workspace: str, app_root: str, cached: str, plan: Dict[str, Any]
2515
+ ) -> Dict[str, Any]:
2516
+ target = os.path.join(app_root, _PHP_MIDDLEWARE_REL)
2517
+ with open(cached, "rb") as handle:
2518
+ payload = handle.read()
2519
+ existing = _existing_bytes(target)
2520
+ if existing not in (None, payload):
2521
+ return {
2522
+ "status": "conflict",
2523
+ "kept": [{"path": os.path.relpath(target, workspace), "reason": "exists with different content"}],
2524
+ "reason": "refusing to overwrite an existing file that is not the pinned middleware",
2525
+ }
2526
+
2527
+ created = []
2528
+ if existing is None:
2529
+ dirs = _missing_dirs(workspace, [target])
2530
+ _write_bytes(target, payload)
2531
+ created.append({"path": os.path.relpath(target, workspace), "sha": hashlib.sha256(payload).hexdigest()})
2532
+ else:
2533
+ dirs = []
2534
+
2535
+ registration: Dict[str, Any] = {"status": "manual", "path": _PHP_KERNEL_REL}
2536
+ bootstrap = os.path.join(app_root, _PHP_BOOTSTRAP_REL)
2537
+ bootstrap_rel = os.path.relpath(bootstrap, workspace)
2538
+ if os.path.isfile(bootstrap):
2539
+ with open(bootstrap, "r", encoding="utf-8") as handle:
2540
+ original = handle.read()
2541
+ patched = _php_register_in_bootstrap(original)
2542
+ if patched is None:
2543
+ registration = {"status": "manual", "path": bootstrap_rel}
2544
+ elif patched == original:
2545
+ registration = {"status": "already_registered", "path": bootstrap_rel}
2546
+ else:
2547
+ backup = _backup_path(workspace, bootstrap)
2548
+ os.makedirs(os.path.dirname(backup), exist_ok=True)
2549
+ shutil.copy2(bootstrap, backup)
2550
+ with open(bootstrap, "w", encoding="utf-8", newline="") as handle:
2551
+ handle.write(patched)
2552
+ registration = {
2553
+ "status": "registered",
2554
+ "path": bootstrap_rel,
2555
+ "backup": backup,
2556
+ "patched_sha": _sha256_file(bootstrap),
2557
+ }
2558
+
2559
+ app_rel = os.path.relpath(app_root, workspace)
2560
+ if created or registration.get("status") == "registered":
2561
+ _write_manifest(workspace, "php_middleware", {
2562
+ "kind": "php_middleware",
2563
+ "app": app_rel,
2564
+ "provider": "php",
2565
+ "created": created,
2566
+ "dirs": dirs,
2567
+ "registration": registration,
2568
+ })
2569
+ status = "patched" if created or registration.get("status") == "registered" else "already_patched"
2570
+ result = {
2571
+ "status": status,
2572
+ "files": [entry["path"] for entry in created] or [os.path.relpath(target, workspace)],
2573
+ "registration": registration.get("status"),
2574
+ }
2575
+ if registration.get("status") == "manual":
2576
+ result["snippet"] = plan.get("snippet") or (
2577
+ "// bootstrap/app.php: add one ->withMiddleware(...) append, or register in app/Http/Kernel.php"
2578
+ )
2579
+ result["reason"] = "the app skeleton has no anchor we can patch safely"
2580
+ return result
2581
+
2582
+
2583
+ def _remove_created(workspace: str, manifest: Dict[str, Any]) -> Tuple[List[str], List[Dict[str, str]]]:
2584
+ """Deletes the files inject created, but only while they are still its bytes."""
2585
+ removed: List[str] = []
2586
+ kept: List[Dict[str, str]] = []
2587
+ for entry in manifest.get("created") or []:
2588
+ target = os.path.join(workspace, entry.get("path", ""))
2589
+ if not os.path.isfile(target):
2590
+ continue
2591
+ if entry.get("sha") and _sha256_file(target) != entry["sha"]:
2592
+ kept.append({"path": entry["path"], "reason": "modified after inject"})
2593
+ continue
2594
+ os.unlink(target)
2595
+ removed.append(entry["path"])
2596
+ for relative in sorted(manifest.get("dirs") or [], key=len, reverse=True):
2597
+ try:
2598
+ os.rmdir(os.path.join(workspace, relative))
2599
+ except OSError:
2600
+ pass
2601
+ return removed, kept
2602
+
2603
+
2604
+ def revert_spring_middleware(workspace: str, manifest: Dict[str, Any]) -> Dict[str, Any]:
2605
+ removed, kept = _remove_created(workspace, manifest)
2606
+ _delete_manifest(manifest)
2607
+ result: Dict[str, Any] = {"status": "reverted", "removed": removed}
2608
+ if kept:
2609
+ result["kept"] = kept
2610
+ return result
2611
+
2612
+
2613
+ def revert_php_middleware(workspace: str, manifest: Dict[str, Any]) -> Dict[str, Any]:
2614
+ restored: List[str] = []
2615
+ kept: List[Dict[str, str]] = []
2616
+ registration = manifest.get("registration") or {}
2617
+ if registration.get("status") == "registered":
2618
+ bootstrap = os.path.join(workspace, registration.get("path") or _PHP_BOOTSTRAP_REL)
2619
+ backup = registration.get("backup") or ""
2620
+ if not os.path.isfile(bootstrap):
2621
+ kept.append({"path": registration.get("path"), "reason": "bootstrap/app.php is gone"})
2622
+ elif not backup or not os.path.isfile(backup):
2623
+ kept.append({"path": registration.get("path"), "reason": "backup is missing"})
2624
+ elif registration.get("patched_sha") and _sha256_file(bootstrap) != registration["patched_sha"]:
2625
+ kept.append({"path": registration.get("path"), "reason": "modified after inject"})
2626
+ else:
2627
+ shutil.copy2(backup, bootstrap)
2628
+ os.unlink(backup)
2629
+ restored.append(registration.get("path"))
2630
+ removed, created_kept = _remove_created(workspace, manifest)
2631
+ kept.extend(created_kept)
2632
+ _delete_manifest(manifest)
2633
+ result: Dict[str, Any] = {"status": "reverted", "removed": removed}
2634
+ if restored:
2635
+ result["restored"] = restored
2636
+ if kept:
2637
+ result["kept"] = kept
2638
+ return result
2639
+
2640
+
2089
2641
  def _injectable_apps(stack: Dict[str, Any]) -> List[Dict[str, Any]]:
2090
2642
  """Every detected app that can be planned/injected, root first.
2091
2643
 
@@ -2355,17 +2907,26 @@ def plan(workspace: str) -> Dict[str, Any]:
2355
2907
  })
2356
2908
  elif provider in ("spring", "php"):
2357
2909
  sidecar_path, note = sidecar_cached(provider)
2358
- actions.append({
2910
+ middleware = plan_middleware(workspace, provider, _app_root(workspace, root))
2911
+ action = {
2359
2912
  "kind": "sidecar",
2360
2913
  "profile": "backend",
2361
2914
  "app": root,
2362
2915
  "framework": framework or provider,
2363
- "writes_repo": False,
2916
+ "writes_repo": bool(middleware.get("writes_repo")),
2364
2917
  "sidecar": sidecar_path,
2365
2918
  "install": note,
2366
2919
  "run": sidecar_run_command(provider, sidecar_path or "", workspace),
2367
- "description": "static route scan + OCC edits + verify through the single-file sidecar; nothing is written into the project",
2368
- })
2920
+ "middleware": middleware,
2921
+ "description": (
2922
+ "static route scan + OCC edits + verify through the single-file sidecar; "
2923
+ "the sandbox middleware is written into the project so verify.sandboxRollback "
2924
+ "rolls the request back on the application's own connection"
2925
+ ),
2926
+ }
2927
+ if middleware.get("reason"):
2928
+ action["reason"] = middleware["reason"]
2929
+ actions.append(action)
2369
2930
 
2370
2931
  db = detect_orm(workspace)
2371
2932
  for action in actions:
@@ -2516,6 +3077,9 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
2516
3077
  sidecar_cached(provider) if dry_run else ensure_sidecar(provider)
2517
3078
  )
2518
3079
  sidecar_path, note = sidecars[provider]
3080
+ middleware = apply_middleware(
3081
+ workspace, _app_root(workspace, root), provider, dry_run=dry_run
3082
+ )
2519
3083
  results["actions"].append({
2520
3084
  "kind": "sidecar",
2521
3085
  "profile": "backend",
@@ -2524,6 +3088,7 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
2524
3088
  "sidecar": sidecar_path,
2525
3089
  "note": note,
2526
3090
  "run": sidecar_run_command(provider, sidecar_path or "", workspace),
3091
+ "middleware": middleware,
2527
3092
  })
2528
3093
 
2529
3094
  return results
@@ -2543,13 +3108,17 @@ def _revert_manifest(workspace: str, kind: str, manifest: Dict[str, Any]) -> Dic
2543
3108
  return revert_next_patch(workspace, app, manifest)
2544
3109
  if kind == "python":
2545
3110
  return revert_python_autoload(workspace, manifest)
3111
+ if kind == "spring_middleware":
3112
+ return revert_spring_middleware(workspace, manifest)
3113
+ if kind == "php_middleware":
3114
+ return revert_php_middleware(workspace, manifest)
2546
3115
  return {"status": "error", "reason": f"unknown manifest kind {kind!r}"}
2547
3116
 
2548
3117
 
2549
3118
  def revert(workspace: str) -> Dict[str, Any]:
2550
3119
  """Reverts every per-app manifest, then the config state."""
2551
3120
  results: Dict[str, Any] = {"workspace": workspace}
2552
- for kind in ("go", "node", "elysia", "dotnet", "next", "python"):
3121
+ for kind in ("go", "node", "elysia", "dotnet", "next", "python", "spring_middleware", "php_middleware"):
2553
3122
  results[kind] = {"status": "nothing-to-revert"}
2554
3123
 
2555
3124
  base = os.path.join(_inject_dir(workspace), "manifests")
package/src/cli.py CHANGED
@@ -981,6 +981,10 @@ def main(argv: Optional[List[str]] = None):
981
981
  print(f" install: {action['install']}")
982
982
  if action.get("run"):
983
983
  print(f" run: {action['run']}")
984
+ middleware = action.get("middleware") or {}
985
+ if middleware:
986
+ files = ", ".join(middleware.get("files") or []) or "-"
987
+ print(f" middleware: {middleware.get('status')} ({files})")
984
988
  if action.get("reason"):
985
989
  print(f" reason: {action['reason']}")
986
990
  if action.get("snippet"):
@@ -1024,6 +1028,10 @@ def main(argv: Optional[List[str]] = None):
1024
1028
  app = action.get("app")
1025
1029
  where = f" [{app}]" if app not in (None, ".", "") else ""
1026
1030
  print(f" {prefix}{action['kind']}{where}: {status}")
1031
+ middleware = action.get("middleware") or {}
1032
+ if middleware:
1033
+ files = ", ".join(middleware.get("files") or []) or "-"
1034
+ print(f" middleware: {middleware.get('status')} ({files})")
1027
1035
  if action.get("run"):
1028
1036
  print(f" run: {action['run']}")
1029
1037
  if action.get("reason"):
package/src/mcp_server.py CHANGED
@@ -48,7 +48,7 @@ from src.session_context import current_root, current_session_id
48
48
 
49
49
  SERVER_INFO = {
50
50
  "name": "tokensafe-mcp",
51
- "version": "4.16.1"
51
+ "version": "4.16.2"
52
52
  }
53
53
 
54
54
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -311,7 +311,7 @@ class TelemetrySync:
311
311
  current_last_id = last_id
312
312
  headers = {
313
313
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.16.1"
314
+ "User-Agent": "TokenSafe-Sync/4.16.2"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.16.1"
20
+ CURRENT_VERSION = "4.16.2"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage