File size: 18,169 Bytes
6381aad
2e959d1
 
 
 
 
 
 
 
 
 
6381aad
 
 
 
 
 
 
 
 
 
 
 
 
 
2922f81
 
 
 
6381aad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2922f81
6381aad
 
 
 
 
 
2922f81
 
6381aad
 
 
 
 
 
2e959d1
b092566
2e959d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6381aad
b092566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c9a69
2c905a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c9a69
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#!/usr/bin/env python3
"""Deployment patches for DeepSeek Harness (manus-lite Space).

Patch 1: remove the loopback/remote differentiation (isLoopback -> true).
Patch 2: switch off the browser-session launch-token gate
         (BROWSER_AUTH_DISABLED = true in browser-auth.ts).

Both fail loudly (non-zero exit, no partial edit) when the upstream source
text is not found exactly as expected — a silent no-op patch is worse than
a failed build. Pinned to the upstream commit the patches were verified
against; bump deliberately.
"""

from __future__ import annotations

import sys
from pathlib import Path

TARGET = Path("/opt/dsh/packages/client/connection/src/client/index.ts")

OLD_IMPORT = "import { isLoopbackHostname } from '../loopback-hostname.ts'\n"
OLD_DERIVATION = (
    "    isLoopback: transport?.ownsHost === true || pageLocation === undefined"
    " || isLoopbackHostname(pageLocation.hostname),\n"
)
# The derivation above was the only consumer of this declaration; leaving it
# would trip TS6133 (noUnusedLocals). A different `pageLocation` in another
# function (declared from `typeof location`) is untouched.
OLD_PAGELOCATION_DECL = "  const pageLocation = options.location\n"
NEW_DERIVATION = (
    "    isLoopback: true, // DEPLOYMENT OVERRIDE (manus-lite): the loopback/remote"
    " differentiation is removed; every operator receives the full local surface.\n"
)
OLD_DOC = """  /**
   * Whether the privileged surface is reachable: the page authority is
   * loopback, the transport declares the page owns the Host
   * ({@link ClientTransportHooks.ownsHost}), or the context is not a browser.
   */
"""
NEW_DOC = """  /**
   * Whether the privileged surface is reachable. Deployment override: always
   * true, so local and remote operators receive the same full settings and
   * persistence surface.
   */
"""


def replace_once(text: str, old: str, new: str, label: str) -> str:
    count = text.count(old)
    if count != 1:
        raise SystemExit(
            f"PATCH FAILED [{label}]: expected the source text exactly once, found {count}x. "
            "Upstream changed — refusing to guess."
        )
    return text.replace(old, new, 1)


def main() -> None:
    if not TARGET.is_file():
        raise SystemExit(f"PATCH FAILED: {TARGET} does not exist")
    text = TARGET.read_text()

    text = replace_once(text, OLD_DOC, NEW_DOC, "isLoopback JSDoc")
    text = replace_once(text, OLD_DERIVATION, NEW_DERIVATION, "isLoopback derivation")
    text = replace_once(text, OLD_PAGELOCATION_DECL, "", "now-unused pageLocation declaration")
    text = replace_once(text, OLD_IMPORT, "", "now-unused isLoopbackHostname import")

    # Post-conditions: the detection must be fully gone from this file, and the
    # server-side fence (a different file) must be untouched by this script.
    if "isLoopbackHostname" in text:
        raise SystemExit("PATCH FAILED: isLoopbackHostname still referenced after patch")
    if "pageLocation = options.location" in text:
        raise SystemExit("PATCH FAILED: options.location declaration still present")
    if "isLoopback: true," not in text:
        raise SystemExit("PATCH FAILED: new derivation not present after patch")

    TARGET.write_text(text)
    print("patch applied: ctx.connection.isLoopback is now unconditionally true")

    patch_browser_auth()
    patch_session_link_fallback()


