Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8001cbebd | ||
|
|
8ae1e1fafa | ||
|
|
a2700854a9 | ||
|
|
61ff536687 | ||
|
|
b7fa429b50 | ||
|
|
80fb6b6f4f | ||
|
|
c6ae15f829 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 dsh-disable-untrusted-origin contributors
|
||||
Copyright (c) 2026 dsh-trustworthy contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
# dsh-disable-untrusted-origin
|
||||
# dsh-trustworthy
|
||||
|
||||
Treat every browser window as if it were running on the DeepSeek Harness host itself.
|
||||
**Removes the untrusted-origin restriction from DeepSeek Harness, and the
|
||||
launch-token prompt with it.** Every browser window is treated as if it were
|
||||
running on the harness machine itself: no declared trusted host, no per-plugin
|
||||
origin fence, and no process token to paste into a phone — one interceptor
|
||||
answers every request with the loopback authority, and the session check is off
|
||||
by default.
|
||||
|
||||
A window that reaches the harness by a LAN address, a DNS name, or a tunnel
|
||||
authenticates normally and then fails every mutating request with
|
||||
`403 {"error":"untrusted origin"}`. Cards render, but Install, Update, toggle,
|
||||
and "Update all" do nothing that the user can see. This plugin removes the
|
||||
distinction between a local window and a remote one. No token, no
|
||||
`--trusted-host`, no per-plugin configuration.
|
||||
distinction between a local window and a remote one — with no declared trusted
|
||||
host, no `--trusted-host`, and no per-plugin configuration. The launch-token
|
||||
check is removed as well; `disableAuth: false` puts it back.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Read this before enabling it
|
||||
|
||||
**This plugin is a deliberate and total removal of the harness's request-identity
|
||||
fence. It is not a bug fix and it is not a workaround for one specific plugin.**
|
||||
fence, and by default of its browser-session check too. It is not a bug fix and
|
||||
it is not a workaround for one specific plugin.**
|
||||
|
||||
The harness fences requests by their `Host` and `Origin` headers for one
|
||||
reason: those are the only headers a page on another origin cannot forge, so
|
||||
@@ -25,25 +32,41 @@ while the harness is reachable. With this plugin enabled:
|
||||
- **A page on any other origin** can issue mutating requests to the API.
|
||||
- Those requests can **run commands on your machine** through the agent.
|
||||
|
||||
With `disableAuth: true` (the default) there is no session check either, so
|
||||
And with the default `disableAuth: true` there is no session check either:
|
||||
**anyone who can reach the port has full control of the agent, including code
|
||||
execution.** Reachability becomes the only access control.
|
||||
execution.** Reachability is the only access control.
|
||||
|
||||
That is a reasonable posture when the port is behind something that
|
||||
authenticates on your behalf, or when it is bound to a network you fully
|
||||
control. It is a poor posture for a `0.0.0.0` bind fronted by a public tunnel
|
||||
with no authentication of its own. Decide accordingly, and re-read this
|
||||
section if you change how the port is exposed.
|
||||
That posture is reasonable when the port is behind something that authenticates
|
||||
on your behalf, or when it is bound to a network you fully control. It is a poor
|
||||
posture for a `0.0.0.0` bind fronted by a public tunnel with no authentication of
|
||||
its own. Decide accordingly, and re-read this section if you change how the port
|
||||
is exposed. Set `disableAuth: false` to restore the launch token as a second
|
||||
line of defence.
|
||||
|
||||
### The launch token, and the `disableAuth` switch
|
||||
|
||||
The Web UI prints a one-time launch token in the process log —
|
||||
`dsh web: http://…/?token=…` — and from `0.2.1-alpha.4` the container entrypoint
|
||||
writes that line into the Docker log as well. The token rotates on every
|
||||
restart. With the check enabled, every new device or origin must open that URL
|
||||
once; the harness exchanges the token for a **30-day cookie** bound to the
|
||||
authority it was minted under, and until then every page answers `401`.
|
||||
|
||||
`0.4.0` made that check the default, on the argument that one exchange covers
|
||||
every domain because the plugin rewrites `Host` to the same loopback authority
|
||||
the cookie is bound to. In practice it still means producing a token on each new
|
||||
device, which is the friction this plugin exists to remove — `0.5.0` therefore
|
||||
restores `disableAuth: true` as the default. Set `disableAuth: false` to get the
|
||||
check, and the cookie, back.
|
||||
|
||||
If you want the errors gone but not the exposure, set `disableAuth: false`.
|
||||
That keeps the process token as the access control while still answering the
|
||||
identity fence, which is what actually produces the 403.
|
||||
|
||||
---
|
||||
|
||||
## What it changes
|
||||
|
||||
Four things, each one reachable only by a different kind of fence.
|
||||
Five things, each one reachable only by a different kind of fence. None of them
|
||||
touches the browser-session check; removing that is the separate `disableAuth`
|
||||
key described at the end of this section.
|
||||
|
||||
**1. Request identity, at the server.** The plugin installs `request` and
|
||||
`upgrade` listeners with `prependListener` on the raw `node:http` server the
|
||||
@@ -80,6 +103,14 @@ plus the metadata that makes the page installable on a phone. These are unrelate
|
||||
to request identity and are here so that one plugin covers the whole "I want to
|
||||
reach this from another machine" problem. See `shimClipboard` below.
|
||||
|
||||
**5. The `webRuntime` service, for plugins that never get to fence at all.** A
|
||||
plugin whose injection list names a service nobody provides is held `pending` by
|
||||
Cordis: its routes are never registered, and the URLs its pane calls answer `405`
|
||||
from the core static handler. Releases from `0.2.1-alpha.2` stopped providing
|
||||
`webRuntime`, which is how the sidebar's Files pane started failing to preview or
|
||||
download anything. The plugin provides it — when nothing else has — built from
|
||||
the trust data the harness still holds. See `provideWebRuntime` below.
|
||||
|
||||
It deliberately does **not** touch `sec-fetch-site`. The harness refuses
|
||||
`cross-site` outright, and that refusal is the last judgement a browser makes
|
||||
on its own behalf. Rewriting it would make a page on another origin look
|
||||
@@ -91,10 +122,10 @@ exactly like a window on this machine.
|
||||
|
||||
```bash
|
||||
# from a checkout or tarball on disk
|
||||
dsh plugin --profile web add file:/path/to/dsh-disable-untrusted-origin
|
||||
dsh plugin --profile web add file:/path/to/dsh-trustworthy
|
||||
|
||||
# or from a published package
|
||||
dsh plugin --profile web add dsh-disable-untrusted-origin
|
||||
dsh plugin --profile web add dsh-trustworthy
|
||||
```
|
||||
|
||||
Then restart the host so the new bundle is loaded.
|
||||
@@ -102,9 +133,35 @@ Then restart the host so the new bundle is loaded.
|
||||
The bundle patch inserts the row automatically. Verify it loaded:
|
||||
|
||||
```bash
|
||||
dsh plugin --profile web list | grep disable-untrusted-origin
|
||||
dsh plugin --profile web list | grep trustworthy
|
||||
```
|
||||
|
||||
### Installing so that the market can update it
|
||||
|
||||
The plugin market decides whether a git-sourced install has an update by
|
||||
resolving **the ref the installed spec names** — `checkUpdates()` in
|
||||
`dshmarket` calls `resolveGitRemoteHead(spec, gitRefOfTarget(spec))`. A spec
|
||||
pinned to a tag therefore reports "up to date" for ever, however many releases
|
||||
are published: the check resolves tag `v0.2.0` and compares it with the very
|
||||
commit it already installed. Publishing a new tag does not make a button
|
||||
appear.
|
||||
|
||||
To receive in-app updates, install from the branch:
|
||||
|
||||
```bash
|
||||
dsh plugin --profile web add 'git+https://gitea.milesward.dev/mward4/dsh-trustworthy.git#main'
|
||||
```
|
||||
|
||||
Releases are still tagged (`v0.2.1`, `v0.2.0`, …) so you can pin to one
|
||||
deliberately and move by hand; the branch ref is what makes the market's
|
||||
**Update** button work. Applying an update leaves the spec alone —
|
||||
`gitUpdateTarget()` strips a fragment only when it is a 40-hex commit pin — so
|
||||
it stays on the branch and keeps following it.
|
||||
|
||||
`dshmarket` caches its update verdicts in memory for 30 minutes; the market page
|
||||
forces a fresh check when it opens, and `GET /dsh-market/updates?force=1` does
|
||||
the same on demand.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
@@ -112,12 +169,13 @@ dsh plugin --profile web list | grep disable-untrusted-origin
|
||||
Override any key in your profile's `cordis.patch.yml`:
|
||||
|
||||
```yaml
|
||||
- id: disable-untrusted-origin
|
||||
- id: trustworthy
|
||||
config:
|
||||
enabled: true
|
||||
disableAuth: true
|
||||
forceClientLoopback: true
|
||||
grantPairing: true
|
||||
provideWebRuntime: true
|
||||
spoofSocketAddress: false
|
||||
shimClipboard: true
|
||||
shimRandomUuid: true
|
||||
@@ -127,14 +185,95 @@ Override any key in your profile's `cordis.patch.yml`:
|
||||
| Key | Default | Effect |
|
||||
|---|---|---|
|
||||
| `enabled` | `true` | Master switch. `false` loads the plugin and changes nothing. |
|
||||
| `disableAuth` | `true` | Also removes the browser-session check, so no process token is needed. **This is the one that removes access control.** |
|
||||
| `disableAuth` | `true` | **Also** removes the browser-session check, so no launch token and no per-device pairing are needed. This is the default: reachability is the only access control. Set `false` to keep the token — exchange it once and the 30-day cookie covers every rewritten request. |
|
||||
| `forceClientLoopback` | `true` | Grants the browser-side `isLoopback` flag so the settings and model surfaces act as they do on the host. |
|
||||
| `grantPairing` | `true` | Provides the paired-device service that plugins like the Skill Center accept instead of a loopback peer. See below. |
|
||||
| `provideWebRuntime` | `true` | Restores the `webRuntime` trust snapshot the harness stopped publishing in 0.2.1-alpha.2, so plugins that inject it (the sidebar) mount instead of answering 405. See below. |
|
||||
| `spoofSocketAddress` | `false` | Also reports the peer address as loopback, for plugins with no pairing path. See below. |
|
||||
| `shimClipboard` | `true` | Restores `navigator.clipboard.writeText` on plain HTTP. See below. |
|
||||
| `shimRandomUuid` | `true` | Restores `crypto.randomUUID` on plain HTTP. See below. |
|
||||
| `shimPwa` | `true` | Serves a manifest and adds the installable-app metadata. See below. |
|
||||
|
||||
### `disableAuth` — the two postures
|
||||
|
||||
Every key above only answers fences. `disableAuth` is the one that changes who
|
||||
may talk to the harness at all.
|
||||
|
||||
- **`true` (default).** The session check is replaced too: `connection.admit`
|
||||
returns the owner's own peer for every request, `authorizeIndex` admits the
|
||||
index, and `authenticatedUrl` stops appending the token to the printed URL. No
|
||||
token, no cookie, no login, nothing to type on a phone — and anyone who reaches
|
||||
the port controls the agent. Use it behind an authenticating proxy, on a
|
||||
network that is already trusted, or when the port is otherwise unreachable from
|
||||
untrusted networks.
|
||||
- **`false`.** The request-identity fence is still rewritten away, and the
|
||||
browser-session check is left exactly as the harness built it. A new browser
|
||||
shows `401` until the launch URL from the process log is opened once; that
|
||||
exchange sets the 30-day cookie, and every later request — including the ones
|
||||
this plugin rewrote the `Host` on — carries it. Each new device still has to be
|
||||
given the token, which is why it is not the default.
|
||||
|
||||
The implementation replaces `admit` because that is where every shape of the
|
||||
gate ends up: releases up to `0.2.1-alpha.2` call `requestRejection` from inside
|
||||
`admit` and wrap its answer, while `0.2.1-alpha.3` and later apply the fence and
|
||||
session check in `admit` itself. `requestRejection` is replaced as well so the
|
||||
older shape cannot short-circuit around the newer one, and every replacement is
|
||||
liveness-aware, so a host that switches the plugin off without running its
|
||||
disposers gets the real gate back.
|
||||
|
||||
### `provideWebRuntime` — the Files pane, and HTTP 405
|
||||
|
||||
`0.2.1-alpha.2` stopped providing a service named `webRuntime`. Its value was the
|
||||
LAN-trust snapshot — `resolveLanTrust(ctx.webServer.host, trustedHosts)`, that is
|
||||
`{ lanAddresses, trustedHosts }` — and third-party plugins inject it to learn
|
||||
which authorities their own copy of the request fence should accept:
|
||||
|
||||
```js
|
||||
export const inject = ['webServer', 'sessions', 'webRuntime', 'tools']
|
||||
const fence = (req) => isTrustedApiRequest(req, ctx.webRuntime.trustedHosts)
|
||||
```
|
||||
|
||||
Cordis holds a row whose injection is unsatisfied in `pending`: the module loads,
|
||||
its inject list is read, and **no `apply` runs** — so none of its routes are
|
||||
registered, and the boot log names it:
|
||||
|
||||
```
|
||||
dsh: warning: 1 entry did not activate
|
||||
better-sidebar (dsh-better-sidebar): pending (waiting for service: webRuntime)
|
||||
```
|
||||
|
||||
That 405 is the whole of the "opening a file stopped working" symptom: the routes
|
||||
are not refusing the request, they do not exist. The core static handler answers
|
||||
every unmounted `POST` with an empty `405`, while the plugin's own paths answer
|
||||
`404` — measured over a non-loopback `Host`, on one profile, with the sidebar's
|
||||
own Files requests:
|
||||
|
||||
| Request | `provideWebRuntime: false` | `provideWebRuntime: true` |
|
||||
|---|---|---|
|
||||
| `POST /sidebar/api/fs.tree` | `405`, 0 bytes | `200`, `{"ok":true,…,"entries":[…]}` |
|
||||
| `POST /sidebar/api/fs.read` | `405`, 0 bytes | `200`, `{"ok":true,"value":{"kind":"text",…}}` |
|
||||
| `GET /sidebar/file?sessionId=…&path=…` | `404` | `200 application/octet-stream` |
|
||||
| `GET /sidebar/file?…&download=1` | `404` | `200`, `content-disposition: attachment` |
|
||||
|
||||
The same release moved `--trusted-host` authorities into `connection.trustedHosts`
|
||||
(it is `trustedHosts: !!js ctx.webStartup.trustedHosts` in the web bundle's patch),
|
||||
which is what the `/api` fence reads. So the service can be rebuilt from what the
|
||||
harness still has, which is what this key does: it provides `webRuntime` — when
|
||||
nothing else has — with `trustedHosts` read **live** from `connection` rather than
|
||||
cloned at assembly time, plus the listener's own bind address, which the core
|
||||
fence accepts separately (`isBindAddressAuthority`) and a two-argument plugin fence
|
||||
otherwise cannot. `lanAddresses` is `[]`, which is what alpha.1 returned for every
|
||||
bind alpha.2 permits.
|
||||
|
||||
This does not weaken anything by itself. It is not a declaration of the arriving
|
||||
authority, and it is inert on the request path whenever the interceptor above is
|
||||
installed: every request already carries the loopback authority by the time any
|
||||
fence reads it. It exists so that a plugin **mounts** at all.
|
||||
|
||||
Set `provideWebRuntime: false` to leave those plugins unmounted — for instance on
|
||||
a harness that removed the service deliberately and where you would rather run
|
||||
plugins without it than republish an interface the harness retired.
|
||||
|
||||
### `grantPairing` — the Skill Center
|
||||
|
||||
Some plugins authorize a request either by a loopback peer or by a **live paired
|
||||
@@ -187,10 +326,20 @@ context**, and the browser withholds two APIs from it:
|
||||
The UUID is minted from `crypto.getRandomValues`, which is *not* restricted to
|
||||
secure contexts; the clipboard falls back to a hidden textarea and
|
||||
`document.execCommand('copy')`. `shimPwa` additionally serves a manifest at
|
||||
`/dsh-disable-untrusted-origin/manifest.webmanifest`, links it, and widens the
|
||||
`/dsh-trustworthy/manifest.webmanifest`, links it, and widens the
|
||||
viewport tag to `viewport-fit=cover` so Add to Home Screen produces a
|
||||
standalone app rather than a bookmark.
|
||||
|
||||
Note that the harness frontend **already ships a manifest** — a static
|
||||
`manifest.webmanifest` with `display: "fullscreen"`, linked relatively from its
|
||||
own `index.html` and served from the fallback seat. So a page with `shimPwa` on
|
||||
carries two `rel="manifest"` links. That is harmless but worth knowing: the
|
||||
browser takes the **first** link in document order, and index injections land at
|
||||
the top of `<head>`, so this plugin's manifest is the one that wins — reporting
|
||||
`display: "standalone"`, which keeps the status bar that `fullscreen` hides.
|
||||
Nothing is string-patched to achieve it; the added link simply precedes the
|
||||
shipped one.
|
||||
|
||||
The harness's own code no longer needs either shim — `@deepseek-ai/dsh-util-crypto`
|
||||
mints UUIDs from `getRandomValues`, and its lint rules point callers there — but
|
||||
third-party plugin bundles are not obliged to, and one that shipped recently
|
||||
@@ -201,19 +350,284 @@ three are `true` by default; serving over HTTPS makes the first two redundant.
|
||||
|
||||
## Compatibility
|
||||
|
||||
Verified against **DSH 0.1.7-rc.2**. The plugin depends on three things that
|
||||
are internal rather than public API, so a harness release that renames any of
|
||||
them will break it:
|
||||
Verified against **DSH 0.1.7-rc.2**, **0.2.0-rc.1**, **0.2.1-alpha.1**,
|
||||
**0.2.1-alpha.2**, **0.2.1-alpha.4**, **0.2.1-rc.1**, and **0.2.2-alpha.2**.
|
||||
From 0.4.0 the manifest also declares the range:
|
||||
|
||||
```json
|
||||
"engines": { "dsh": ">=0.1.7-rc.2 <0.3.0-0" }
|
||||
```
|
||||
|
||||
`0.2.1-alpha.4` made `engines.dsh` the compatibility declaration a plugin should
|
||||
provide — the harness uses it, when present, in place of guessing from
|
||||
`@deepseek-ai/dsh-*` peer ranges. This plugin has no dsh peers at all, so the
|
||||
declaration is the only statement of support it makes, and it is bounded above
|
||||
at the next minor release, excluding its prereleases, rather than left open.
|
||||
|
||||
`0.2.1-rc.2` is not listed separately because all four bundles the plugin hooks
|
||||
are byte-identical between rc.1 and rc.2. `0.2.2-alpha.2` *is* listed: it is the
|
||||
first release since 0.2.1-rc.1 that moves a hooked bundle, so it was re-checked live
|
||||
rather than inferred. Its `dsh-client-connection` and `dsh-web-app` are still
|
||||
byte-identical to `0.2.1-rc.2`; `dsh-host-webserver` and
|
||||
`dsh-host-frontend-static` changed in ways that leave the surfaces used here
|
||||
intact, and `dsh-session`'s stricter publication does not touch this plugin.
|
||||
|
||||
The plugin depends on several things that are internal rather than public API,
|
||||
so a harness release that renames any of them will break it:
|
||||
|
||||
| Depends on | Where |
|
||||
|---|---|
|
||||
| `webServer.server` — the raw `node:http` server | `@deepseek-ai/dsh-host-webserver` |
|
||||
| `webServer.host` — the listener's own bind address | `@deepseek-ai/dsh-host-webserver` |
|
||||
| `webServer.register` / `webServer.tapIndex` — the route registry and index transforms | `@deepseek-ai/dsh-host-webserver` |
|
||||
| `connection.trustedHosts` — the authorities the `/api` fence reads | `@deepseek-ai/dsh-client-connection` |
|
||||
| `connection.admit` — the fence and session check, alone from 0.2.1-alpha.3 | `@deepseek-ai/dsh-client-connection` |
|
||||
| `connection.requestRejection` / `authorizeIndex` / `authenticatedUrl` | `@deepseek-ai/dsh-client-connection` |
|
||||
| the `webserver/index-inject` channel and the `ownsHost` marker | webserver + connection client |
|
||||
|
||||
If `webServer.server` is ever absent the plugin throws at load with a clear
|
||||
message rather than failing quietly.
|
||||
The only one used conditionally is `connection.admit`: the bypass path replaces
|
||||
it when `disableAuth: true` (the default). With `disableAuth: false` the plugin
|
||||
does not touch it at all.
|
||||
|
||||
Every one of those is probed before use. If a release reshapes the surface, the
|
||||
plugin logs which capability it lost and carries on with the rest, rather than
|
||||
failing the fiber and taking the parts that still work down with it. Losing the
|
||||
raw server is the one that matters — it is reported as such:
|
||||
|
||||
```
|
||||
trustworthy: the webserver exposes no raw server, so the request-identity
|
||||
interceptor was not installed and a Host fence will still refuse a remote
|
||||
window; the harness surface may have changed
|
||||
```
|
||||
|
||||
### What was checked on 0.2.2-alpha.2
|
||||
|
||||
The first release since 0.2.1-rc.1 that moves a bundle this plugin hooks, so it was
|
||||
re-checked end to end instead of inferred from byte-identity.
|
||||
|
||||
**What moved.** `dsh-client-connection` and `dsh-web-app` are still
|
||||
byte-identical to `0.2.1-rc.2`, so the allow path — `admit`, `trustedHosts`,
|
||||
`requestRejection`, `authorizeIndex`, `authenticatedUrl` — is untouched. The two
|
||||
surfaces that did move are `dsh-host-webserver` and `dsh-host-frontend-static`.
|
||||
The webserver gained a second route kind (`{ resource }`: a Fetch-API
|
||||
`Request → Response` handler, plus a `readResource` variant) beside the plain
|
||||
`{ handler }` one; `server`, `register`, `tapIndex`, `host`, `port`, and
|
||||
`protocol` are unchanged, and the interceptor wraps the raw server's request
|
||||
emission before routing, so a route's kind does not matter to it. The frontend
|
||||
static bundle still authorizes the index through
|
||||
`connection.authorizeIndex(request, shim)` and still emits
|
||||
`webserver/index-inject`, so the browser grant, the shims, the viewport, and the
|
||||
PWA route inject exactly as before. `dsh-session` tightened store-owned
|
||||
publication (`cannot append outside a SessionStore`), which this plugin never
|
||||
does. The CLI's new optional bundles do not change a profile's explicit bundle
|
||||
list, so nothing new is inserted next to this one.
|
||||
|
||||
**Measured on a sandbox of the published `@deepseek-ai/[email protected]`** (the
|
||||
npm `alpha` tag; `latest` still points at `0.2.1-rc.2`), with a copy of a real
|
||||
profile, over a non-loopback peer:
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| interceptor answers `GET /` for a foreign `Host` | `200` index, no cookie |
|
||||
| WebSocket upgrade for a foreign `Host` | `101` |
|
||||
| `/api/*` over the non-loopback peer and over a named host | `200`, not the `400` trust fence |
|
||||
| browser grant, shims, viewport, and PWA markers in the served index | all present |
|
||||
| PWA manifest | `200 application/manifest+json` |
|
||||
| Files pane over a foreign `Host` — `fs.tree`, `fs.read`, `GET /sidebar/file` download | `200`, and the downloaded bytes are the file's |
|
||||
| `dsh plugin` load | no skip line, no missing-surface warning |
|
||||
|
||||
`node scripts/live-probe.mjs` passes **11/11** against that sandbox, including
|
||||
the sidebar Files API row. A control run with the bundle disabled answers `401`
|
||||
to `GET /` — the token gate stands — so a remote browser never gets as far as
|
||||
the pane; that is the difference the bypass makes. The installed sidebar bundle
|
||||
(0.28.0) no longer injects `webRuntime` at all, so on this harness its Files
|
||||
routes register whether or not the service is provided; `provideWebRuntime`
|
||||
stays for bundles that still inject it (0.26 and older), where the missing
|
||||
service is what left the pane answering `405`.
|
||||
|
||||
One harness deployment change to know about: since DSH 0.2.1-alpha.2, `dsh web --host` refuses
|
||||
a wildcard address (`0.0.0.0`, `::`) — *"is an unspecified (wildcard) address,
|
||||
which is not supported: binding every interface would expose remote code
|
||||
execution to the network; bind one concrete IPv4 or IPv6 address instead"* — so
|
||||
a container that bound wildcard must pass its concrete container IP. The bind
|
||||
address is still accepted as an authority by the trust snapshot, so
|
||||
`provideWebRuntime` and the no-`--trusted-host` posture keep working.
|
||||
|
||||
### What was checked on 0.2.1-rc.1
|
||||
|
||||
This is the release the 0.4.0 change answers. Two things moved.
|
||||
|
||||
**The gate moved into `admit`.** `requestRejection` is now a façade over
|
||||
`admit`, and the `/api` route and the WebSocket upgrade call `admit` directly.
|
||||
A plugin that only answered `requestRejection` — which is all 0.3.0 did when
|
||||
`disableAuth: true` — left the index reachable and every WebSocket refused with
|
||||
`401`, so the page loaded and then showed a disconnected shell. The bypass path
|
||||
now replaces `admit` itself and returns the owner's peer (`browserPeer` on this
|
||||
release, `operator` before alpha.3); measured on a sandboxed rc.1 with a
|
||||
non-loopback `Host`, the upgrade answered `101` with no cookie.
|
||||
|
||||
**The session check, when enabled, survives the rewrite.** The plugin rewrites
|
||||
`Host`/`Origin` to `127.0.0.1:<port>`, which is also the authority the harness
|
||||
mints the session cookie for. Measured on a sandbox, with `disableAuth: false`,
|
||||
in order:
|
||||
|
||||
| Request (`Host: ai.milesward.dev`) | Result |
|
||||
|---|---|
|
||||
| `GET /` with no cookie | `401` |
|
||||
| `GET /?token=<launch token>` | `303`, `location: ./`, `Set-Cookie: dsh-auth-…` |
|
||||
| `GET /` with that cookie | `200` index |
|
||||
| `Upgrade /api/remote.mux` with that cookie | `101` |
|
||||
|
||||
The cookie payload's `authority` is `127.0.0.1:<port>` — the rewritten one — so
|
||||
the browser keeps the cookie for the public origin it opened, and the plugin's
|
||||
rewrite presents the matching authority on every request afterwards. This is
|
||||
what lets the 30-day session survive a Host rewrite, and it is why
|
||||
`disableAuth: false` is a viable posture for anyone who would rather keep the
|
||||
check.
|
||||
|
||||
The token rotates whenever the process restarts (`dsh web: …?token=…` in the
|
||||
process log; the container entrypoint prints that line into the Docker log from
|
||||
0.2.1-alpha.4). The safety property the old bypass traded away is exactly this
|
||||
one: after `disableAuth: true` the printed URL has no token and every session is
|
||||
unauthenticated.
|
||||
|
||||
Also verified on this release: `webServer.server` / `register` / `tapIndex` and
|
||||
the `webserver/index-inject` channel are unchanged, so the interceptor, the
|
||||
browser grant, the shims, and the PWA route need no adjustment. The
|
||||
`dsh-client-connection`, `dsh-host-webserver`, `dsh-web-app`, and
|
||||
`dsh-host-frontend-static` bundles are byte-identical between 0.2.1-rc.1 and
|
||||
0.2.1-rc.2.
|
||||
|
||||
### What was checked on 0.2.1-alpha.2
|
||||
|
||||
Everything in the table above is still present and still of the shape this plugin
|
||||
reaches for — with one removal, which is what 0.3.0 answers.
|
||||
|
||||
* `webRuntime` is **gone**. `dsh-web-app` no longer provides it, no package
|
||||
provides it, and a plugin that injects it is held `pending` (the boot-log line
|
||||
quoted under `provideWebRuntime`).
|
||||
* `connection.trustedHosts` is not gone but **changed source**: the web bundle's
|
||||
patch now sets it from `webStartup.trustedHosts` (the `--trusted-host` values),
|
||||
and `isBindAddressAuthority` accepts `webServer.host` alongside it. It stays a
|
||||
plain `string[]` this plugin can read per request, which is what the snapshot is
|
||||
rebuilt from.
|
||||
* `webServer.host` is a **config value, not a socket fact**: it is the concrete
|
||||
IPv4/IPv6 literal passed to `--host`, and the setter now rejects a wildcard
|
||||
(`"0.0.0.0" is an unspecified (wildcard) address, which is not supported`).
|
||||
* `webServer.server` and `webServer.register` still exist, so the interceptor and
|
||||
the shims are unaffected. That the interceptor still works is visible in the
|
||||
table's right-hand column: every one of those requests arrived with a
|
||||
**non-loopback** `Host` (`172.17.0.4:3104`) and still reached the plugin's own
|
||||
fence, which only a rewritten request identity can do on an undeclared
|
||||
authority.
|
||||
|
||||
Not re-measured on alpha.2: the seven-point fence matrix from alpha.1 below, and
|
||||
the `--help`/peer-gate notes. The alpha.1 note is kept because it is still what
|
||||
the fence behaviour rests on, and because the `resolveLanTrust` details in it
|
||||
describe the value this plugin now rebuilds.
|
||||
|
||||
### What was checked on 0.2.1-alpha.1
|
||||
|
||||
The three packages this plugin reaches into are **byte-identical** between
|
||||
0.2.0-rc.1 and 0.2.1-alpha.1 — `dsh-host-webserver/lib/index.js`
|
||||
(`48605e6f4fc88362c07569686df1417b`), `dsh-client-connection/lib/index.js`
|
||||
(`39d2d6d64f3ffb91ec623932a15a068b`), and `dsh-settings/lib/index.js`
|
||||
(`5024d014ad19237fb91fbf8bb4370903`) — so nothing in the table above has moved,
|
||||
`ownsHost` is still read by the client bundle, and the `webserver/index-inject`
|
||||
channel is still emitted and still typed.
|
||||
|
||||
The release does add `--public-url`, and it is worth being explicit about what
|
||||
it is not: it advertises an HTTP root in the printed URL, the system prompt, and
|
||||
`DSH_WEB_URL`, and it **grants no trust** — the CLI's own help says so. The trust
|
||||
surface is a separate function, `resolveLanTrust()`, and `publicUrl` never
|
||||
reaches it. `--public-url` does not replace this plugin.
|
||||
|
||||
Measured on 0.2.1-alpha.1 over a non-loopback peer, plugin enabled vs.
|
||||
`enabled: false`, same harness and same profile: **7/7 with it on, 1/7 with it
|
||||
off**. Switched off, the shell answers 401, the Skill Center answers 400 (the
|
||||
fence's own throw), the shims are absent, and the ready URL carries a process
|
||||
token again. That difference is the whole of what this plugin carries.
|
||||
|
||||
An in-place upgrade of a real 0.2.0-rc.1 profile to 0.2.1-alpha.1 boots and
|
||||
serves with this plugin installed and no version exemption recorded. Two other
|
||||
plugins are refused by the harness's peer-range gate on that release —
|
||||
`@memtensor/memos-local-plugin` and `@michengai/dsh-btw`, both because of an
|
||||
absolute `<0.2.0` / `… || 0.2.0-rc.2` upper bound in their `@deepseek-ai/dsh-*`
|
||||
peers. This plugin declares **no `@deepseek-ai/dsh-*` peers at all**
|
||||
(`peerDependencies` is `@deepseek-ai/schemastery` only), so the gate has nothing
|
||||
to reject it on and it skips nothing at boot.
|
||||
|
||||
### Why it never writes the trusted-host lists
|
||||
|
||||
The obvious fix for this problem is to add the arriving host to
|
||||
`connection.trustedHosts`. This plugin deliberately does not — and that is a
|
||||
narrower statement than it looks, now that `provideWebRuntime` exists: it
|
||||
*publishes* a `webRuntime` value built from that list, and writes nothing into
|
||||
`connection.trustedHosts` itself.
|
||||
|
||||
The reason is the same one that has always applied. A fence that compares against
|
||||
a **literal loopback value** rather than against a list is not moved by any
|
||||
declaration at all; plugin markets published before the list existed hardcode
|
||||
exactly that check, and they are the ones producing the 403 users actually see.
|
||||
Rewriting the request identity satisfies every fence, of every shape and every
|
||||
age; a list entry satisfies only the fences that read the list. The same argument
|
||||
applies to the restored snapshot: its list is a faithful reproduction of what the
|
||||
harness already believes, not an attempt to talk a fence into accepting something
|
||||
the harness would refuse.
|
||||
|
||||
On **0.2.1-alpha.1** there was a second, version-specific reason: the harness
|
||||
assembled two trusted-host arrays — one on `webRuntime`, one on `connection` —
|
||||
as separate objects cloned at assembly time, so a host declared into one was
|
||||
invisible to the other and half the fix silently did nothing. `0.2.1-alpha.2`
|
||||
removed the `webRuntime` array along with the service, leaving `connection` as
|
||||
the single source, which is what the snapshot reads.
|
||||
|
||||
### Reload safety
|
||||
|
||||
The plugin mutates objects the harness owns, and a reload gives those mutations
|
||||
two authors. The harness does not promise an ordering between them — in practice
|
||||
the **successor applies before the predecessor's cleanup runs** — and it does not
|
||||
always run disposers at all when a plugin is switched off by editing its patch
|
||||
row.
|
||||
|
||||
Three guards follow from that, and each has a test:
|
||||
|
||||
- Replacements are recorded through a **handover carrier** keyed on the target
|
||||
itself, with the installing generation stamped as its owner. A cleanup whose
|
||||
owner is no longer current returns without touching anything, so a
|
||||
predecessor cannot restore the fence underneath a live successor. The carrier
|
||||
key is `Symbol.for('dsh-trustworthy.handover')` — a registry symbol, not a
|
||||
module-local one, so a reload that re-imports this file still shares it.
|
||||
- The service methods answer through a **liveness check on the plugin's own
|
||||
fiber**. If the fiber is gone the replacement stops admitting and delegates to
|
||||
the true original instead, read from the carrier rather than captured at
|
||||
install time. A plugin switched off without its disposers therefore closes
|
||||
rather than leaving the gateway open — the failure mode is a working fence, not
|
||||
a silent hole.
|
||||
- The interceptor is tagged `Symbol.for('dsh-trustworthy.interceptor')`, and a new
|
||||
one **retires any predecessor bearing the tag** before prepending itself. Two
|
||||
live interceptors would both run, and the older one is a closure over a dead
|
||||
generation's configuration — it would keep spoofing the peer address after
|
||||
`spoofSocketAddress` was turned off.
|
||||
|
||||
### Known limits
|
||||
|
||||
- `sec-fetch-site: cross-site` is refused **unconditionally** by
|
||||
`isTrustedApiRequest`, before the `Origin` check and regardless of the
|
||||
trusted-host list. No header rewrite can defeat it, and this plugin does not
|
||||
try. It only guards requests a browser itself marks as cross-site, so it has
|
||||
no effect on normal navigation or on the WebSocket. With `disableAuth: true`
|
||||
(the default) the gate that calls it is replaced, so it does not run either.
|
||||
- Rewriting `Host` decides the **cookie authority** the harness derives from it
|
||||
(`dsh-auth-<sha256(authority)>`). With `disableAuth: false` the launch token is
|
||||
exchanged for the rewritten authority, so the resulting 30-day cookie matches
|
||||
every request the plugin intercepts. The authority is the loopback bind
|
||||
(`127.0.0.1:<port>`), so changing `--port` mints a new one and requires one new
|
||||
exchange. A session cookie you already
|
||||
hold under the public hostname is not reused; expect one re-login on enabling
|
||||
the plugin.
|
||||
- `Referer` is read by no layer of the harness, core or plugin. It is rewritten
|
||||
only for third-party code that might read it.
|
||||
|
||||
### Relationship to `@goodandready/dsh-lanmode`
|
||||
|
||||
@@ -240,6 +654,33 @@ So the two overlap almost entirely. Running both is redundant, and
|
||||
`spoofSocketAddress` in particular will confuse lanmode's device tracking — but
|
||||
neither will break the other if you do.
|
||||
|
||||
`shimClipboard`, `shimRandomUuid`, and `shimPwa` exist so that lanmode is not
|
||||
needed for the browser side either; with them on, the only things it still owns
|
||||
are its mobile navigation UI, its QR tool, and its device registry.
|
||||
|
||||
### Relationship to `@mzzsfy/dsh-auto-trust-all`
|
||||
|
||||
The other published approach to this problem, and a good one — it solves it by
|
||||
**declaring** the arriving host, wrapping the webserver's route-registration
|
||||
methods and adding each `Host` it sees to both trusted-host lists, under an LRU
|
||||
cap.
|
||||
|
||||
The difference is reach. A declaration only helps a fence that consults the
|
||||
list, and the fences users actually hit do not: they compare against a literal
|
||||
loopback value, in versions published before the list existed. Declaring the
|
||||
host leaves those untouched; rewriting the request identity satisfies them. This
|
||||
plugin also has nothing to cap, because it declares nothing.
|
||||
|
||||
The reload guards here — a generation-owned carrier, identity-checked teardown,
|
||||
per-request liveness, and a tagged interceptor that retires its predecessor —
|
||||
come from the same problem being solved there. That project's convention is also
|
||||
worth stating, because it predicts what is coming: its own review standard
|
||||
declares *any* audit finding of "missing Host validation / DNS-rebinding defence
|
||||
/ token validation" **invalid** in its packages. Third-party loopback-only
|
||||
fences are therefore a deliberate ecosystem position, not an oversight, and more
|
||||
of them will appear. `sec-fetch-site` and the cookie authority above are the two
|
||||
limits inherited from the harness side.
|
||||
|
||||
### What it does not fix
|
||||
|
||||
- Anything gating on TLS state, or on a proxy's own authentication.
|
||||
@@ -256,25 +697,53 @@ neither will break the other if you do.
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
node test/fence.test.mjs # drives real requests past the real plugin-market fence
|
||||
node test/apply.test.mjs # wiring, including that unload restores every original
|
||||
node test/shims.test.mjs # executes the generated shim in a context without the APIs
|
||||
node test/fence.test.mjs # drives real requests past the real plugin-market fence
|
||||
node test/apply.test.mjs # wiring, including that unload restores every original
|
||||
node test/handover.test.mjs # the reload orderings: predecessor vs. successor, liveness
|
||||
node test/shims.test.mjs # executes the generated shim in a context without the APIs
|
||||
node test/web-runtime.test.mjs # the restored webRuntime value, and when it is provided
|
||||
node scripts/live-probe.mjs # against the running harness, over a non-loopback peer
|
||||
```
|
||||
|
||||
All five suites together — **61 tests** (fence 8, apply 22, handover 15,
|
||||
shims 9, web-runtime 7) — are `node --test test/*.test.mjs` from the plugin
|
||||
directory. The shell has to expand that glob: `node --test test/` fails with `MODULE_NOT_FOUND`
|
||||
on Node 22.
|
||||
|
||||
The manifest pins what it supports: `engines.dsh` is
|
||||
`>=0.1.7-rc.2 <0.3.0-0`, so a harness from a future minor release skips this
|
||||
plugin instead of loading it against a surface it was never checked on. Bump the
|
||||
range only after re-running the probe matrix above.
|
||||
|
||||
`test/fence.test.mjs` loads `sameOrigin()` from the installed `dshmarket` when a
|
||||
profile is present and says which source it used, so a run against a bundled
|
||||
copy is never mistaken for a run against the real thing. `test/shims.test.mjs`
|
||||
evaluates the shim source in a `node:vm` context that lacks `crypto.randomUUID`
|
||||
and `navigator.clipboard`, so it checks the delivered code rather than the string
|
||||
that delivers it. The suites need no dependency tree beyond a resolvable
|
||||
`@deepseek-ai/schemastery` for the second.
|
||||
that delivers it. `test/handover.test.mjs` exercises the orderings directly,
|
||||
including the one the harness does not promise — a predecessor's cleanup running
|
||||
*after* its successor installed. The suites need no dependency tree beyond a
|
||||
resolvable `@deepseek-ai/schemastery` for the second.
|
||||
|
||||
`scripts/live-probe.mjs` is the one that matters after a change: it connects to a
|
||||
**non-loopback** local address, because the Skill Center fences on the socket
|
||||
address as well as the `Host`, so a probe over `127.0.0.1` can never reproduce a
|
||||
remote client and always looks like it passes.
|
||||
|
||||
## Releases
|
||||
|
||||
| Version | What changed |
|
||||
|---|---|
|
||||
| **0.5.1** | Documentation and compatibility only — **no code change from 0.5.0**. Records the 0.2.2-alpha.2 review: the allow path's bundles are byte-identical, the webserver's new route kind does not touch the interceptor, and `scripts/live-probe.mjs` passes 11/11 against a sandbox of the published release (Files pane, PWA, shell, Skill Center, shims). Also notes the new `--host` wildcard refusal. |
|
||||
| **0.5.0** | Restores `disableAuth: true` as the default: no launch token and no per-device pairing, which is what the plugin exists to remove. `0.4.0`'s keep-the-check posture remains available with `disableAuth: false`. No code change beyond the default and the documentation; validated on DSH `0.2.1-rc.2`, where the bypass still replaces `connection.admit`. |
|
||||
| **0.4.0** | Keeps the browser-session check by default (`disableAuth: false`) and makes the 0.2.1-alpha.3 launch-token → 30-day-cookie flow survive the Host rewrite, including on a remote origin; the no-check posture moves to `disableAuth: true` and now replaces `connection.admit` as well, because the gate moved there. Declares `engines.dsh` (the 0.2.1-alpha.4 recommendation) and is validated on 0.2.1-alpha.4 and 0.2.1-rc.1. |
|
||||
| **0.3.0** | Provides the `webRuntime` trust snapshot that `0.2.1-alpha.2` stopped publishing (`lib/web-runtime.js`, `provideWebRuntime`), so a plugin that injects it — the sidebar among them — mounts instead of answering 405 on every request. The value is read live from `connection.trustedHosts` plus the listener's bind address, and an existing provider is left alone. |
|
||||
| 0.2.1 | Documentation and compatibility only — **no code change from 0.2.0**. Records the 0.2.1-alpha.1 validation above, and how to install so the market can update it. |
|
||||
| 0.2.0 | Renamed from `dsh-disable-untrusted-origin`. Added `lib/handover.js`: originals recorded once on a `Symbol.for` carrier, a liveness check (`fiber.uid === null`) on every delegated path, and an interceptor that retires a tagged predecessor. Capabilities now degrade with a warning instead of failing the fiber. |
|
||||
| 0.1.2 | Restored `crypto.randomUUID` and `navigator.clipboard` on plain HTTP, added the PWA manifest, and widened the viewport for notched screens. |
|
||||
| 0.1.1 | Provided the paired-device service, so the Skill Center works over a remote address instead of answering 400. |
|
||||
| 0.1.0 | First release: one interceptor on the raw server, rewriting request identity to the loopback authority. |
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
+12
-8
@@ -1,16 +1,20 @@
|
||||
# dsh-disable-untrusted-origin — bundle layer
|
||||
# dsh-trustworthy — bundle layer
|
||||
#
|
||||
# Applied automatically when the package is installed as a profile bundle
|
||||
# (package.json declares dsh.bundle.patch).
|
||||
#
|
||||
# The defaults below are the plugin's stated posture: the identity fence is
|
||||
# disarmed, the browser-session check is removed, the browser is granted the
|
||||
# host's own isLoopback flag, and the APIs a non-secure page is denied are
|
||||
# restored. Override any key in your profile patch:
|
||||
# disarmed, no process token or per-device pairing is required, the browser is
|
||||
# granted the host's own isLoopback flag, and the APIs a non-secure page is
|
||||
# denied are restored. Reachability is therefore the only access control — put
|
||||
# the port behind something that authenticates on your behalf if it is exposed.
|
||||
# To keep the harness's own browser-session check instead (the first visit is
|
||||
# then the one-time launch token from the process log, exchanged for a 30-day
|
||||
# cookie), set `disableAuth: false`. Override any key in your profile patch:
|
||||
#
|
||||
# - id: disable-untrusted-origin
|
||||
# - id: trustworthy
|
||||
# config:
|
||||
# disableAuth: false # keep the process token, disarm only the fence
|
||||
# disableAuth: false # keep the launch-token check; one token per device
|
||||
# grantPairing: false # when dsh-remote-web-ui provides the pairing service itself
|
||||
# spoofSocketAddress: true # also satisfy socket-based fences with no pairing path
|
||||
# shimClipboard: false # unnecessary when you reach the harness over HTTPS
|
||||
@@ -19,8 +23,8 @@
|
||||
#
|
||||
# Set `enabled: false` to suspend the plugin without removing the bundle.
|
||||
- insert:
|
||||
- id: disable-untrusted-origin
|
||||
name: 'dsh-disable-untrusted-origin'
|
||||
- id: trustworthy
|
||||
name: 'dsh-trustworthy'
|
||||
config:
|
||||
enabled: true
|
||||
disableAuth: true
|
||||
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* Handover between generations of the same plugin.
|
||||
*
|
||||
* Everything this plugin installs is a mutation of an object somebody else
|
||||
* owns: methods on the `connection` service, and listeners on the raw HTTP
|
||||
* server. A reload — the plugin market switching it off and on, a line-level
|
||||
* config change, a bundle patch reloaded — runs `apply` again and, sooner or
|
||||
* later, the previous generation's cleanup. Those two events have no
|
||||
* guaranteed order, and the unordered case is destructive:
|
||||
*
|
||||
* generation 1 captures the true originals, installs A
|
||||
* generation 2 captures A as its "originals", installs B
|
||||
* generation 1 cleans up, restoring the true originals
|
||||
*
|
||||
* Generation 2 is now silently inert while believing it is installed, because
|
||||
* the value it displaced was itself a replacement. The fix is to record the
|
||||
* originals once, on the shared object, together with the identity of the
|
||||
* generation that currently owns them; a cleanup runs only while it still owns
|
||||
* the installation. That is what {@link installReplacements} does, and the
|
||||
* interceptor needs the mirror of it — a listener that survives its author
|
||||
* must not be joined by its successor.
|
||||
*
|
||||
* Deliberately free of imports, like `authority.js` and `shims.js`, so the
|
||||
* tests can load it with no resolvable dependency tree.
|
||||
*
|
||||
* The sharing channels are `Symbol.for` keys, not module-local state: a reload
|
||||
* can arrive as a fresh module instance with a fresh set of module bindings, and
|
||||
* only the global symbol registry is common to both.
|
||||
*/
|
||||
|
||||
/** Carrier for the recorded originals and the owning generation. */
|
||||
export const HANDOVER = Symbol.for('dsh-trustworthy.handover')
|
||||
|
||||
/** Marks a listener as this plugin's request interceptor. */
|
||||
export const INTERCEPTOR = Symbol.for('dsh-trustworthy.interceptor')
|
||||
|
||||
/** Fallback carrier for a target that refuses a symbol property. */
|
||||
const carriers = new WeakMap()
|
||||
|
||||
/**
|
||||
* Read the carrier on a shared object.
|
||||
*
|
||||
* @param target - the object the installation lives on.
|
||||
* @param create - whether to make one when it is absent.
|
||||
* @returns the carrier, or `undefined` when absent and not creating.
|
||||
*/
|
||||
function carrierFor(target, create) {
|
||||
const existing = target[HANDOVER]
|
||||
if (existing !== undefined) return existing
|
||||
const mapped = carriers.get(target)
|
||||
if (mapped !== undefined) return mapped
|
||||
if (!create) return undefined
|
||||
const carrier = { originals: new Map(), owner: null }
|
||||
try {
|
||||
Object.defineProperty(target, HANDOVER, {
|
||||
value: carrier,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
enumerable: false,
|
||||
})
|
||||
} catch {
|
||||
// A frozen or exotic host object still gets coordination, just only within
|
||||
// this module instance rather than across a fresh one.
|
||||
carriers.set(target, carrier)
|
||||
}
|
||||
return carrier
|
||||
}
|
||||
|
||||
/**
|
||||
* Install replacement properties, with a handover between generations.
|
||||
*
|
||||
* The originals are captured exactly once and kept on the target, so a
|
||||
* successor inherits them rather than treating its predecessor's replacements
|
||||
* as the state to return to. A cleanup restores only while its own generation
|
||||
* still owns the installation, and only for keys still holding its own value —
|
||||
* so a third party that replaced one of them in the meantime keeps it.
|
||||
*
|
||||
* @param target - the object whose properties are replaced.
|
||||
* @param replacements - a map of property name to replacement value.
|
||||
* @returns a cleanup function, safe to call more than once.
|
||||
*/
|
||||
export function installReplacements(target, replacements) {
|
||||
const carrier = carrierFor(target, true)
|
||||
const keys = Object.keys(replacements)
|
||||
|
||||
// Recorded before the first overwrite, and never again: from the second
|
||||
// generation on, the live values are this plugin's own replacements.
|
||||
for (const key of keys) {
|
||||
if (!carrier.originals.has(key)) carrier.originals.set(key, target[key])
|
||||
}
|
||||
|
||||
const token = {}
|
||||
carrier.owner = token
|
||||
for (const key of keys) target[key] = replacements[key]
|
||||
|
||||
let restored = false
|
||||
return () => {
|
||||
if (restored) return
|
||||
restored = true
|
||||
// A newer generation has taken the installation over; its values are the
|
||||
// live ones and this cleanup must not touch them.
|
||||
if (carrier.owner !== token) return
|
||||
for (const key of keys) {
|
||||
if (target[key] !== replacements[key]) continue
|
||||
const original = carrier.originals.get(key)
|
||||
if (original === undefined) delete target[key]
|
||||
else target[key] = original
|
||||
}
|
||||
carrier.owner = null
|
||||
if (target[HANDOVER] === carrier) {
|
||||
try {
|
||||
delete target[HANDOVER]
|
||||
} catch {
|
||||
/* Non-configurable on an exotic host; the carrier is inert anyway. */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The value a key held before this plugin first replaced it.
|
||||
*
|
||||
* Read from the carrier rather than captured in the caller, so a replacement
|
||||
* can delegate to the true original even when it was installed by a later
|
||||
* generation — and can do so lazily, at call time, when the carrier is known to
|
||||
* exist.
|
||||
*
|
||||
* @param target - the object the installation lives on.
|
||||
* @param key - the property name.
|
||||
* @returns the original value, or `undefined` when there is no carrier or the
|
||||
* property did not exist before this plugin was installed.
|
||||
*/
|
||||
export function originalOf(target, key) {
|
||||
return carrierFor(target, false)?.originals.get(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the request-identity interceptor ahead of every other listener.
|
||||
*
|
||||
* `prependListener`, not `on`: the webserver registers its own request handler
|
||||
* when it constructs the server, so appending would run this after every route
|
||||
* lookup and change nothing.
|
||||
*
|
||||
* Any predecessor bearing {@link INTERCEPTOR} is removed first. A reload can
|
||||
* add the successor before the predecessor's cleanup runs, and two identical
|
||||
* interceptors are not merely wasteful — the older one is a live closure over a
|
||||
* dead generation's config, which would keep spoofing the peer address after
|
||||
* `spoofSocketAddress` was turned off.
|
||||
*
|
||||
* @param server - the raw `node:http` server.
|
||||
* @param listener - the interceptor, called with the request or the socket.
|
||||
* @param events - the server events to cover, `request` and `upgrade`.
|
||||
* @returns a cleanup function, safe to call more than once.
|
||||
*/
|
||||
export function installInterceptor(server, listener, events = ['request', 'upgrade']) {
|
||||
listener[INTERCEPTOR] = true
|
||||
for (const event of events) {
|
||||
for (const existing of server.listeners(event)) {
|
||||
if (existing[INTERCEPTOR] === true) server.removeListener(event, existing)
|
||||
}
|
||||
server.prependListener(event, listener)
|
||||
}
|
||||
let removed = false
|
||||
return () => {
|
||||
if (removed) return
|
||||
removed = true
|
||||
for (const event of events) server.removeListener(event, listener)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a fiber is still the live installation.
|
||||
*
|
||||
* Cordis nulls a fiber's `uid` at the very start of disposal — before its
|
||||
* disposers run, and before the state machine moves to `UNLOADING` — so a
|
||||
* closure left behind by a generation whose cleanup never ran can recognise
|
||||
* that it no longer owns the process. The alternative signal, `fiber.state`, is
|
||||
* a numeric enum whose members are not part of the plugin-facing API; `uid` is
|
||||
* documented as "`null` once disposed".
|
||||
*
|
||||
* Conservative by construction: only a positive signal of disposal answers
|
||||
* false. A host that has reshaped the fiber, or a mock without one, keeps the
|
||||
* installation working rather than silently disarming it.
|
||||
*
|
||||
* @param fiber - the plugin fiber, usually `ctx.fiber`.
|
||||
* @returns false only when the fiber is known to have been disposed.
|
||||
*/
|
||||
export function fiberLive(fiber) {
|
||||
if (fiber === undefined || fiber === null) return true
|
||||
return fiber.uid !== null
|
||||
}
|
||||
+219
-83
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* dsh-disable-untrusted-origin — make every browser window behave like a
|
||||
* dsh-trustworthy — make every browser window behave like a
|
||||
* window running on the harness machine itself.
|
||||
*
|
||||
* DeepSeek Harness fences its HTTP surface by request identity. The `/api`
|
||||
@@ -11,7 +11,13 @@
|
||||
* request with `403`, which reads to the user as a button that does nothing.
|
||||
*
|
||||
* This plugin removes the distinction in two places, and separately restores
|
||||
* the browser capabilities a non-secure page is denied.
|
||||
* the browser capabilities a non-secure page is denied. It removes the origin
|
||||
* fence and the harness's own browser-session check by default, so a window is
|
||||
* admitted with no process token and no per-device pairing. Set
|
||||
* `disableAuth: false` to keep the session check, in which case the first visit
|
||||
* is the one-time launch token from the process log (`dsh web: …?token=…`; the
|
||||
* container entrypoint prints it into the Docker log from `0.2.1-alpha.4`),
|
||||
* exchanged for a 30-day cookie bound to the authority it was minted under.
|
||||
*
|
||||
* 1. A `request`/`upgrade` listener installed ahead of every route answers
|
||||
* each connection with the loopback authority. One interception covers the
|
||||
@@ -25,14 +31,38 @@
|
||||
* `navigator.clipboard`, both of which exist only in a secure context, plus
|
||||
* the metadata that makes the page installable on a phone.
|
||||
*
|
||||
* Security: this is a deliberate and total removal of the request-identity
|
||||
* fence across the whole HTTP surface. It defends against DNS rebinding and
|
||||
* against another page in the same browser driving this API, and both
|
||||
* defences stop applying once this plugin is enabled. Read the README before
|
||||
* turning it on, and keep the listening port behind something that
|
||||
* authenticates on your behalf.
|
||||
* What it deliberately does not do is *declare* the arriving authority. The
|
||||
* `connection` service's `trustedHosts` is what the `/api` fence reads, and an
|
||||
* entry there changes which names the gate accepts — a weaker and narrower
|
||||
* guarantee than rewriting the request, and one no declaration can give a fence
|
||||
* that compares against a hardcoded loopback literal. Rewriting needs no
|
||||
* declaration at all.
|
||||
*
|
||||
* @module dsh-disable-untrusted-origin
|
||||
* It does, separately, **restore** the `webRuntime` service that releases from
|
||||
* `0.2.1-alpha.2` on stopped providing, when nothing else provides it. That
|
||||
* service was the LAN-trust snapshot a third-party plugin injects to learn the
|
||||
* authorities its own copy of the fence should accept; without it the row stays
|
||||
* `pending`, its routes never mount, and its URLs fall through to the core
|
||||
* handler — which is what a `405` in a plugin's own pane actually is. See
|
||||
* `lib/web-runtime.js` and `provideWebRuntime`.
|
||||
*
|
||||
* Reload safety: everything installed here is a mutation of an object the
|
||||
* harness owns, and a reload can run a successor's installation before its
|
||||
* predecessor's cleanup. `handover.js` records the originals once, on the
|
||||
* shared object, and restores them only while the generation that wrote them
|
||||
* still owns the installation — so a reload cannot leave the plugin inert while
|
||||
* it believes it is mounted, nor let a superseded interceptor keep acting.
|
||||
*
|
||||
* Security: removing the request-identity fence is deliberate and total for
|
||||
* every window that reaches the port. It defends against DNS rebinding and
|
||||
* against another page in the same browser driving this API, and both defences
|
||||
* stop applying once this plugin is enabled. The default also removes the
|
||||
* session check, so reachability is the only access control — a `0.0.0.0` bind
|
||||
* fronted by a public tunnel with no authentication of its own is wide open.
|
||||
* Set `disableAuth: false` to keep the launch-token check. Read the README
|
||||
* before deploying either posture.
|
||||
*
|
||||
* @module dsh-trustworthy
|
||||
*/
|
||||
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
@@ -42,6 +72,14 @@ import {
|
||||
loopbackise,
|
||||
spoofPeerAddress,
|
||||
} from './authority.js'
|
||||
import {
|
||||
HANDOVER,
|
||||
INTERCEPTOR,
|
||||
fiberLive,
|
||||
installInterceptor,
|
||||
installReplacements,
|
||||
originalOf,
|
||||
} from './handover.js'
|
||||
import {
|
||||
MANIFEST_PATH,
|
||||
manifest,
|
||||
@@ -49,12 +87,27 @@ import {
|
||||
shimSource,
|
||||
withCoverViewport,
|
||||
} from './shims.js'
|
||||
import {
|
||||
WEB_RUNTIME_SERVICE,
|
||||
bindAuthority,
|
||||
connectionAuthorities,
|
||||
trustedAuthorities,
|
||||
webRuntimeShim,
|
||||
} from './web-runtime.js'
|
||||
|
||||
export { CLIENT_LOOPBACK_GRANT, loopbackAuthority, loopbackise, spoofPeerAddress }
|
||||
export { HANDOVER, INTERCEPTOR, fiberLive, installInterceptor, installReplacements, originalOf }
|
||||
export { MANIFEST_PATH, manifest, pwaMarkup, shimSource, withCoverViewport }
|
||||
export {
|
||||
WEB_RUNTIME_SERVICE,
|
||||
bindAuthority,
|
||||
connectionAuthorities,
|
||||
trustedAuthorities,
|
||||
webRuntimeShim,
|
||||
}
|
||||
|
||||
/** Stable Cordis plugin name. */
|
||||
export const name = 'disable-untrusted-origin'
|
||||
export const name = 'trustworthy'
|
||||
|
||||
/** The webserver owns the routes; the connection service owns the fence. */
|
||||
export const inject = ['webServer', 'connection']
|
||||
@@ -78,10 +131,15 @@ export const Config = z.object({
|
||||
.boolean()
|
||||
.default(true)
|
||||
.description(
|
||||
'Also remove the browser-session check, so no process token is needed. '
|
||||
+ 'Anyone who can reach the port then has full control of the agent, '
|
||||
+ 'including code execution. Keep this true only behind a port or '
|
||||
+ 'tunnel that authenticates on its own.',
|
||||
'Remove the browser-session check as well, so no process token is ever '
|
||||
+ 'needed and no device has to be paired. Anyone who can reach the port '
|
||||
+ 'then has full control of the agent, including code execution: '
|
||||
+ 'reachability is the only access control. This is the default because '
|
||||
+ 'the plugin exists to make every window behave like the host window, '
|
||||
+ 'and a token paste on each new device defeats that. Set it false to '
|
||||
+ 'keep the harness\'s launch-token check: open the URL from the process '
|
||||
+ 'log once, and the 30-day cookie it exchanges covers this plugin\'s '
|
||||
+ 'rewritten requests too.',
|
||||
),
|
||||
forceClientLoopback: z
|
||||
.boolean()
|
||||
@@ -101,6 +159,17 @@ export const Config = z.object({
|
||||
+ 'off when @linxin666/dsh-remote-web-ui is installed: it provides the '
|
||||
+ 'same service, and two providers for one name is a load error.',
|
||||
),
|
||||
provideWebRuntime: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.description(
|
||||
'Provide the Web-runtime trust snapshot that releases from 0.2.1-alpha.2 '
|
||||
+ 'on stopped publishing, when nothing else provides it. Plugins that '
|
||||
+ 'inject `webRuntime` — the sidebar among them — stay pending without '
|
||||
+ 'it, and their routes are never registered, which their pane reports '
|
||||
+ 'as an HTTP 405. Turn this off to leave those plugins unmounted on a '
|
||||
+ 'harness that removed the service.',
|
||||
),
|
||||
spoofSocketAddress: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
@@ -145,7 +214,7 @@ export const Config = z.object({
|
||||
*/
|
||||
export function apply(ctx, config) {
|
||||
if (!config.enabled) {
|
||||
ctx.logger?.info('disable-untrusted-origin: disabled by config; no fence was changed')
|
||||
ctx.logger?.info('trustworthy: disabled by config; no fence was changed')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -155,54 +224,78 @@ export function apply(ctx, config) {
|
||||
const authorityNow = () => (authority ??= loopbackAuthority(ctx.webServer.port))
|
||||
|
||||
const onRequest = (request) => {
|
||||
// A listener can outlive its own cleanup when a host tears a fiber down
|
||||
// without running disposers. Cordis nulls the fiber's `uid` at the start of
|
||||
// disposal, so a superseded interceptor recognises itself and stops acting
|
||||
// rather than going on spoofing an identity nobody is asking it to spoof.
|
||||
if (!fiberLive(ctx.fiber)) return
|
||||
loopbackise(request.headers, authorityNow())
|
||||
if (config.spoofSocketAddress) spoofPeerAddress(request)
|
||||
}
|
||||
|
||||
const server = ctx.webServer.server
|
||||
if (server === undefined) {
|
||||
throw new Error(
|
||||
'disable-untrusted-origin: the webserver exposes no raw server; the interceptor cannot be installed',
|
||||
// The host surface is probed rather than assumed. A harness release that
|
||||
// stops exposing the raw server should cost the user this plugin's effect and
|
||||
// a log line, not a failed fiber whose error takes the tree down with it.
|
||||
const server = ctx.webServer?.server
|
||||
if (server === undefined || typeof server.prependListener !== 'function') {
|
||||
ctx.logger?.warn(
|
||||
'trustworthy: the webserver exposes no raw server, so the request-identity '
|
||||
+ 'interceptor was not installed and a Host fence will still refuse a '
|
||||
+ 'remote window; the harness surface may have changed',
|
||||
)
|
||||
} else {
|
||||
// `prependListener`, not `on`: the webserver registers its own request
|
||||
// handler when it constructs the server, so appending would run this after
|
||||
// every route lookup and change nothing.
|
||||
const detach = installInterceptor(server, onRequest)
|
||||
ctx.effect(() => detach, 'trustworthy: request identity interceptor')
|
||||
}
|
||||
// `prependListener`, not `on`: the webserver registers its own request
|
||||
// handler when it constructs the server, so appending would run this after
|
||||
// every route lookup and change nothing.
|
||||
server.prependListener('request', onRequest)
|
||||
server.prependListener('upgrade', onRequest)
|
||||
ctx.effect(
|
||||
() => () => {
|
||||
server.removeListener('request', onRequest)
|
||||
server.removeListener('upgrade', onRequest)
|
||||
},
|
||||
'disable-untrusted-origin: request identity interceptor',
|
||||
)
|
||||
|
||||
if (config.disableAuth) {
|
||||
const connection = ctx.connection
|
||||
const originals = {
|
||||
requestRejection: connection.requestRejection,
|
||||
authorizeIndex: connection.authorizeIndex,
|
||||
authenticatedUrl: connection.authenticatedUrl,
|
||||
// The gate is one method. Releases up to `0.2.1-alpha.2` asked
|
||||
// `requestRejection` first and `admit` wrapped its answer; from
|
||||
// `0.2.1-alpha.3` on `admit` applies the fence and the session check
|
||||
// itself, and `requestRejection` is a façade over it. Replacing `admit`
|
||||
// therefore satisfies both shapes, and replacing `requestRejection` keeps
|
||||
// the older shape from short-circuiting around it.
|
||||
//
|
||||
// The peer that comes back is one the harness already owns: `operator` up
|
||||
// to `0.2.1-alpha.2`, `browserPeer` from `0.2.1-alpha.3` on. There is no
|
||||
// synthetic identity to invent, and returning the owner's peer is exactly
|
||||
// what the session check would have produced for a logged-in browser.
|
||||
//
|
||||
// `authenticatedUrl` is the startup URL and the remote-access handoff;
|
||||
// returning the base URL keeps the process token out of the printed link.
|
||||
//
|
||||
// Each replacement is live-aware rather than unconditional. A host that
|
||||
// takes a plugin out of service by editing its patch row does not always
|
||||
// run the plugin's disposers, and a service method that goes on answering
|
||||
// "admitted" after the plugin was switched off is the worst possible leak:
|
||||
// the fence would look restored while the gateway stayed open. When the
|
||||
// fiber is gone these delegate to the true original instead — read from the
|
||||
// handover carrier, so a later generation still finds the real one rather
|
||||
// than a predecessor's replacement.
|
||||
const live = () => fiberLive(ctx.fiber)
|
||||
const delegate = (key, admitted) =>
|
||||
function (...args) {
|
||||
if (live()) return admitted(...args)
|
||||
const original = originalOf(connection, key)
|
||||
return original === undefined ? undefined : original.apply(this, args)
|
||||
}
|
||||
const admit = (request) => {
|
||||
const peer = connection.browserPeer ?? connection.operator
|
||||
if (peer !== undefined) return { peer }
|
||||
const original = originalOf(connection, 'admit')
|
||||
return original === undefined ? undefined : original.call(connection, request)
|
||||
}
|
||||
// The `/api` gateway asks one method whether the request may proceed; it
|
||||
// applies the identity fence and then the session check. Answering
|
||||
// `undefined` admits both.
|
||||
connection.requestRejection = () => undefined
|
||||
// The shell is served by the frontend's fallback seat, which asks the
|
||||
// connection service before reading index.html. Affirming unconditionally
|
||||
// serves the application on a bare URL, with no process token and no
|
||||
// cookie.
|
||||
connection.authorizeIndex = () => true
|
||||
// The startup URL and the remote-access handoff both come from here;
|
||||
// returning the base URL keeps the token out of the printed link.
|
||||
connection.authenticatedUrl = (baseUrl) => baseUrl
|
||||
ctx.effect(
|
||||
() => () => {
|
||||
for (const [key, value] of Object.entries(originals)) connection[key] = value
|
||||
},
|
||||
'disable-untrusted-origin: authentication bypass',
|
||||
)
|
||||
const restore = installReplacements(connection, {
|
||||
admit: delegate('admit', admit),
|
||||
requestRejection: delegate('requestRejection', () => undefined),
|
||||
authorizeIndex: delegate('authorizeIndex', () => true),
|
||||
authenticatedUrl: delegate('authenticatedUrl', (baseUrl) => baseUrl),
|
||||
})
|
||||
ctx.effect(() => restore, 'trustworthy: authentication bypass')
|
||||
}
|
||||
|
||||
if (config.grantPairing) {
|
||||
@@ -221,12 +314,42 @@ export function apply(ctx, config) {
|
||||
// test, it only happens for a remote window, which is why the Skill Center
|
||||
// works on the host and fails everywhere else.
|
||||
//
|
||||
// Registered on this plugin's own fiber, so unload withdraws it.
|
||||
// Registered on this plugin's own fiber, so unload withdraws it. The answer
|
||||
// is gated on the fiber being live as well: if a host switches the plugin
|
||||
// off without running its disposers, the registration would otherwise go on
|
||||
// vouching for every device.
|
||||
if (ctx.get(PAIRING_SERVICE) === undefined) {
|
||||
ctx.provide(PAIRING_SERVICE, { isPairedDevice: () => true })
|
||||
ctx.provide(PAIRING_SERVICE, { isPairedDevice: () => fiberLive(ctx.fiber) })
|
||||
} else {
|
||||
ctx.logger?.info(
|
||||
`disable-untrusted-origin: ${PAIRING_SERVICE} is already provided; leaving that provider in place`,
|
||||
`trustworthy: ${PAIRING_SERVICE} is already provided; leaving that provider in place`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (config.provideWebRuntime) {
|
||||
// Not a fence change, and not a declaration of the arriving authority: this
|
||||
// restores a service the harness stopped publishing, for plugins that inject
|
||||
// it and would otherwise never mount at all. The value is read live from
|
||||
// `connection`, so it follows the same trust source the `/api` fence derives
|
||||
// its own list from rather than a snapshot frozen at assembly time.
|
||||
//
|
||||
// Registered on this plugin's own fiber, so unload withdraws it and a
|
||||
// consumer that depended on it is released with it. Unlike the pairing
|
||||
// service below there is no liveness gate on the answer: that one *decides*
|
||||
// whether a device is paired, so a registration outliving its disposers
|
||||
// would keep vouching for devices, while this one only republishes the
|
||||
// authorities `connection` already carries. Probing first matters for the
|
||||
// same reason it does for pairing: a second registration of one service
|
||||
// name is a load error.
|
||||
if (ctx.get(WEB_RUNTIME_SERVICE) === undefined) {
|
||||
ctx.provide(WEB_RUNTIME_SERVICE, webRuntimeShim(ctx))
|
||||
ctx.logger?.info(
|
||||
`trustworthy: provided the ${WEB_RUNTIME_SERVICE} service this harness no longer publishes`,
|
||||
)
|
||||
} else {
|
||||
ctx.logger?.info(
|
||||
`trustworthy: ${WEB_RUNTIME_SERVICE} is already provided; leaving that provider in place`,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -262,47 +385,60 @@ export function apply(ctx, config) {
|
||||
}
|
||||
|
||||
if (config.shimPwa) {
|
||||
// Served from the webserver rather than injected inline, so the browser
|
||||
// can fetch it under the URL the manifest link advertises.
|
||||
dispose.push(ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: MANIFEST_PATH,
|
||||
handler: (request, response) => {
|
||||
const body = JSON.stringify(manifest('DeepSeek Harness'))
|
||||
response.writeHead(200, {
|
||||
'content-type': 'application/manifest+json; charset=utf-8',
|
||||
'content-length': Buffer.byteLength(body),
|
||||
'cache-control': 'no-cache',
|
||||
})
|
||||
response.end(body)
|
||||
},
|
||||
}))
|
||||
// Both seats are probed, for the same reason the raw server is: the
|
||||
// harness reshapes this surface between releases, and a missing method
|
||||
// should cost the user a log line rather than a failed fiber.
|
||||
if (
|
||||
typeof ctx.webServer?.register !== 'function'
|
||||
|| typeof ctx.webServer?.tapIndex !== 'function'
|
||||
) {
|
||||
ctx.logger?.warn(
|
||||
'trustworthy: the webserver exposes no route registry or index '
|
||||
+ 'transform, so the installable-app metadata was not added',
|
||||
)
|
||||
} else {
|
||||
// Served from the webserver rather than injected inline, so the browser
|
||||
// can fetch it under the URL the manifest link advertises.
|
||||
dispose.push(ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: MANIFEST_PATH,
|
||||
handler: (request, response) => {
|
||||
const body = JSON.stringify(manifest('DeepSeek Harness'))
|
||||
response.writeHead(200, {
|
||||
'content-type': 'application/manifest+json; charset=utf-8',
|
||||
'content-length': Buffer.byteLength(body),
|
||||
'cache-control': 'no-cache',
|
||||
})
|
||||
response.end(body)
|
||||
},
|
||||
}))
|
||||
|
||||
ctx.inject(['webServer'], (webCtx) => {
|
||||
webCtx.on('webserver/index-inject', (table) => {
|
||||
table.push({
|
||||
kind: 'html',
|
||||
placement: 'head',
|
||||
html: pwaMarkup({ manifestPath: MANIFEST_PATH, includeManifestLink: true }),
|
||||
ctx.inject(['webServer'], (webCtx) => {
|
||||
webCtx.on('webserver/index-inject', (table) => {
|
||||
table.push({
|
||||
kind: 'html',
|
||||
placement: 'head',
|
||||
html: pwaMarkup({ manifestPath: MANIFEST_PATH, includeManifestLink: true }),
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// The viewport tag already exists, so it is rewritten in place rather
|
||||
// than joined by a second one whose precedence the browser decides.
|
||||
dispose.push(ctx.webServer.tapIndex(withCoverViewport))
|
||||
// The viewport tag already exists, so it is rewritten in place rather
|
||||
// than joined by a second one whose precedence the browser decides.
|
||||
dispose.push(ctx.webServer.tapIndex(withCoverViewport))
|
||||
}
|
||||
}
|
||||
|
||||
ctx.effect(
|
||||
() => () => {
|
||||
for (const undo of dispose) undo()
|
||||
},
|
||||
'disable-untrusted-origin: browser shims',
|
||||
'trustworthy: browser shims',
|
||||
)
|
||||
}
|
||||
|
||||
ctx.logger?.info(
|
||||
`disable-untrusted-origin: every window is treated as local; authentication is ${
|
||||
`trustworthy: every window is treated as local; authentication is ${
|
||||
config.disableAuth ? 'disabled' : 'kept'
|
||||
}`,
|
||||
)
|
||||
|
||||
+3
-3
@@ -13,13 +13,13 @@
|
||||
*/
|
||||
|
||||
/** Attribute marking the injected shim script, so a second injection is a no-op. */
|
||||
export const SHIM_MARKER = 'data-dsh-duo-shims'
|
||||
export const SHIM_MARKER = 'data-dsh-trustworthy-shims'
|
||||
|
||||
/** Attribute marking the injected PWA metadata block. */
|
||||
export const PWA_MARKER = 'data-dsh-duo-pwa'
|
||||
export const PWA_MARKER = 'data-dsh-trustworthy-pwa'
|
||||
|
||||
/** Where the plugin serves its PWA manifest from. */
|
||||
export const MANIFEST_PATH = '/dsh-disable-untrusted-origin/manifest.webmanifest'
|
||||
export const MANIFEST_PATH = '/dsh-trustworthy/manifest.webmanifest'
|
||||
|
||||
/**
|
||||
* The page-side shim, as a single IIFE.
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* dsh-trustworthy — the `webRuntime` seam, for harness releases that stopped
|
||||
* providing it.
|
||||
*
|
||||
* `@deepseek-ai/dsh-web-app` used to provide a `webRuntime` service whose value
|
||||
* was the LAN-trust snapshot — `resolveLanTrust(ctx.webServer.host, trustedHosts)`,
|
||||
* that is `{ lanAddresses, trustedHosts }`. Releases from `0.2.1-alpha.2` on no
|
||||
* longer provide it: the `--trusted-host` authorities are parsed by the
|
||||
* `webStartup` service and consumed by `@deepseek-ai/dsh-client-connection` into
|
||||
* `connection.trustedHosts`, and the listener's own bind address is accepted by
|
||||
* the `/api` fence as a separate case.
|
||||
*
|
||||
* Plugins written against the old shape never learn that it moved. They declare
|
||||
* `inject: ['webRuntime']`, so Cordis holds their row **pending** — the module
|
||||
* loads and its inject list is read, but the fiber never mounts. Their routes
|
||||
* are then simply absent, and the core fallback answers in their place: a
|
||||
* `POST /sidebar/api/fs.list` that matches no route falls through to the
|
||||
* static-file handler, which allows `GET`/`HEAD` only and answers **405**.
|
||||
*
|
||||
* This module fills that seam. Same service name, same value shape, but read
|
||||
* live from the trust source the harness actually has now, rather than cloned
|
||||
* at assembly time — so a later `--trusted-host`, or a row that changed
|
||||
* `connection`'s config, is visible to a plugin's own copy of the fence.
|
||||
*
|
||||
* @module dsh-trustworthy/web-runtime
|
||||
*/
|
||||
|
||||
/** Service name sibling plugins inject, and read, for the Web runtime snapshot. */
|
||||
export const WEB_RUNTIME_SERVICE = 'webRuntime'
|
||||
|
||||
/**
|
||||
* Bind hosts that name every interface rather than one of them. A wildcard can
|
||||
* be written as an authority but never *means* one, so it is not an entry.
|
||||
*/
|
||||
const WILDCARD_BIND_HOSTS = new Set(['0.0.0.0', '::', '::0', '*'])
|
||||
|
||||
/**
|
||||
* The non-loopback authorities this deployment declared — the `--trusted-host`
|
||||
* values, as `connection` received them. Read per call rather than captured, so
|
||||
* the snapshot tracks the same list the `/api` fence is using.
|
||||
*
|
||||
* @param ctx - host plugin context carrying `connection`.
|
||||
* @returns declared authorities, in the order they were configured.
|
||||
*/
|
||||
export function connectionAuthorities(ctx) {
|
||||
const declared = ctx.connection?.trustedHosts
|
||||
if (!Array.isArray(declared)) return []
|
||||
return declared.filter((entry) => typeof entry === 'string' && entry !== '')
|
||||
}
|
||||
|
||||
/**
|
||||
* The listener's own bind address, when it names one interface. `0.2.1-alpha.2`'s
|
||||
* `/api` fence accepts this address on its own (`isBindAddressAuthority`), and
|
||||
* a plugin carrying a private copy of the older two-argument fence cannot: it
|
||||
* only ever compares against the list it is handed. Publishing the bind address
|
||||
* as an entry makes that older fence accept exactly what the core fence accepts
|
||||
* — the entry is port-less, so like the core check it matches the address on any
|
||||
* port, and a wildcard is not an authority: `0.2.1-alpha.2` refuses to bind one
|
||||
* at all (`host "0.0.0.0" is an unspecified (wildcard) address, which is not
|
||||
* supported`), so that case is unreachable rather than merely unused.
|
||||
*
|
||||
* @param ctx - host plugin context carrying `webServer`.
|
||||
* @returns the bind host, or undefined when the surface is gone or wildcarded.
|
||||
*/
|
||||
export function bindAuthority(ctx) {
|
||||
const host = ctx.webServer?.host
|
||||
if (typeof host !== 'string' || host === '' || WILDCARD_BIND_HOSTS.has(host)) return undefined
|
||||
return host
|
||||
}
|
||||
|
||||
/**
|
||||
* The authorities the removed `webRuntime.trustedHosts` would carry today.
|
||||
*
|
||||
* @param ctx - host plugin context carrying `connection` and `webServer`.
|
||||
* @returns deduplicated authorities: the declared ones, then the bind address.
|
||||
*/
|
||||
export function trustedAuthorities(ctx) {
|
||||
const declared = connectionAuthorities(ctx)
|
||||
const bind = bindAuthority(ctx)
|
||||
return bind === undefined ? [...new Set(declared)] : [...new Set([...declared, bind])]
|
||||
}
|
||||
|
||||
/**
|
||||
* The value of the `webRuntime` service, shaped as `0.2.1-alpha.1` provided it.
|
||||
*
|
||||
* Both members are getters: a consumer reads `trustedHosts` inside its fence, per
|
||||
* request, so a snapshot that could not see a later authority would quietly
|
||||
* refuse requests the `/api` gateway admits. `lanAddresses` stays empty because
|
||||
* `0.2.1-alpha.2` rejects a wildcard bind — alpha.1 filled it from the host's
|
||||
* interfaces only for `0.0.0.0`, so the empty list is that same function's
|
||||
* answer for every bind this harness allows.
|
||||
*
|
||||
* When dsh-trustworthy's interceptor is installed the list is inert for the
|
||||
* plugin's own routes: every request arrives carrying the loopback authority, so
|
||||
* a fence written against this value admits it before reading the list. The
|
||||
* populated list matters to consumers that read it for another reason, and to a
|
||||
* deployment that installs this shim without the interceptor.
|
||||
*
|
||||
* @param ctx - host plugin context carrying `connection` and `webServer`.
|
||||
* @returns the service value.
|
||||
*/
|
||||
export function webRuntimeShim(ctx) {
|
||||
return {
|
||||
get trustedHosts() {
|
||||
return trustedAuthorities(ctx)
|
||||
},
|
||||
get lanAddresses() {
|
||||
return []
|
||||
},
|
||||
}
|
||||
}
|
||||
+10
-5
@@ -1,14 +1,16 @@
|
||||
{
|
||||
"name": "dsh-disable-untrusted-origin",
|
||||
"version": "0.1.2",
|
||||
"description": "Treat every browser window as if it were running on the DeepSeek Harness host itself: answers each request with the loopback authority so no Host/Origin fence refuses it, optionally removes the browser-session check, and restores the browser APIs a non-secure page is denied.",
|
||||
"name": "dsh-trustworthy",
|
||||
"version": "0.5.1",
|
||||
"description": "Removes the untrusted-origin restriction from DeepSeek Harness while keeping its own session check: every browser window is treated as if it were running on the harness machine itself, so no declared trusted host and no per-plugin origin fence refuse it. One interceptor answers every request with the loopback authority, and the one-time launch token is exchanged for a 30-day cookie exactly as on the loopback host.",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"exports": {
|
||||
".": "./lib/index.js",
|
||||
"./authority": "./lib/authority.js",
|
||||
"./handover": "./lib/handover.js",
|
||||
"./package.json": "./package.json",
|
||||
"./shims": "./lib/shims.js"
|
||||
"./shims": "./lib/shims.js",
|
||||
"./web-runtime": "./lib/web-runtime.js"
|
||||
},
|
||||
"files": [
|
||||
"lib/",
|
||||
@@ -17,6 +19,9 @@
|
||||
"LICENSE"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"dsh": ">=0.1.7-rc.2 <0.3.0-0"
|
||||
},
|
||||
"keywords": [
|
||||
"dsh",
|
||||
"dsh-plugin",
|
||||
@@ -31,7 +36,7 @@
|
||||
"patch": "./cordis.patch.yml"
|
||||
},
|
||||
"compatibility": {
|
||||
"dsh": ">=0.1.7-rc.2"
|
||||
"dsh": ">=0.1.7-rc.2 <0.3.0-0"
|
||||
}
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
+27
-2
@@ -4,8 +4,11 @@
|
||||
* Verifies, against the process actually serving your browser, that
|
||||
* 1. a non-loopback `Host` is admitted by the plugin market's fence,
|
||||
* 2. the shell is served without a process token,
|
||||
* 3. the Skill Center answers a non-loopback *peer*, and
|
||||
* 4. the browser shims and the PWA manifest actually reach the page.
|
||||
* 3. the Skill Center answers a non-loopback *peer*,
|
||||
* 4. the browser shims and the PWA manifest actually reach the page, and
|
||||
* 5. the sidebar's Files API is registered rather than falling through to the
|
||||
* static handler as a 405 — the shape a plugin takes when the service it
|
||||
* injects (`webRuntime`) is not provided.
|
||||
*
|
||||
* Point 3 is the one that needs care: the Skill Center fences on the socket
|
||||
* address as well as the Host, so a probe over 127.0.0.1 can never reproduce a
|
||||
@@ -140,11 +143,33 @@ try {
|
||||
}
|
||||
record('manifest is served', manifestOk, `${manifest.status}`)
|
||||
|
||||
// A plugin whose injection is unsatisfied never runs `apply`, so its routes are
|
||||
// absent and this URL is answered by the core static handler, which allows only
|
||||
// GET/HEAD. A registered route answers 400 (no sessionId) or 404 in the plugin's
|
||||
// own JSON shape; 405 is the fall-through, and is the whole of "the Files pane
|
||||
// stopped previewing anything".
|
||||
const sidebar = await request({
|
||||
method: 'POST',
|
||||
path: '/sidebar/api/fs.tree',
|
||||
host: anyIdentity,
|
||||
body: '{}',
|
||||
})
|
||||
const sidebarMounted = sidebar.status !== 405 && sidebar.status !== 0
|
||||
record(
|
||||
'sidebar Files API is registered',
|
||||
sidebarMounted,
|
||||
sidebarMounted
|
||||
? `${sidebar.status} from a registered route`
|
||||
: '405 from the static handler: the plugin never mounted (is webRuntime provided?)',
|
||||
)
|
||||
|
||||
const failed = checks.filter((check) => !check.ok)
|
||||
console.log(`\n${checks.length - failed.length}/${checks.length} passed`)
|
||||
if (failed.length > 0) {
|
||||
console.log('\nA 403 on the market means the origin fence is still in force.')
|
||||
console.log('A 400 on the Skill Center means it is still refusing (or throwing for) a remote peer.')
|
||||
console.log('A missing shim or manifest usually means the updated bundle is not loaded yet.')
|
||||
console.log('A 405 on the Files API means a plugin stayed pending: check the boot log for')
|
||||
console.log('"did not activate" and whether the service it injects is provided.')
|
||||
process.exit(1)
|
||||
}
|
||||
+189
-24
@@ -17,13 +17,17 @@ import test from 'node:test'
|
||||
const PLUGIN = '../lib/index.js'
|
||||
|
||||
/** A host context carrying only what the plugin touches. */
|
||||
async function mockHost() {
|
||||
async function mockHost({ rawServer = true, registry = true } = {}) {
|
||||
const disposers = []
|
||||
const hooks = new Map()
|
||||
const warnings = []
|
||||
const originals = {
|
||||
requestRejection: function requestRejection() {
|
||||
return 403
|
||||
},
|
||||
admit: function admit() {
|
||||
return { rejection: 401 }
|
||||
},
|
||||
authorizeIndex: function authorizeIndex() {
|
||||
return false
|
||||
},
|
||||
@@ -31,7 +35,12 @@ async function mockHost() {
|
||||
return `${baseUrl}?token=launch-secret`
|
||||
},
|
||||
}
|
||||
const connection = { ...originals }
|
||||
const connection = {
|
||||
...originals,
|
||||
// Releases up to 0.2.1-alpha.2 named the owner peer `operator`; from
|
||||
// 0.2.1-alpha.3 on it is `browserPeer`. A real host has one or the other.
|
||||
browserPeer: { id: 'browser-peer' },
|
||||
}
|
||||
const provided = new Map()
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200)
|
||||
@@ -40,33 +49,47 @@ async function mockHost() {
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
|
||||
// The webserver is a route registry plus an index transform list, and both
|
||||
// refuse duplicates or release cleanly exactly as the real one does.
|
||||
// refuse duplicates or release cleanly exactly as the real one does. Either
|
||||
// seat can be withheld, so the tests can prove the plugin degrades to a
|
||||
// warning rather than to a failed fiber when a release reshapes the surface.
|
||||
const exact = new Map()
|
||||
const taps = []
|
||||
const webServer = {
|
||||
port: server.address().port,
|
||||
server,
|
||||
host: '0.0.0.0',
|
||||
register(route) {
|
||||
if (exact.has(route.path)) {
|
||||
throw new Error(`webserver: duplicate ${route.kind} route "${route.path}"`)
|
||||
}
|
||||
exact.set(route.path, route)
|
||||
return () => {
|
||||
exact.delete(route.path)
|
||||
}
|
||||
},
|
||||
tapIndex(transform) {
|
||||
taps.push(transform)
|
||||
return () => {
|
||||
const at = taps.indexOf(transform)
|
||||
if (at !== -1) taps.splice(at, 1)
|
||||
}
|
||||
},
|
||||
...(rawServer ? { server } : {}),
|
||||
...(registry
|
||||
? {
|
||||
register(route) {
|
||||
if (exact.has(route.path)) {
|
||||
throw new Error(`webserver: duplicate ${route.kind} route "${route.path}"`)
|
||||
}
|
||||
exact.set(route.path, route)
|
||||
return () => {
|
||||
exact.delete(route.path)
|
||||
}
|
||||
},
|
||||
tapIndex(transform) {
|
||||
taps.push(transform)
|
||||
return () => {
|
||||
const at = taps.indexOf(transform)
|
||||
if (at !== -1) taps.splice(at, 1)
|
||||
}
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
|
||||
const ctx = {
|
||||
logger: { info() {} },
|
||||
// Cordis nulls a fiber's uid at the start of disposal, and leaves it
|
||||
// non-null for as long as the plugin is mounted.
|
||||
fiber: { uid: 1 },
|
||||
logger: {
|
||||
info() {},
|
||||
warn(message) {
|
||||
warnings.push(message)
|
||||
},
|
||||
},
|
||||
webServer,
|
||||
connection,
|
||||
effect(callback) {
|
||||
@@ -105,6 +128,7 @@ async function mockHost() {
|
||||
provided,
|
||||
exact,
|
||||
taps,
|
||||
warnings,
|
||||
/** Apply the registered index transforms, as `renderIndex` does. */
|
||||
renderIndex(html) {
|
||||
return taps.reduce((current, tap) => tap(current), html)
|
||||
@@ -179,21 +203,39 @@ test('disableAuth replaces the session methods and unload restores them', async
|
||||
const host = await mockHost()
|
||||
const { apply } = await import(PLUGIN)
|
||||
apply(host.ctx, CONFIG)
|
||||
assert.deepEqual(host.connection.admit({}), { peer: host.connection.browserPeer })
|
||||
assert.equal(host.connection.requestRejection({}), undefined)
|
||||
assert.equal(host.connection.authorizeIndex({}, {}), true)
|
||||
assert.equal(host.connection.authenticatedUrl('http://box:3080'), 'http://box:3080')
|
||||
host.unload()
|
||||
assert.deepEqual(host.connection.admit({}), { rejection: 401 })
|
||||
assert.equal(host.connection.requestRejection({}), 403)
|
||||
assert.equal(host.connection.authorizeIndex({}, {}), false)
|
||||
assert.equal(host.connection.authenticatedUrl('http://box:3080'), 'http://box:3080?token=launch-secret')
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
})
|
||||
|
||||
test('disableAuth admits through the operator peer on 0.2.1-alpha.2 and older', async () => {
|
||||
const host = await mockHost()
|
||||
const operator = { id: 'operator-peer' }
|
||||
delete host.connection.browserPeer
|
||||
host.connection.operator = operator
|
||||
const { apply } = await import(PLUGIN)
|
||||
apply(host.ctx, CONFIG)
|
||||
try {
|
||||
assert.deepEqual(host.connection.admit({}), { peer: operator })
|
||||
} finally {
|
||||
host.unload()
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
}
|
||||
})
|
||||
|
||||
test('disableAuth false leaves the session methods untouched', async () => {
|
||||
const host = await mockHost()
|
||||
const { apply } = await import(PLUGIN)
|
||||
apply(host.ctx, { ...CONFIG, disableAuth: false })
|
||||
try {
|
||||
assert.deepEqual(host.connection.admit({}), { rejection: 401 })
|
||||
assert.equal(host.connection.requestRejection({}), 403)
|
||||
assert.equal(host.connection.authorizeIndex({}, {}), false)
|
||||
} finally {
|
||||
@@ -299,7 +341,7 @@ test('the shims reach the index and the manifest answers', async () => {
|
||||
try {
|
||||
const rows = host.rows()
|
||||
|
||||
const script = rows.find((row) => row.kind === 'script' && row.text?.includes('data-dsh-duo-shims'))
|
||||
const script = rows.find((row) => row.kind === 'script' && row.text?.includes('data-dsh-trustworthy-shims'))
|
||||
assert.ok(script, 'the shim script row is present')
|
||||
assert.equal(script.placement, 'head', 'the shim runs before any bundle')
|
||||
assert.match(script.text, /getRandomValues/, 'the UUID polyfill mints from the unrestricted call')
|
||||
@@ -353,7 +395,7 @@ test('turning the shims off leaves the index alone', async () => {
|
||||
apply(host.ctx, { ...CONFIG, shimClipboard: false, shimRandomUuid: false, shimPwa: false })
|
||||
try {
|
||||
const rows = host.rows()
|
||||
assert.equal(rows.filter((row) => row.text?.includes('data-dsh-duo-shims')).length, 0, 'no shim script')
|
||||
assert.equal(rows.filter((row) => row.text?.includes('data-dsh-trustworthy-shims')).length, 0, 'no shim script')
|
||||
assert.equal(rows.filter((row) => row.kind === 'html').length, 0, 'no PWA metadata')
|
||||
assert.equal(rows.filter((row) => row.text?.includes('ownsHost')).length, 1, 'the identity grant is unaffected')
|
||||
assert.equal(host.exact.size, 0, 'no manifest route')
|
||||
@@ -370,7 +412,7 @@ test('the PWA shim alone does not drag the browser shims in', async () => {
|
||||
apply(host.ctx, { ...CONFIG, shimClipboard: false, shimRandomUuid: false })
|
||||
try {
|
||||
const rows = host.rows()
|
||||
assert.equal(rows.filter((row) => row.kind === 'script' && row.text?.includes('data-dsh-duo-shims')).length, 0)
|
||||
assert.equal(rows.filter((row) => row.kind === 'script' && row.text?.includes('data-dsh-trustworthy-shims')).length, 0)
|
||||
assert.equal(rows.filter((row) => row.kind === 'html').length, 1)
|
||||
assert.equal(host.exact.size, 1)
|
||||
} finally {
|
||||
@@ -388,3 +430,126 @@ test('unload withdraws the manifest route and the index transform', async () =>
|
||||
assert.equal(host.taps.length, 0, 'the viewport transform is released')
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
})
|
||||
|
||||
// The rest of the suite is about being switched off by a host that does not
|
||||
// run disposers, and about a reload that gives the installation two authors.
|
||||
|
||||
test('a disposed fiber stops admitting requests', async () => {
|
||||
// A host can take a plugin out of service by editing its patch row, and the
|
||||
// harness does not always run the plugin's disposers when it does. An
|
||||
// installed-but-switched-off plugin whose service methods still answer
|
||||
// "admitted" is the worst case: the interface reports the plugin as off while
|
||||
// the gateway stands open.
|
||||
const host = await mockHost()
|
||||
const { apply } = await import(PLUGIN)
|
||||
apply(host.ctx, CONFIG)
|
||||
|
||||
assert.deepEqual(host.connection.admit({}), { peer: host.connection.browserPeer }, 'admitting while mounted')
|
||||
assert.equal(host.connection.requestRejection(), undefined, 'admitted while mounted')
|
||||
assert.equal(host.connection.authorizeIndex(), true)
|
||||
assert.equal(host.connection.authenticatedUrl('/base'), '/base')
|
||||
|
||||
host.ctx.fiber.uid = null
|
||||
assert.deepEqual(host.connection.admit({}), { rejection: 401 }, 'the real gate answers again')
|
||||
assert.equal(host.connection.requestRejection(), 403, 'the real fence answers again')
|
||||
assert.equal(host.connection.authorizeIndex(), false)
|
||||
assert.equal(
|
||||
host.connection.authenticatedUrl('/base'),
|
||||
'/base?token=launch-secret',
|
||||
'the launch token comes back',
|
||||
)
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
})
|
||||
|
||||
test('a disposed fiber stops rewriting request identity', async () => {
|
||||
const host = await mockHost()
|
||||
const { apply } = await import(PLUGIN)
|
||||
apply(host.ctx, CONFIG)
|
||||
|
||||
const interceptor = host.server.listeners('request')[0]
|
||||
const mounted = { headers: { host: '192.168.1.49:3080' } }
|
||||
interceptor(mounted)
|
||||
assert.equal(mounted.headers.host, `127.0.0.1:${host.ctx.webServer.port}`)
|
||||
|
||||
host.ctx.fiber.uid = null
|
||||
const after = { headers: { host: '192.168.1.49:3080' } }
|
||||
interceptor(after)
|
||||
assert.equal(after.headers.host, '192.168.1.49:3080', 'a dead generation rewrites nothing')
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
})
|
||||
|
||||
test('a disposed fiber stops vouching for paired devices', async () => {
|
||||
const host = await mockHost()
|
||||
const { apply } = await import(PLUGIN)
|
||||
apply(host.ctx, CONFIG)
|
||||
|
||||
const pairing = host.provided.get('remoteWebUiPairing')
|
||||
assert.equal(pairing.isPairedDevice(), true)
|
||||
host.ctx.fiber.uid = null
|
||||
assert.equal(pairing.isPairedDevice(), false, 'an off plugin vouches for nobody')
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
})
|
||||
|
||||
test('a late cleanup from the previous generation leaves the reload in charge', async () => {
|
||||
// The ordering the harness does not promise: on reload the successor applies
|
||||
// before the predecessor's disposers run. The two generations share one
|
||||
// connection service, so the predecessor's cleanup is the dangerous one — an
|
||||
// unconditional restore would put the fence back while the successor still
|
||||
// believed it was mounted.
|
||||
const previous = await mockHost()
|
||||
const current = await mockHost()
|
||||
previous.ctx.connection = current.ctx.connection
|
||||
|
||||
const { apply } = await import(PLUGIN)
|
||||
apply(previous.ctx, CONFIG)
|
||||
apply(current.ctx, CONFIG)
|
||||
|
||||
previous.unload()
|
||||
assert.equal(
|
||||
current.connection.requestRejection(),
|
||||
undefined,
|
||||
'the successor is still admitting after the predecessor was cleaned up',
|
||||
)
|
||||
|
||||
current.unload()
|
||||
assert.equal(current.connection.requestRejection(), 403, 'the original survives both generations')
|
||||
assert.equal(current.connection.authenticatedUrl('/base'), '/base?token=launch-secret')
|
||||
await new Promise((resolve) => previous.server.close(resolve))
|
||||
await new Promise((resolve) => current.server.close(resolve))
|
||||
})
|
||||
|
||||
test('a webserver with no raw server is reported, not fatal', async () => {
|
||||
// A release may reshape the surface the plugin reaches through. Losing an
|
||||
// optional capability is a warning; throwing would fail the fiber and take
|
||||
// the parts that still work down with it.
|
||||
const host = await mockHost({ rawServer: false })
|
||||
const { apply } = await import(PLUGIN)
|
||||
|
||||
assert.doesNotThrow(() => apply(host.ctx, CONFIG))
|
||||
assert.equal(host.warnings.length, 1, 'the loss is reported')
|
||||
assert.match(host.warnings[0], /no raw server/)
|
||||
assert.equal(host.connection.requestRejection(), undefined, 'the rest still works')
|
||||
host.unload()
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
})
|
||||
|
||||
test('a webserver with no route registry is reported, not fatal', async () => {
|
||||
const host = await mockHost({ registry: false })
|
||||
const { apply } = await import(PLUGIN)
|
||||
|
||||
assert.doesNotThrow(() => apply(host.ctx, CONFIG))
|
||||
assert.equal(host.warnings.length, 1)
|
||||
assert.match(host.warnings[0], /no route registry/)
|
||||
assert.equal(host.connection.requestRejection(), undefined)
|
||||
host.unload()
|
||||
await new Promise((resolve) => host.server.close(resolve))
|
||||
})
|
||||
|
||||
test('the shipped default removes the session check', async () => {
|
||||
// A token prompt on every new device is the friction this plugin exists to
|
||||
// remove; 0.4.0 made the check opt-out, and that regressed the posture.
|
||||
const { Config } = await import(PLUGIN)
|
||||
const defaults = Config({})
|
||||
assert.equal(defaults.enabled, true)
|
||||
assert.equal(defaults.disableAuth, true)
|
||||
})
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* Behavioural check for the generation handover.
|
||||
*
|
||||
* The mechanism this plugin installs is a mutation of objects the harness
|
||||
* owns, and a reload gives those mutations two authors. These tests are about
|
||||
* the orderings — which the harness does not promise — and about the two ways
|
||||
* a reload goes wrong: a predecessor's cleanup tearing down its successor, and
|
||||
* a superseded installation going on acting after it was replaced.
|
||||
*
|
||||
* node test/handover.test.mjs
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
HANDOVER,
|
||||
INTERCEPTOR,
|
||||
fiberLive,
|
||||
installInterceptor,
|
||||
installReplacements,
|
||||
originalOf,
|
||||
} from '../lib/handover.js'
|
||||
|
||||
/** A stand-in for a service whose methods the plugin replaces. */
|
||||
function service() {
|
||||
return {
|
||||
requestRejection: () => 403,
|
||||
authorizeIndex: () => false,
|
||||
authenticatedUrl: (baseUrl) => `${baseUrl}?token=secret`,
|
||||
}
|
||||
}
|
||||
|
||||
/** The replacements one generation installs, distinguishable from another's. */
|
||||
function generation(tag, { live = () => true } = {}) {
|
||||
const admitted = () => `admitted-by-${tag}`
|
||||
return {
|
||||
requestRejection: () => (live() ? admitted() : 'delegated'),
|
||||
authorizeIndex: () => live(),
|
||||
authenticatedUrl: (baseUrl) => (live() ? baseUrl : `${baseUrl}?token=secret`),
|
||||
}
|
||||
}
|
||||
|
||||
test('the originals are recorded once and restored on cleanup', () => {
|
||||
const target = service()
|
||||
const first = generation('one')
|
||||
|
||||
const restore = installReplacements(target, first)
|
||||
assert.equal(target.requestRejection(), 'admitted-by-one')
|
||||
assert.equal(target.authenticatedUrl('/base'), '/base', 'the token is gone while installed')
|
||||
|
||||
restore()
|
||||
assert.equal(target.requestRejection(), 403, 'the fence is back')
|
||||
assert.equal(target.authorizeIndex(), false)
|
||||
assert.equal(target.authenticatedUrl('/base'), '/base?token=secret')
|
||||
})
|
||||
|
||||
test('a predecessor cleanup cannot tear down its successor', () => {
|
||||
// The ordering the harness does not promise: the successor installs first,
|
||||
// and only then does the predecessor's disposer run. Restoring
|
||||
// unconditionally here would put the true originals back while the successor
|
||||
// still believed it was mounted — the plugin inert, reporting itself live.
|
||||
const target = service()
|
||||
const first = installReplacements(target, generation('one'))
|
||||
const second = installReplacements(target, generation('two'))
|
||||
|
||||
first()
|
||||
assert.equal(target.requestRejection(), 'admitted-by-two', 'the successor still owns the service')
|
||||
assert.equal(target.authenticatedUrl('/base'), '/base')
|
||||
|
||||
second()
|
||||
assert.equal(target.requestRejection(), 403, 'the true original survives both generations')
|
||||
assert.equal(target.authenticatedUrl('/base'), '/base?token=secret')
|
||||
})
|
||||
|
||||
test('a cleanup before the next install leaves the original intact', () => {
|
||||
// The ordering the harness usually produces, asserted so that the guard is
|
||||
// not accidentally relying on the unordered case.
|
||||
const target = service()
|
||||
const first = installReplacements(target, generation('one'))
|
||||
first()
|
||||
|
||||
const second = installReplacements(target, generation('two'))
|
||||
assert.equal(target.requestRejection(), 'admitted-by-two')
|
||||
second()
|
||||
assert.equal(target.requestRejection(), 403, 'not a predecessor replacement')
|
||||
})
|
||||
|
||||
test('the original is readable from the carrier across generations', () => {
|
||||
const target = service()
|
||||
const first = installReplacements(target, generation('one'))
|
||||
assert.equal(originalOf(target, 'requestRejection')(), 403)
|
||||
|
||||
installReplacements(target, generation('two'))
|
||||
assert.equal(
|
||||
originalOf(target, 'requestRejection')(),
|
||||
403,
|
||||
'a later generation must still find the true original, not the predecessor',
|
||||
)
|
||||
first()
|
||||
assert.equal(target.requestRejection(), 'admitted-by-two')
|
||||
})
|
||||
|
||||
test('cleanup is idempotent and a third party keeps what it replaced', () => {
|
||||
const target = service()
|
||||
const restore = installReplacements(target, generation('one'))
|
||||
|
||||
target.authorizeIndex = () => 'someone-else'
|
||||
restore()
|
||||
restore()
|
||||
assert.equal(target.authorizeIndex(), 'someone-else', 'a foreign replacement is left alone')
|
||||
assert.equal(target.requestRejection(), 403, 'and the untouched keys are restored')
|
||||
})
|
||||
|
||||
test('a property that did not exist is removed rather than set to undefined', () => {
|
||||
const target = {}
|
||||
const restore = installReplacements(target, { requestRejection: () => 'admitted' })
|
||||
assert.equal(target.requestRejection(), 'admitted')
|
||||
restore()
|
||||
assert.equal('requestRejection' in target, false)
|
||||
})
|
||||
|
||||
test('the carrier is a shared, non-enumerable symbol property', () => {
|
||||
const target = service()
|
||||
const restore = installReplacements(target, generation('one'))
|
||||
assert.equal(HANDOVER, Symbol.for('dsh-trustworthy.handover'), 'shared across module instances')
|
||||
const descriptor = Object.getOwnPropertyDescriptor(target, HANDOVER)
|
||||
assert.equal(descriptor.enumerable, false, 'invisible to a serializer walking the service')
|
||||
restore()
|
||||
assert.equal(target[HANDOVER], undefined, 'withdrawn once nothing is installed')
|
||||
})
|
||||
|
||||
test('a target that refuses the carrier still coordinates', () => {
|
||||
// Some hosts freeze their service objects. Coordination then only covers this
|
||||
// module instance, which is still the common reload path, because a reload
|
||||
// that re-imports the module usually reuses the cached one.
|
||||
const target = Object.preventExtensions(service())
|
||||
const first = installReplacements(target, generation('one'))
|
||||
assert.equal(target.requestRejection(), 'admitted-by-one')
|
||||
first()
|
||||
assert.equal(target.requestRejection(), 403)
|
||||
})
|
||||
|
||||
test('the interceptor is prepended ahead of an existing handler', () => {
|
||||
const server = new EventEmitter()
|
||||
const order = []
|
||||
server.on('request', () => order.push('route'))
|
||||
|
||||
const detach = installInterceptor(server, () => order.push('interceptor'))
|
||||
server.emit('request')
|
||||
assert.deepEqual(order, ['interceptor', 'route'], 'the rewrite runs before any route lookup')
|
||||
|
||||
detach()
|
||||
order.length = 0
|
||||
server.emit('request')
|
||||
assert.deepEqual(order, ['route'])
|
||||
})
|
||||
|
||||
test('the interceptor covers both request and upgrade', () => {
|
||||
const server = new EventEmitter()
|
||||
const seen = []
|
||||
installInterceptor(server, (event) => seen.push(event))
|
||||
server.emit('request', 'request')
|
||||
server.emit('upgrade', 'upgrade')
|
||||
assert.deepEqual(seen, ['request', 'upgrade'], 'a websocket upgrade is a request too')
|
||||
})
|
||||
|
||||
test('a superseded interceptor is retired rather than joined', () => {
|
||||
// A reload can add the successor while the predecessor is still attached.
|
||||
// Two listeners would both run, and the older one is a closure over a dead
|
||||
// generation's configuration.
|
||||
const server = new EventEmitter()
|
||||
const seen = []
|
||||
const first = () => seen.push('old')
|
||||
const detachFirst = installInterceptor(server, first)
|
||||
|
||||
const second = () => seen.push('new')
|
||||
const detachSecond = installInterceptor(server, second)
|
||||
|
||||
assert.equal(server.listenerCount('request'), 1, 'only the successor remains')
|
||||
server.emit('request')
|
||||
assert.deepEqual(seen, ['new'])
|
||||
|
||||
detachFirst()
|
||||
server.emit('request')
|
||||
assert.deepEqual(seen, ['new', 'new'], "the predecessor's cleanup is a harmless no-op")
|
||||
|
||||
detachSecond()
|
||||
assert.equal(server.listenerCount('request'), 0)
|
||||
detachSecond()
|
||||
assert.equal(server.listenerCount('request'), 0, 'cleanup is idempotent')
|
||||
})
|
||||
|
||||
test('the interceptor is marked so a successor can find it', () => {
|
||||
const server = new EventEmitter()
|
||||
const listener = () => {}
|
||||
installInterceptor(server, listener)
|
||||
assert.equal(listener[INTERCEPTOR], true)
|
||||
assert.equal(INTERCEPTOR, Symbol.for('dsh-trustworthy.interceptor'))
|
||||
})
|
||||
|
||||
test('a foreign listener is left in place', () => {
|
||||
const server = new EventEmitter()
|
||||
const foreign = () => {}
|
||||
server.on('request', foreign)
|
||||
const detach = installInterceptor(server, () => {})
|
||||
detach()
|
||||
assert.equal(server.listenerCount('request'), 1)
|
||||
assert.equal(server.listeners('request')[0], foreign)
|
||||
})
|
||||
|
||||
test('liveness answers false only on a positive signal of disposal', () => {
|
||||
assert.equal(fiberLive(undefined), true, 'a host without a fiber is not a reason to disarm')
|
||||
assert.equal(fiberLive(null), true)
|
||||
assert.equal(fiberLive({}), true, 'an unrecognised shape is not a reason to disarm')
|
||||
assert.equal(fiberLive({ uid: 0 }), true, 'the root fiber is live')
|
||||
assert.equal(fiberLive({ uid: 12 }), true)
|
||||
assert.equal(fiberLive({ uid: null }), false, 'cordis nulls uid at the start of disposal')
|
||||
})
|
||||
|
||||
test('a dead generation delegates instead of admitting', () => {
|
||||
// The replacement a live plugin installs on the connection service. Once its
|
||||
// fiber is disposed it must behave as if the plugin were never mounted —
|
||||
// otherwise switching the plugin off would leave the gateway open.
|
||||
const target = service()
|
||||
const fiber = { uid: 1 }
|
||||
const live = () => fiberLive(fiber)
|
||||
const delegate = (key, admitted) =>
|
||||
function delegated(...args) {
|
||||
if (live()) return admitted(...args)
|
||||
const original = originalOf(target, key)
|
||||
return original === undefined ? undefined : original.apply(this, args)
|
||||
}
|
||||
|
||||
installReplacements(target, {
|
||||
requestRejection: delegate('requestRejection', () => undefined),
|
||||
authorizeIndex: delegate('authorizeIndex', () => true),
|
||||
})
|
||||
|
||||
assert.equal(target.requestRejection(), undefined, 'admitted while the fiber is live')
|
||||
assert.equal(target.authorizeIndex(), true)
|
||||
|
||||
fiber.uid = null
|
||||
assert.equal(target.requestRejection(), 403, 'the fence is answered by the original again')
|
||||
assert.equal(target.authorizeIndex(), false)
|
||||
})
|
||||
+3
-3
@@ -89,7 +89,7 @@ test('the UUID polyfill mints a v4 UUID from the unrestricted call', async () =>
|
||||
assert.equal(minted, '00010203-0405-4607-8809-0a0b0c0d0e0f')
|
||||
assert.notEqual(sandbox.crypto.randomUUID(), minted, 'each call reads fresh bytes')
|
||||
assert.equal(calls.draws, 2, 'one random draw per minted UUID')
|
||||
assert.deepEqual(calls.attributes, [['data-dsh-duo-shims', '1']], 'the script is stamped')
|
||||
assert.deepEqual(calls.attributes, [['data-dsh-trustworthy-shims', '1']], 'the script is stamped')
|
||||
})
|
||||
|
||||
test('the UUID polyfill leaves an existing implementation alone', async () => {
|
||||
@@ -148,12 +148,12 @@ test('nothing is emitted when every shim is off', async () => {
|
||||
test('the PWA block carries the manifest link and the app metadata', async () => {
|
||||
const { pwaMarkup, MANIFEST_PATH } = await import(SHIMS)
|
||||
const markup = pwaMarkup({ manifestPath: MANIFEST_PATH, includeManifestLink: true })
|
||||
assert.match(markup, /rel="manifest" href="\/dsh-disable-untrusted-origin\/manifest\.webmanifest"/)
|
||||
assert.match(markup, /rel="manifest" href="\/dsh-trustworthy\/manifest\.webmanifest"/)
|
||||
assert.match(markup, /apple-mobile-web-app-capable/)
|
||||
assert.match(markup, /apple-mobile-web-app-status-bar-style/)
|
||||
assert.match(markup, /name="theme-color"/)
|
||||
// Every tag is marked, so a probe can find the block in the served document.
|
||||
assert.equal((markup.match(/data-dsh-duo-pwa/g) ?? []).length, 4)
|
||||
assert.equal((markup.match(/data-dsh-trustworthy-pwa/g) ?? []).length, 4)
|
||||
assert.doesNotMatch(
|
||||
pwaMarkup({ manifestPath: MANIFEST_PATH, includeManifestLink: false }),
|
||||
/rel="manifest"/,
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* The `webRuntime` seam: the value it publishes, and the wiring that publishes
|
||||
* it only when the harness has not.
|
||||
*
|
||||
* The fence and apply suites cover the request identity; this one covers the
|
||||
* service releases from `0.2.1-alpha.2` on stopped providing, whose absence
|
||||
* leaves an injecting plugin `pending` and its routes unregistered — the 405 a
|
||||
* user sees in the sidebar's Files tab.
|
||||
*
|
||||
* node test/web-runtime.test.mjs
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
import { createServer } from 'node:http'
|
||||
import test from 'node:test'
|
||||
|
||||
import { Config, apply } from '../lib/index.js'
|
||||
import {
|
||||
WEB_RUNTIME_SERVICE,
|
||||
bindAuthority,
|
||||
connectionAuthorities,
|
||||
trustedAuthorities,
|
||||
webRuntimeShim,
|
||||
} from '../lib/web-runtime.js'
|
||||
|
||||
/** A config with every engagement off but the one under test. */
|
||||
function quietConfig(overrides = {}) {
|
||||
return {
|
||||
enabled: true,
|
||||
disableAuth: false,
|
||||
forceClientLoopback: false,
|
||||
grantPairing: false,
|
||||
provideWebRuntime: true,
|
||||
spoofSocketAddress: false,
|
||||
shimClipboard: false,
|
||||
shimRandomUuid: false,
|
||||
shimPwa: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A host context carrying only what `apply` touches, plus the real raw server
|
||||
* the interceptor is installed on.
|
||||
*
|
||||
* @param options - bind host, the authorities `connection` was given, and any
|
||||
* value already registered under the `webRuntime` name.
|
||||
*/
|
||||
async function mockHost({ host = '172.17.0.4', trustedHosts = [], webRuntime } = {}) {
|
||||
const provided = new Map()
|
||||
if (webRuntime !== undefined) provided.set(WEB_RUNTIME_SERVICE, webRuntime)
|
||||
const logs = []
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200)
|
||||
response.end('route handler')
|
||||
})
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
const ctx = {
|
||||
fiber: { uid: 1 },
|
||||
logger: {
|
||||
info(message) {
|
||||
logs.push(message)
|
||||
},
|
||||
warn(message) {
|
||||
logs.push(message)
|
||||
},
|
||||
},
|
||||
webServer: { port: server.address().port, host, server },
|
||||
connection: { trustedHosts },
|
||||
effect() {},
|
||||
inject(_services, callback) {
|
||||
callback(ctx)
|
||||
},
|
||||
on() {},
|
||||
// Cordis's `get` answers undefined for a name nobody provided, and its
|
||||
// `provide` throws on a second registration of one name.
|
||||
get(service) {
|
||||
return provided.get(service)
|
||||
},
|
||||
provide(service, value) {
|
||||
if (provided.has(service)) throw new Error(`service "${service}" has been registered`)
|
||||
provided.set(service, value)
|
||||
return () => provided.delete(service)
|
||||
},
|
||||
}
|
||||
return { ctx, server, provided, logs }
|
||||
}
|
||||
|
||||
test('declared authorities survive as strings and malformed entries do not', () => {
|
||||
assert.deepEqual(connectionAuthorities({ connection: { trustedHosts: [] } }), [])
|
||||
assert.deepEqual(
|
||||
connectionAuthorities({
|
||||
connection: { trustedHosts: ['ai.milesward.dev', '', 7, null, '192.168.1.49:3080'] },
|
||||
}),
|
||||
['ai.milesward.dev', '192.168.1.49:3080'],
|
||||
)
|
||||
// A harness that never built the list, or a host context without the service.
|
||||
assert.deepEqual(connectionAuthorities({}), [])
|
||||
assert.deepEqual(connectionAuthorities({ connection: {} }), [])
|
||||
})
|
||||
|
||||
test('the bind address is an authority only when it names one interface', () => {
|
||||
assert.equal(bindAuthority({ webServer: { host: '172.17.0.4' } }), '172.17.0.4')
|
||||
assert.equal(bindAuthority({ webServer: { host: '::1' } }), '::1')
|
||||
// A wildcard can be written as an authority but never means one.
|
||||
for (const host of ['0.0.0.0', '::', '::0', '*', '']) {
|
||||
assert.equal(bindAuthority({ webServer: { host } }), undefined, host)
|
||||
}
|
||||
assert.equal(bindAuthority({}), undefined)
|
||||
assert.equal(bindAuthority({ webServer: {} }), undefined)
|
||||
})
|
||||
|
||||
test('the snapshot is the declared authorities plus the bind address, deduplicated', () => {
|
||||
assert.deepEqual(
|
||||
trustedAuthorities({
|
||||
connection: { trustedHosts: ['ai.milesward.dev', '172.17.0.4'] },
|
||||
webServer: { host: '172.17.0.4' },
|
||||
}),
|
||||
['ai.milesward.dev', '172.17.0.4'],
|
||||
)
|
||||
// The wildcard bind adds nothing — alpha.1's resolveLanTrust agreed, and
|
||||
// alpha.2 refuses a wildcard `--host` outright.
|
||||
assert.deepEqual(
|
||||
trustedAuthorities({ connection: { trustedHosts: ['app.internal'] }, webServer: { host: '0.0.0.0' } }),
|
||||
['app.internal'],
|
||||
)
|
||||
})
|
||||
|
||||
test('the snapshot is read per request, not captured once', () => {
|
||||
const connection = { trustedHosts: ['ai.milesward.dev'] }
|
||||
const runtime = webRuntimeShim({ connection, webServer: { host: '10.0.0.7' } })
|
||||
assert.deepEqual(runtime.trustedHosts, ['ai.milesward.dev', '10.0.0.7'])
|
||||
assert.deepEqual(runtime.lanAddresses, [])
|
||||
|
||||
// A fence reads the list inside a request; a value frozen at mount time would
|
||||
// go on refusing a name the `/api` gateway had since admitted.
|
||||
connection.trustedHosts = ['ai.milesward.dev', 'app.internal']
|
||||
assert.deepEqual(runtime.trustedHosts, ['ai.milesward.dev', 'app.internal', '10.0.0.7'])
|
||||
})
|
||||
|
||||
test('the seam is on by default, and `apply` provides it', async (t) => {
|
||||
assert.equal(Config({}).provideWebRuntime, true)
|
||||
|
||||
const { ctx, server, provided, logs } = await mockHost({ trustedHosts: ['ai.milesward.dev'] })
|
||||
t.after(() => server.close())
|
||||
apply(ctx, quietConfig())
|
||||
|
||||
assert.deepEqual(provided.get(WEB_RUNTIME_SERVICE)?.trustedHosts, [
|
||||
'ai.milesward.dev',
|
||||
'172.17.0.4',
|
||||
])
|
||||
assert.ok(logs.some((line) => line.includes('provided the webRuntime service')), logs.join('\n'))
|
||||
})
|
||||
|
||||
test('an existing provider is left alone', async (t) => {
|
||||
const existing = { trustedHosts: ['someone-else.example'] }
|
||||
const { ctx, server, provided, logs } = await mockHost({ webRuntime: existing })
|
||||
t.after(() => server.close())
|
||||
apply(ctx, quietConfig())
|
||||
|
||||
assert.equal(provided.get(WEB_RUNTIME_SERVICE), existing)
|
||||
assert.ok(logs.some((line) => line.includes('already provided')), logs.join('\n'))
|
||||
})
|
||||
|
||||
test('the seam can be switched off, and a suspended plugin provides nothing', async (t) => {
|
||||
const off = await mockHost()
|
||||
t.after(() => off.server.close())
|
||||
apply(off.ctx, quietConfig({ provideWebRuntime: false }))
|
||||
assert.equal(off.provided.has(WEB_RUNTIME_SERVICE), false)
|
||||
|
||||
const suspended = await mockHost()
|
||||
t.after(() => suspended.server.close())
|
||||
apply(suspended.ctx, quietConfig({ enabled: false }))
|
||||
assert.equal(suspended.provided.has(WEB_RUNTIME_SERVICE), false)
|
||||
})
|
||||
Reference in new issue
Block a user