# ---------------------------------------------------------------------------
# Patch 2: disable the browser-session launch-token gate.
#
# What it changes (one isolated switch):
#   packages/client/connection/src/browser-auth.ts
#     + const BROWSER_AUTH_DISABLED = true
#     + early `return true` in isAuthenticated() and authorizeIndex()
#     + authenticatedUrl() no longer appends ?token=
#
# Why this shape: the two enforcement points (the 401 on API/fetch routes via
# requestRejection -> isAuthenticated, and the index gate via authorizeIndex)
# are bypassed, while the token/cookie machinery underneath stays intact.
# Flipping BROWSER_AUTH_DISABLED back to false restores the stock behavior,
# which keeps this repurposing-friendly: the auth code is switched off, not
# ripped out.
# ---------------------------------------------------------------------------

AUTH_TARGET = Path("/opt/dsh/packages/client/connection/src/browser-auth.ts")

OLD_CONST_ANCHOR = "const PROCESS_LAUNCH_TOKENS = new WeakMap<object, string>()\n"
NEW_CONST_ANCHOR = (
    "const PROCESS_LAUNCH_TOKENS = new WeakMap<object, string>()\n"
    "/**\n"
    " * Deployment switch (manus-lite): the browser-session launch-token gate\n"
    " * is switched off; the Space's own access control is the gate. The\n"
    " * token/cookie machinery below stays intact — flip this back to false\n"
    " * to restore the stock authentication behavior.\n"
    " */\n"
    "const BROWSER_AUTH_DISABLED = true\n"
)

OLD_AUTHORIZE_INDEX = (
    "  authorizeIndex(req: ConnectionIndexRequest, res: ConnectionIndexResponse): boolean {\n"
    "    /* v8 ignore next -- node:http always supplies url on server requests. */\n"
)
NEW_AUTHORIZE_INDEX = (
    "  authorizeIndex(req: ConnectionIndexRequest, res: ConnectionIndexResponse): boolean {\n"
    "    if (BROWSER_AUTH_DISABLED) return true\n"
    "    /* v8 ignore next -- node:http always supplies url on server requests. */\n"
)

OLD_IS_AUTHENTICATED = (
    "  isAuthenticated(request: ConnectionTrustRequest): boolean {\n"
    "    const authority = requestAuthority(request.headers)\n"
)
NEW_IS_AUTHENTICATED = (
    "  isAuthenticated(request: ConnectionTrustRequest): boolean {\n"
    "    if (BROWSER_AUTH_DISABLED) return true\n"
    "    const authority = requestAuthority(request.headers)\n"
)

OLD_TOKEN_URL = "    url.searchParams.set(TOKEN_QUERY, this.launchToken)\n"
NEW_TOKEN_URL = (
    "    if (!BROWSER_AUTH_DISABLED) url.searchParams.set(TOKEN_QUERY, this.launchToken)\n"
)


def patch_browser_auth() -> None:
    if not AUTH_TARGET.is_file():
        raise SystemExit(f"PATCH FAILED: {AUTH_TARGET} does not exist")
    text = AUTH_TARGET.read_text()

    text = replace_once(text, OLD_CONST_ANCHOR, NEW_CONST_ANCHOR, "BROWSER_AUTH_DISABLED constant")
    text = replace_once(text, OLD_AUTHORIZE_INDEX, NEW_AUTHORIZE_INDEX, "authorizeIndex bypass")
    text = replace_once(text, OLD_IS_AUTHENTICATED, NEW_IS_AUTHENTICATED, "isAuthenticated bypass")
    text = replace_once(text, OLD_TOKEN_URL, NEW_TOKEN_URL, "authenticatedUrl token skip")

    # Post-conditions.
    if "BROWSER_AUTH_DISABLED = true" not in text:
        raise SystemExit("PATCH FAILED: deployment switch not present after patch")
    if text.count("if (BROWSER_AUTH_DISABLED) return true") != 2:
        raise SystemExit("PATCH FAILED: expected exactly two enforcement bypasses")
    if text.count("if (!BROWSER_AUTH_DISABLED) url.searchParams.set") != 1:
        raise SystemExit("PATCH FAILED: token URL skip not present after patch")

    AUTH_TARGET.write_text(text)
    print("patch applied: browser-session launch-token gate is switched off")


# ---------------------------------------------------------------------------
# Patch 3: session publish fallback when hard links are unsupported.
#
# What it changes (one isolated fallback):
#   packages/session/session-persistence-jsonl/src/generation.ts
#     + isENOTSUP() errno helper next to isEEXIST()
#     + publishCurrentExclusive(): when fs.link() fails with ENOTSUP, publish
#       by exclusive-create ('wx') plus copy instead of failing the turn.
#
# Why this shape: the Space's bucket filesystem (FUSE) does not implement
# hard links, so every session persist failed with ENOTSUP and every chat
# turn died before any model was invoked. The link() path stays primary on
# filesystems that support it; the fallback only triggers on ENOTSUP. The
# 'wx' open preserves the EEXIST arbitration (a lost publish race still
# returns false), and bytes are fsynced before close to keep the durability
# contract. Flipping nothing back is needed on normal filesystems — the
# fallback is inert there.
# ---------------------------------------------------------------------------

SESSION_TARGET = Path("/opt/dsh/packages/session/session-persistence-jsonl/src/generation.ts")

OLD_IS_EEXIST = (
    "function isEEXIST(error: unknown): boolean {\n"
    "  return (error as NodeJS.ErrnoException | null)?.code === 'EEXIST'\n"
    "}\n"
)
NEW_IS_EEXIST = (
    "function isEEXIST(error: unknown): boolean {\n"
    "  return (error as NodeJS.ErrnoException | null)?.code === 'EEXIST'\n"
    "}\n"
    "\n"
    "/** Deployment probe (manus-lite): hard links are unsupported on the Space's bucket filesystem. */\n"
    "function isENOTSUP(error: unknown): boolean {\n"
    "  return (error as NodeJS.ErrnoException | null)?.code === 'ENOTSUP'\n"
    "}\n"
)

OLD_PUBLISH_LINK = (
    "  try {\n"
    "    await internals.fs.link(staged, currentPath)\n"
    "  } catch (error) {\n"
    "    /* v8 ignore else -- a non-collision filesystem error propagates unchanged. */\n"
    "    if (isEEXIST(error)) return false\n"
    "    /* v8 ignore next -- the filesystem error is already complete. */\n"
    "    throw error\n"
    "  }\n"
)
NEW_PUBLISH_LINK = (
    "  try {\n"
    "    await internals.fs.link(staged, currentPath)\n"
    "  } catch (error) {\n"
    "    /* v8 ignore else -- a non-collision filesystem error propagates unchanged. */\n"
    "    if (isEEXIST(error)) return false\n"
    "    if (!isENOTSUP(error)) {\n"
    "      /* v8 ignore next -- the filesystem error is already complete. */\n"
    "      throw error\n"
    "    }\n"
    "    // DEPLOYMENT OVERRIDE (manus-lite): the Space's bucket filesystem does\n"
    "    // not implement hard links (link() fails with ENOTSUP). Publish by\n"
    "    // exclusive-create plus copy instead: the 'wx' open keeps the EEXIST\n"
    "    // arbitration, and the bytes are fsynced before close to keep the\n"
    "    // durability contract of the link path.\n"
    "    const fallbackBytes = await internals.fs.readFile(staged)\n"
    "    let fallbackHandle: FileHandle\n"
    "    try {\n"
    "      fallbackHandle = await internals.fs.open(currentPath, 'wx')\n"
    "    } catch (openError) {\n"
    "      if (isEEXIST(openError)) return false\n"
    "      throw openError\n"
    "    }\n"
    "    try {\n"
    "      await fallbackHandle.writeFile(fallbackBytes)\n"
    "      await fallbackHandle.sync()\n"
    "    } finally {\n"
    "      await fallbackHandle.close()\n"
    "    }\n"
    "  }\n"
)


def patch_session_link_fallback() -> None:
    if not SESSION_TARGET.is_file():
        raise SystemExit(f"PATCH FAILED: {SESSION_TARGET} does not exist")
    text = SESSION_TARGET.read_text()

    text = replace_once(text, OLD_IS_EEXIST, NEW_IS_EEXIST, "isENOTSUP helper")
    text = replace_once(text, OLD_PUBLISH_LINK, NEW_PUBLISH_LINK, "publishCurrentExclusive ENOTSUP fallback")

    # Post-conditions.
    if "function isENOTSUP(error: unknown): boolean" not in text:
        raise SystemExit("PATCH FAILED: isENOTSUP helper not present after patch")
    if "internals.fs.open(currentPath, 'wx')" not in text:
        raise SystemExit("PATCH FAILED: ENOTSUP fallback not present after patch")

    SESSION_TARGET.write_text(text)
    print("patch applied: session publish falls back to exclusive-create on ENOTSUP")

    patch_materialize_enotsup()


# ---------------------------------------------------------------------------
# Patch 4: materializePosix ENOTSUP fallback (the actual first-append path).
#
# What it changes:
#   packages/session/session-persistence-jsonl/src/index.ts
#     + isENOTSUP() errno helper next to isENOENT()
#     + materializePosix(): when link() fails with ENOTSUP, publish via
#       publishCopyExclusive() (exclusive-create 'wx' + copy) instead of
#       failing the turn.
#     + publishCopyExclusive(): opens finalPath with 'wx' (EEXIST on race,
#       preserving the no-clobber guarantee), copies staged bytes, syncs.
#
# Why this shape: Patch 3 fixed generation.ts (migration publication), but
# the live ENOTSUP failure was in index.ts materializePosix — the
# first-append path every new session takes. The temp filename in the error
# (session.v3.jsonl.zstd.<hash>.tmp) matches writeSyncedTempFile, not the
# migration stager. This patch fixes the actual failing call site.
# ---------------------------------------------------------------------------

MATERIALIZE_TARGET = Path("/opt/dsh/packages/session/session-persistence-jsonl/src/index.ts")

OLD_IS_ENOENT = (
    "/** Whether a filesystem error means absence; every non-ENOENT failure must surface. */\n"
    "function isENOENT(error: unknown): boolean {\n"
    "  return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'\n"
    "}\n"
)
NEW_IS_ENOENT = (
    "/** Whether a filesystem error means absence; every non-ENOENT failure must surface. */\n"
    "function isENOENT(error: unknown): boolean {\n"
    "  return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'\n"
    "}\n"
    "\n"
    "/** Whether a filesystem error means the operation is unsupported (e.g. hard links on FUSE). */\n"
    "function isENOTSUP(error: unknown): boolean {\n"
    "  return (error as NodeJS.ErrnoException | null)?.code === 'ENOTSUP'\n"
    "}\n"
)

OLD_MATERIALIZE_LINK = (
    "    // Publish via link()+unlink(), NOT rename(): link fails with EEXIST if the\n"
    "    // final path already exists, so two processes materializing the same id\n"
    "    // concurrently cannot clobber each other. rename() would silently overwrite.\n"
    "    let linked = false\n"
    "    try {\n"
    "      await link(tmp, finalPath)\n"
    "      linked = true\n"
    "    } finally {\n"
    "      // Remove an unpublished temp on failure. After publication, defer cleanup\n"
    "      // until the directory entry is durable so cleanup cannot reject a live log.\n"
    "      /* v8 ignore next -- link failure is the TOCTOU/IO race guarded above; not reachable in test */\n"
    "      if (!linked) await rm(tmp, { force: true })\n"
    "    }\n"
)
NEW_MATERIALIZE_LINK = (
    "    // Publish via link()+unlink(), NOT rename(): link fails with EEXIST if the\n"
    "    // final path already exists, so two processes materializing the same id\n"
    "    // concurrently cannot clobber each other. rename() would silently overwrite.\n"
    "    let published = false\n"
    "    try {\n"
    "      try {\n"
    "        await link(tmp, finalPath)\n"
    "      } catch (error) {\n"
    "        // DEPLOYMENT OVERRIDE (manus-lite): filesystems without hard-link\n"
    "        // support raise ENOTSUP. Fall back to exclusive-create plus copy:\n"
    "        // open(finalPath, 'wx') fails with EEXIST when the target exists,\n"
    "        // preserving the no-clobber guarantee link() provides.\n"
    "        if (!isENOTSUP(error)) throw error\n"
    "        await this.publishCopyExclusive(tmp, finalPath)\n"
    "      }\n"
    "      published = true\n"
    "    } finally {\n"
    "      // Remove an unpublished temp on failure. After publication, defer cleanup\n"
    "      // until the directory entry is durable so cleanup cannot reject a live log.\n"
    "      /* v8 ignore next -- link failure is the TOCTOU/IO race guarded above; not reachable in test */\n"
    "      if (!published) await rm(tmp, { force: true })\n"
    "    }\n"
)

OLD_MATERIALIZE_WIN32_ANCHOR = (
    "  /* v8 ignore stop */\n"
    "\n"
    "  /* v8 ignore start -- native Windows coverage exercises this integration path */\n"
    "  private async materializeWin32(\n"
)
NEW_MATERIALIZE_WIN32_ANCHOR = (
    "  /* v8 ignore stop */\n"
    "\n"
    "  /**\n"
    "   * Publish staged bytes to finalPath on filesystems without hard-link support.\n"
    "   * Opens finalPath with exclusive create ('wx') so a concurrent\n"
    "   * materialization of the same id fails with EEXIST instead of clobbering —\n"
    "   * the same guarantee link() provides. A failure mid-copy removes the\n"
    "   * partial file; EEXIST propagates as the lost race.\n"
    "   */\n"
    "  private async publishCopyExclusive(tmp: string, finalPath: string): Promise<void> {\n"
    "    const handle = await open(finalPath, 'wx', 0o600)\n"
    "    try {\n"
    "      const staged = await open(tmp, 'r')\n"
    "      try {\n"
    "        await handle.writeFile(await staged.readFile())\n"
    "      } finally {\n"
    "        await staged.close()\n"
    "      }\n"
    "      await handle.sync()\n"
    "    } catch (error) {\n"
    "      try {\n"
    "        await handle.close()\n"
    "      } finally {\n"
    "        await rm(finalPath, { force: true })\n"
    "      }\n"
    "      throw error\n"
    "    }\n"
    "    await handle.close()\n"
    "  }\n"
    "\n"
    "  /* v8 ignore start -- native Windows coverage exercises this integration path */\n"
    "  private async materializeWin32(\n"
)


def patch_materialize_enotsup() -> None:
    if not MATERIALIZE_TARGET.is_file():
        raise SystemExit(f"PATCH FAILED: {MATERIALIZE_TARGET} does not exist")
    text = MATERIALIZE_TARGET.read_text()

    text = replace_once(text, OLD_IS_ENOENT, NEW_IS_ENOENT, "isENOTSUP helper in index.ts")
    text = replace_once(text, OLD_MATERIALIZE_LINK, NEW_MATERIALIZE_LINK, "materializePosix ENOTSUP fallback")
    text = replace_once(text, OLD_MATERIALIZE_WIN32_ANCHOR, NEW_MATERIALIZE_WIN32_ANCHOR, "publishCopyExclusive method")

    # Post-conditions.
    if "function isENOTSUP(error: unknown): boolean" not in text:
        raise SystemExit("PATCH FAILED: isENOTSUP helper not present in index.ts after patch")
    if "await this.publishCopyExclusive(tmp, finalPath)" not in text:
        raise SystemExit("PATCH FAILED: materializePosix ENOTSUP fallback not present after patch")
    if "private async publishCopyExclusive(tmp: string, finalPath: string)" not in text:
        raise SystemExit("PATCH FAILED: publishCopyExclusive method not present after patch")

    MATERIALIZE_TARGET.write_text(text)
    print("patch applied: materializePosix falls back to exclusive-create copy on ENOTSUP")


if __name__ == "__main__":
    main()