@johnhenry/browsermesh-objects 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +99 -2
- package/package.json +34 -4
- package/src/actions.mjs +42 -0
- package/src/duplex.mjs +81 -0
- package/src/index.mjs +14 -0
- package/src/open.mjs +68 -0
- package/src/serve.mjs +184 -0
- package/src/who.mjs +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Clawser Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,100 @@
|
|
|
1
|
-
#
|
|
1
|
+
# browsermesh-objects
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@johnhenry/browsermesh-objects)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
[wsh](https://github.com/johnhenry/wsh)'s remote-object layer (`@johnhenry/wsh/objects`: values, events,
|
|
7
|
+
handles, one-way callbacks) over a BrowserMesh protocol channel. A pod exposes named roots; another pod reaches
|
|
8
|
+
them by path (`await remote.app.counter.value`), under two authorisations: wsh's allow-lists (what the host
|
|
9
|
+
offers, by path) and the host's `PeerRegistry` grants for the channel's verified peer (what this peer may do,
|
|
10
|
+
per root and per action).
|
|
11
|
+
|
|
12
|
+
Peer dependencies: `@johnhenry/wsh` `>=0.48.0` (the first version with events, handles and callbacks) and
|
|
13
|
+
`@johnhenry/browsermesh-apps` `>=0.21.0` (the protocol channel and `createRootAuthorizer`).
|
|
14
|
+
Nothing is served unless `exposeObjectsOnMesh` is called, and nothing is allowed without a grant.
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
import { attachService, createMeshProtocolService, protocolScope } from '@johnhenry/browsermesh-apps'
|
|
18
|
+
import { exposeObjectsOnMesh, openObjectsOnMesh } from '@johnhenry/browsermesh-objects'
|
|
19
|
+
import { on, set } from '@johnhenry/wsh/objects'
|
|
20
|
+
|
|
21
|
+
// host
|
|
22
|
+
const host = attachService(node, undefined, createMeshProtocolService())
|
|
23
|
+
const objects = exposeObjectsOnMesh(host, {
|
|
24
|
+
roots: { app },
|
|
25
|
+
allow: { get: ['app.title', 'app.counter.**'], call: ['app.counter.inc'], on: ['app.bus@ready'] },
|
|
26
|
+
watch: node.registry.onAccessChange.bind(node.registry), // end a session when a grant is revoked or expires
|
|
27
|
+
})
|
|
28
|
+
node.registry.grantCapabilities(peerPodId, [protocolScope('objects'), 'objects:app:get', 'objects:app:call'])
|
|
29
|
+
|
|
30
|
+
// consumer
|
|
31
|
+
const { roots, close } = await openObjectsOnMesh(service, hostPodId)
|
|
32
|
+
await roots.app.title
|
|
33
|
+
await roots.app.counter.inc(1)
|
|
34
|
+
await on(roots.app.bus, 'ready', (data) => {}) // refused: the grant has no objects:app:on
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## API
|
|
38
|
+
|
|
39
|
+
- `exposeObjectsOnMesh(target, opts)` returns `{ protocol, authorizer, stop(), sessions(), stats() }`.
|
|
40
|
+
`target` is a mesh service (`attachService(node, undefined, createMeshProtocolService())`, or its `.api`) or a
|
|
41
|
+
channel factory `(accept) => stop` for any other protocol host (then `authorizer` is required).
|
|
42
|
+
Options: `roots`, `allow`, `handles`, `eventFields`, `limits` (wsh's, unchanged), `protocol` (default
|
|
43
|
+
`'objects'`: also the prefix of the scopes), `authorizer` (a `createRootAuthorizer`; default: the service's own,
|
|
44
|
+
backed by its registry), `watch` (`registry.onAccessChange.bind(registry)`), `versions`, `maxPendingSends`.
|
|
45
|
+
- `openObjectsOnMesh(channel | service, peer, opts)` returns `{ roots, channel, peer, close() }`. With a service
|
|
46
|
+
the channel is opened here (`protocol`, `timeoutMs`); a peer that does not serve it gives an
|
|
47
|
+
`ObjectsOnMeshError` (`reason: 'not-served'`, or `'unsupported'` for a version it cannot speak).
|
|
48
|
+
- The helpers that work on references (`get`, `set`, `call`, `on`, `off`, `snapshot`, `describe`, `use`, `release`)
|
|
49
|
+
are wsh's, from `@johnhenry/wsh/objects`.
|
|
50
|
+
- `actionFor(op)`, `OBJECT_ACTIONS`, `whoFor(podId)`, `duplexOverChannel(channel)` are exported for hosts that
|
|
51
|
+
build their own plumbing.
|
|
52
|
+
|
|
53
|
+
## Which grant each operation needs
|
|
54
|
+
|
|
55
|
+
| Operation | Action | Scope |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| read a value, `describe`, `snapshot` | `get` | `objects:ROOT:get` |
|
|
58
|
+
| `call`, `construct`, a call that passes callbacks (they are arguments of the call) | `call` | `objects:ROOT:call` |
|
|
59
|
+
| `set` | `set` | `objects:ROOT:set` |
|
|
60
|
+
| subscribe to an event source | `on` | `objects:ROOT:on` |
|
|
61
|
+
| an operation through a handle | the action of the operation, on the path that produced the handle | as above |
|
|
62
|
+
| anything this table does not name | refused | |
|
|
63
|
+
|
|
64
|
+
Opening the protocol needs `protocol:objects:open`. The scopes use the registry's wildcards (`objects:*:get`,
|
|
65
|
+
`objects:app:*`) and expiry. A peer is told of the roots it can use on some action, no others. `on` is not `get`:
|
|
66
|
+
a peer granted only `objects:app:get` is refused a subscription.
|
|
67
|
+
|
|
68
|
+
## Identity
|
|
69
|
+
|
|
70
|
+
The caller is the channel's verified peer: a pod id, the key the session is bound to, never a field of a message.
|
|
71
|
+
It is handed to the layer in `who.podId`; `who.username` and `who.fingerprint` stay `null` (a pod id is not a wsh
|
|
72
|
+
key fingerprint, and the layer is never told it is). All decisions are made from `who.podId` (see `src/who.mjs`).
|
|
73
|
+
|
|
74
|
+
## Revocation and bounds
|
|
75
|
+
|
|
76
|
+
- A request is judged when it arrives: revoking or expiring a grant refuses the very next one.
|
|
77
|
+
- What a peer holds open is judged again: an event subscription needs `on` and a callback needs `call`, at every
|
|
78
|
+
delivery; a peer that has lost one has the session closed and the listener taken out of the host's source. With
|
|
79
|
+
`watch` this happens when the registry announces the change; without it, at the next delivery.
|
|
80
|
+
- Losing `protocol:objects:open` closes the channel through the protocol host.
|
|
81
|
+
- Events and callbacks leave through the mesh channel's credit. A reader that stops reading makes wsh's bounded
|
|
82
|
+
queue (`maxQueuedEvents`) fill and then drop events, counted: the next event delivered says how many were lost
|
|
83
|
+
before it (`info.dropped`). Responses are bounded too: a peer that keeps asking and never reads is cut off once
|
|
84
|
+
`maxPendingSends` (default 256) writes wait for credit (`stats().closedSlow`).
|
|
85
|
+
- A result larger than the channel's `maxMessageBytes` (or wsh's `maxValueBytes`) is refused by name, not sent.
|
|
86
|
+
- Handles: wsh's table (`maxHandles`, default 64) is per channel, refused when full, released on
|
|
87
|
+
`release(handle)` and when the session ends.
|
|
88
|
+
|
|
89
|
+
## Older peers and versions
|
|
90
|
+
|
|
91
|
+
Nothing new is put on the wire: the layer's messages travel as raw messages of the protocol `objects` (the name
|
|
92
|
+
is `protocol`). A peer that has not got the protocol, or has no protocol support at all, answers the open with
|
|
93
|
+
-32601; nothing else is sent to it. The layer's own feature list (`events`, `callbacks`, `handles`) is how a client
|
|
94
|
+
knows what a host supports, as in wsh.
|
|
95
|
+
|
|
96
|
+
## Not a sandbox
|
|
97
|
+
|
|
98
|
+
An allow-list of paths means what it says only because nothing but cloneable values cross. A `call` runs the host
|
|
99
|
+
application's function with the caller's arguments, with the application's authority. List the functions you would
|
|
100
|
+
hand to that peer; see wsh's README ("Threat model of `values` mode").
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-objects",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "wsh's remote-object layer (values, events, handles, callbacks) over a BrowserMesh protocol channel, authorised per root and per action for the channel's verified peer",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"LICENSE",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"keywords": [
|
|
16
|
+
"wsh",
|
|
17
|
+
"remote-objects",
|
|
18
|
+
"capabilities",
|
|
19
|
+
"mesh",
|
|
20
|
+
"browser"
|
|
21
|
+
],
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/johnhenry/browsermesh",
|
|
26
|
+
"directory": "packages/browsermesh-objects"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://opensource.johnhenry.me/browsermesh/",
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=26.0.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@johnhenry/browsermesh-apps": ">=0.21.0 <1.0.0",
|
|
34
|
+
"@johnhenry/wsh": ">=0.48.0 <1.0.0"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/actions.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* actions.mjs -- which action of the registry an object operation needs.
|
|
3
|
+
*
|
|
4
|
+
* Every operation of wsh's object layer is judged by its OWN action, as a
|
|
5
|
+
* scope `objects:<root>:<action>` through the registry (`createRootAuthorizer`):
|
|
6
|
+
*
|
|
7
|
+
* get, describe, snapshot -> get
|
|
8
|
+
* call, construct -> call (a call that carries callbacks is still one call:
|
|
9
|
+
* the callbacks are arguments of it)
|
|
10
|
+
* set -> set
|
|
11
|
+
* on (a subscription) -> on
|
|
12
|
+
*
|
|
13
|
+
* An operation through a handle is judged by the layer as the producing path
|
|
14
|
+
* extended by the member, with the kind of the operation that is performed
|
|
15
|
+
* through it, so a handle never turns a `get` into a `call`: a peer granted
|
|
16
|
+
* `objects:app:get` can read through a handle and cannot call through it.
|
|
17
|
+
*
|
|
18
|
+
* Anything this table does not name is NOT allowed. There is no fallback to
|
|
19
|
+
* `get`: an operation a newer layer adds is refused until it is named here.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** The actions of the object layer, in the order of the scopes a grant lists. */
|
|
23
|
+
export const OBJECT_ACTIONS = Object.freeze(['get', 'call', 'set', 'on'])
|
|
24
|
+
|
|
25
|
+
const ACTION_OF_KIND = new Map([
|
|
26
|
+
['get', 'get'],
|
|
27
|
+
['describe', 'get'],
|
|
28
|
+
['snapshot', 'get'],
|
|
29
|
+
['call', 'call'],
|
|
30
|
+
['construct', 'call'],
|
|
31
|
+
['set', 'set'],
|
|
32
|
+
['on', 'on'],
|
|
33
|
+
])
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {{ kind?: string }} op - an operation as the layer hands it to `authorize`
|
|
37
|
+
* @returns {'get'|'call'|'set'|'on'|null} null when the kind is not one this adapter knows (and so is refused)
|
|
38
|
+
*/
|
|
39
|
+
export function actionFor(op) {
|
|
40
|
+
const kind = op?.kind
|
|
41
|
+
return typeof kind === 'string' ? ACTION_OF_KIND.get(kind) ?? null : null
|
|
42
|
+
}
|
package/src/duplex.mjs
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* duplex.mjs -- a mesh protocol channel as the object layer's peer, with the
|
|
3
|
+
* backpressure the layer expects.
|
|
4
|
+
*
|
|
5
|
+
* wsh's `createDuplexPeer({ send })` takes a synchronous `send` and its
|
|
6
|
+
* `notify` returns nothing. The layer's event and callback pump awaits what
|
|
7
|
+
* `notify` returns ("the write waits for the channel's credit") and keeps at
|
|
8
|
+
* most `maxQueuedEvents` waiting, dropping and counting the rest. A bare
|
|
9
|
+
* duplex peer returns nothing, so the pump would never wait: every event
|
|
10
|
+
* would go straight into the mesh channel's send queue, which holds a message
|
|
11
|
+
* until credit is granted and is not bounded by anything of wsh's. This
|
|
12
|
+
* module makes `notify` return the channel's own send promise, so a reader
|
|
13
|
+
* that stops reading (no credit) makes the pump wait, its bounded queue fill,
|
|
14
|
+
* and events be dropped and counted by the layer.
|
|
15
|
+
*
|
|
16
|
+
* Responses, progress and cancel frames are not events: each answers a
|
|
17
|
+
* request the far side made. They are sent at once, but the number of sends
|
|
18
|
+
* not yet accepted by the channel is bounded (`maxPendingSends`): a peer that
|
|
19
|
+
* keeps asking and never reads is cut off (the objects channel is closed,
|
|
20
|
+
* `stats().closedSlow` counts it) instead of growing this side's memory.
|
|
21
|
+
*/
|
|
22
|
+
import { createDuplexPeer } from '@johnhenry/wsh/objects'
|
|
23
|
+
|
|
24
|
+
/** Sends the channel has not accepted yet, at most, before the peer is cut off. */
|
|
25
|
+
export const DEFAULT_MAX_PENDING_SENDS = 256
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} channel - a protocol channel (`send`, `onMessage`, `onClose`, `maxMessageBytes`, `close`)
|
|
29
|
+
* @param {object} [opts]
|
|
30
|
+
* @param {number} [opts.maxPendingSends=256]
|
|
31
|
+
* @returns the layer's peer (`request`, `notify`, `onRequest`, `onNotification`, `onClose`, `maxMessageBytes`, `close`, `closed`) plus `stats()`
|
|
32
|
+
*/
|
|
33
|
+
export function duplexOverChannel(channel, { maxPendingSends = DEFAULT_MAX_PENDING_SENDS } = {}) {
|
|
34
|
+
if (!Number.isSafeInteger(maxPendingSends) || maxPendingSends < 1) throw new TypeError('maxPendingSends must be a positive integer')
|
|
35
|
+
const stats = { pendingSends: 0, sendFailures: 0, closedSlow: 0 }
|
|
36
|
+
let lastSend // the channel's promise for the message `send` was just given
|
|
37
|
+
|
|
38
|
+
const duplex = createDuplexPeer({
|
|
39
|
+
maxMessageBytes: channel.maxMessageBytes,
|
|
40
|
+
send(message) {
|
|
41
|
+
lastSend = undefined
|
|
42
|
+
if (stats.pendingSends >= maxPendingSends) {
|
|
43
|
+
stats.closedSlow += 1
|
|
44
|
+
duplex.close('the far side is not reading')
|
|
45
|
+
try { channel.close('the far side is not reading') } catch { /* already closed */ }
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
stats.pendingSends += 1
|
|
49
|
+
lastSend = channel.send(message).then(
|
|
50
|
+
() => { stats.pendingSends -= 1 },
|
|
51
|
+
() => { stats.pendingSends -= 1; stats.sendFailures += 1; duplex.close('send failed') },
|
|
52
|
+
)
|
|
53
|
+
},
|
|
54
|
+
})
|
|
55
|
+
channel.onMessage((message) => { duplex.receive(message) })
|
|
56
|
+
channel.onClose(() => duplex.close('channel closed'))
|
|
57
|
+
|
|
58
|
+
const peer = {
|
|
59
|
+
get maxMessageBytes() { return duplex.maxMessageBytes },
|
|
60
|
+
get closed() { return duplex.closed },
|
|
61
|
+
get onClose() { return duplex.onClose },
|
|
62
|
+
set onClose(fn) { duplex.onClose = fn },
|
|
63
|
+
onRequest: (method, handler) => duplex.onRequest(method, handler),
|
|
64
|
+
onNotification: (method, handler) => duplex.onNotification(method, handler),
|
|
65
|
+
request: (method, params, options) => duplex.request(method, params, options),
|
|
66
|
+
/** Resolves when the channel has taken the message (its credit allowed it); the layer's pump waits on it. */
|
|
67
|
+
notify(method, params) {
|
|
68
|
+
lastSend = undefined
|
|
69
|
+
duplex.notify(method, params)
|
|
70
|
+
const sent = lastSend
|
|
71
|
+
lastSend = undefined
|
|
72
|
+
return sent
|
|
73
|
+
},
|
|
74
|
+
close(reason) {
|
|
75
|
+
duplex.close(reason)
|
|
76
|
+
try { channel.close(reason) } catch { /* already closed */ }
|
|
77
|
+
},
|
|
78
|
+
stats: () => ({ ...stats }),
|
|
79
|
+
}
|
|
80
|
+
return peer
|
|
81
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @johnhenry/browsermesh-objects -- wsh's remote-object layer over a mesh protocol channel.
|
|
3
|
+
*
|
|
4
|
+
* serve: exposeObjectsOnMesh(service | channelFactory, { roots, allow, ... })
|
|
5
|
+
* consume: openObjectsOnMesh(channel | service, peer, opts) -> { roots, close }
|
|
6
|
+
*
|
|
7
|
+
* The wsh helpers that work on the references (`get`, `set`, `call`, `on`, `snapshot`, `use`, `release`)
|
|
8
|
+
* come from `@johnhenry/wsh/objects` and are not re-exported.
|
|
9
|
+
*/
|
|
10
|
+
export { exposeObjectsOnMesh } from './serve.mjs'
|
|
11
|
+
export { openObjectsOnMesh, ObjectsOnMeshError } from './open.mjs'
|
|
12
|
+
export { OBJECT_ACTIONS, actionFor } from './actions.mjs'
|
|
13
|
+
export { whoFor, podIdOf } from './who.mjs'
|
|
14
|
+
export { duplexOverChannel, DEFAULT_MAX_PENDING_SENDS } from './duplex.mjs'
|
package/src/open.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* open.mjs -- consume a peer's objects: the roots as lazy references
|
|
3
|
+
* (`await roots.app.counter.value`), with wsh's `get`, `set`, `call`, `on`,
|
|
4
|
+
* `snapshot`, `use` and `release` working on them unchanged.
|
|
5
|
+
*/
|
|
6
|
+
import { createObjectsClient } from '@johnhenry/wsh/objects'
|
|
7
|
+
import { assertProtocolChannel } from '@johnhenry/browsermesh-apps/protocol-channel'
|
|
8
|
+
import { ChannelErrorCode } from '@johnhenry/browsermesh-apps/mesh-channel'
|
|
9
|
+
import { duplexOverChannel } from './duplex.mjs'
|
|
10
|
+
|
|
11
|
+
/** A peer that does not serve objects at all, or serves a version this side cannot speak. `reason` names which. */
|
|
12
|
+
export class ObjectsOnMeshError extends Error {
|
|
13
|
+
constructor(reason, message, cause) {
|
|
14
|
+
super(message, cause ? { cause } : undefined)
|
|
15
|
+
this.name = 'ObjectsOnMeshError'
|
|
16
|
+
this.reason = reason
|
|
17
|
+
this.code = cause?.code
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function mapOpenError(error, protocol) {
|
|
22
|
+
if (error?.code === ChannelErrorCode.METHOD_NOT_FOUND) {
|
|
23
|
+
return new ObjectsOnMeshError('not-served', `the peer does not serve the "${protocol}" protocol (an older peer, or objects are not exposed there)`, error)
|
|
24
|
+
}
|
|
25
|
+
if (error?.code === ChannelErrorCode.UNSUPPORTED) {
|
|
26
|
+
return new ObjectsOnMeshError('unsupported', `the peer cannot speak this version of the "${protocol}" protocol`, error)
|
|
27
|
+
}
|
|
28
|
+
return error
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {object} target - an open protocol channel, or a mesh service (`attachService(..., createMeshProtocolService())` or its `.api`)
|
|
33
|
+
* @param {string|object} [peer] - the peer's pod id when `target` is a service (the channel is opened here); options may be given here instead for a channel
|
|
34
|
+
* @param {object} [opts]
|
|
35
|
+
* @param {string} [opts.protocol='objects'] - used when opening through a service
|
|
36
|
+
* @param {number} [opts.timeoutMs] - for opening, and for the layer's requests
|
|
37
|
+
* @param {Function} [opts.onCallbackError] - a callback of ours threw (wsh's option)
|
|
38
|
+
* @param {Function} [opts.onCallbackDropped] - the host dropped calls of a callback (wsh's option)
|
|
39
|
+
* @param {number} [opts.maxPendingSends] - see duplex.mjs
|
|
40
|
+
* @returns {Promise<{ roots: object, channel: object, peer: object, close(): void }>}
|
|
41
|
+
* `roots` are the host's roots as lazy references; `peer.stats()` counts sends, failures and cut-offs.
|
|
42
|
+
*/
|
|
43
|
+
export async function openObjectsOnMesh(target, peer, opts) {
|
|
44
|
+
if (peer !== null && typeof peer === 'object') { opts = peer; peer = undefined }
|
|
45
|
+
const { protocol = 'objects', timeoutMs, onCallbackError, onCallbackDropped, maxPendingSends } = opts ?? {}
|
|
46
|
+
let channel
|
|
47
|
+
let duplex
|
|
48
|
+
const attachDuplex = (ch) => { duplex = duplexOverChannel(ch, { maxPendingSends }) }
|
|
49
|
+
const api = target && typeof target === 'object' ? (target.api ?? target) : null
|
|
50
|
+
if (typeof api?.openProtocol === 'function') {
|
|
51
|
+
if (typeof peer !== 'string' || !peer) throw new TypeError('openObjectsOnMesh: the peer to open the protocol on is required with a service')
|
|
52
|
+
try {
|
|
53
|
+
// The duplex is built in `setup`, before the open request leaves, so nothing arrives before it listens.
|
|
54
|
+
channel = await api.openProtocol(peer, protocol, { ...(timeoutMs === undefined ? {} : { timeoutMs }), setup: attachDuplex })
|
|
55
|
+
} catch (e) { throw mapOpenError(e, protocol) }
|
|
56
|
+
} else {
|
|
57
|
+
assertProtocolChannel(target)
|
|
58
|
+
channel = target
|
|
59
|
+
attachDuplex(channel)
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const roots = await createObjectsClient(duplex, { ...(timeoutMs === undefined ? {} : { timeoutMs }), onCallbackError, onCallbackDropped })
|
|
63
|
+
return { roots, channel, peer: duplex, close: () => duplex.close('closed by the opener') }
|
|
64
|
+
} catch (e) {
|
|
65
|
+
duplex.close('could not open the objects')
|
|
66
|
+
throw e
|
|
67
|
+
}
|
|
68
|
+
}
|
package/src/serve.mjs
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serve.mjs -- serve wsh's remote-object layer to mesh peers.
|
|
3
|
+
*
|
|
4
|
+
* const objects = exposeObjectsOnMesh(service, {
|
|
5
|
+
* roots: { app }, // the named roots: all that is reachable
|
|
6
|
+
* allow: { get: ['app.title'], call: ['app.counter.inc'], on: ['app.bus@ready'] },
|
|
7
|
+
* })
|
|
8
|
+
* registry.grantCapabilities(peerPodId, ['protocol:objects:open', 'objects:app:get'])
|
|
9
|
+
*
|
|
10
|
+
* Two authorisations apply to every operation, and both must say yes: wsh's
|
|
11
|
+
* allow-lists (what the HOST offers, by path) and then the registry grant of
|
|
12
|
+
* the channel's verified peer (what THIS PEER may do on that root), each
|
|
13
|
+
* operation by its own action (see actions.mjs). Default deny at both.
|
|
14
|
+
*
|
|
15
|
+
* Revocation: a request is judged when it arrives, so a revoked or expired
|
|
16
|
+
* grant refuses the very next one. What a peer holds OPEN is judged again too:
|
|
17
|
+
* an event subscription needs `on` and a callback needs `call` (it is an
|
|
18
|
+
* argument of a call) at every delivery and whenever `watch` reports an access
|
|
19
|
+
* change for that peer; a peer that has lost one of them has the objects
|
|
20
|
+
* channel closed. Losing the protocol scope itself closes the channel through
|
|
21
|
+
* the protocol host, as for any protocol.
|
|
22
|
+
*/
|
|
23
|
+
import { createObjectsServer } from '@johnhenry/wsh/objects'
|
|
24
|
+
import { OBJECT_ACTIONS, actionFor } from './actions.mjs'
|
|
25
|
+
import { whoFor, podIdOf } from './who.mjs'
|
|
26
|
+
import { duplexOverChannel } from './duplex.mjs'
|
|
27
|
+
|
|
28
|
+
const defaultRandom = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n))
|
|
29
|
+
const defaultTimers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {object|Function} target - a mesh service (`attachService(node, undefined, createMeshProtocolService())`, or its `.api`):
|
|
33
|
+
* the objects are served with its `serveProtocol`, and its `rootAuthorizer` is the default authorizer.
|
|
34
|
+
* Or a channel factory `(accept) => stop`: called once with `accept(channel)`, to register on any protocol host
|
|
35
|
+
* (`(accept) => host.serveProtocol('objects', accept)`); then `authorizer` is required.
|
|
36
|
+
* @param {object} opts
|
|
37
|
+
* @param {Record<string, object>} opts.roots - the named roots
|
|
38
|
+
* @param {object} [opts.allow] - wsh's allow-lists by operation (`get`, `call`, `set`, `on`); nothing is allowed by default
|
|
39
|
+
* @param {Record<string, object>} [opts.handles] - roots that opt in to handles (wsh's option, unchanged)
|
|
40
|
+
* @param {Record<string, string[]>} [opts.eventFields] - event fields a subscriber may ask for, by event type (wsh's option)
|
|
41
|
+
* @param {object} [opts.limits] - wsh's bounds (`maxSubscriptions`, `maxQueuedEvents`, `maxHandles`, ...)
|
|
42
|
+
* @param {string} [opts.protocol='objects'] - the protocol name; also the prefix of the scopes (`<protocol>:<root>:<action>`)
|
|
43
|
+
* @param {{ can: Function, scope?: Function }} [opts.authorizer] - a `createRootAuthorizer` result; default: the service's own, backed by its registry
|
|
44
|
+
* @param {(listener: (event: { pubKey: string }) => void) => (() => void)} [opts.watch] - `registry.onAccessChange.bind(registry)`:
|
|
45
|
+
* with it a revoked or expired grant is noticed at once, not at the next delivery
|
|
46
|
+
* @param {number[]} [opts.versions] - protocol versions to serve (default [1])
|
|
47
|
+
* @param {number} [opts.maxPendingSends] - see duplex.mjs
|
|
48
|
+
* @returns {{ protocol: string, authorizer: object, stop(): void, sessions(): number, stats(): object }}
|
|
49
|
+
*/
|
|
50
|
+
export function exposeObjectsOnMesh(target, opts = {}) {
|
|
51
|
+
const {
|
|
52
|
+
roots, allow = {}, handles, eventFields, limits, protocol = 'objects', watch, versions, maxPendingSends,
|
|
53
|
+
random = defaultRandom, timers = defaultTimers,
|
|
54
|
+
} = opts
|
|
55
|
+
if (!roots || typeof roots !== 'object' || !Object.keys(roots).length) throw new TypeError('exposeObjectsOnMesh: roots must name at least one root')
|
|
56
|
+
const api = target && typeof target === 'object' ? (target.api ?? target) : null
|
|
57
|
+
if (typeof target !== 'function' && typeof api?.serveProtocol !== 'function') {
|
|
58
|
+
throw new TypeError('exposeObjectsOnMesh: the first argument is a mesh service (with serveProtocol) or a channel factory function')
|
|
59
|
+
}
|
|
60
|
+
const authorizer = opts.authorizer ?? (typeof api?.rootAuthorizer === 'function' ? api.rootAuthorizer(protocol, { actions: [...OBJECT_ACTIONS] }) : undefined)
|
|
61
|
+
if (!authorizer || typeof authorizer.can !== 'function') throw new TypeError('exposeObjectsOnMesh: an authorizer is required (createRootAuthorizer), nothing is served without one')
|
|
62
|
+
if (watch !== undefined && typeof watch !== 'function') throw new TypeError('exposeObjectsOnMesh: watch must be a function')
|
|
63
|
+
// A root name that could carry scope syntax is refused here, not at the first request.
|
|
64
|
+
for (const root of Object.keys(roots)) authorizer.scope?.(root, 'get')
|
|
65
|
+
|
|
66
|
+
const can = (podId, root, action) => {
|
|
67
|
+
if (!podId || !action) return false
|
|
68
|
+
try { return authorizer.can(podId, root, action) === true } catch { return false }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const server = createObjectsServer({
|
|
72
|
+
roots,
|
|
73
|
+
mode: 'values',
|
|
74
|
+
allow,
|
|
75
|
+
handles,
|
|
76
|
+
eventFields,
|
|
77
|
+
limits,
|
|
78
|
+
random,
|
|
79
|
+
timers,
|
|
80
|
+
// Asked for every operation the allow-lists let through: the registry grant of the verified peer, for this operation's own action.
|
|
81
|
+
authorize: (who, op) => can(podIdOf(who), op.root, actionFor(op)),
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
const sessions = new Set()
|
|
85
|
+
const counters = { sessions: 0, revoked: 0, droppedNotifications: 0, closedSlow: 0, sendFailures: 0 }
|
|
86
|
+
|
|
87
|
+
function accept(channel) {
|
|
88
|
+
const podId = channel.peer
|
|
89
|
+
const peer = duplexOverChannel(channel, { maxPendingSends })
|
|
90
|
+
const subs = new Map() // subscription id -> root
|
|
91
|
+
const callbacks = new Map() // callback id -> root
|
|
92
|
+
const session = { channel, peer }
|
|
93
|
+
sessions.add(session)
|
|
94
|
+
counters.sessions += 1
|
|
95
|
+
|
|
96
|
+
const revoke = () => {
|
|
97
|
+
counters.revoked += 1
|
|
98
|
+
peer.close('authorization revoked')
|
|
99
|
+
}
|
|
100
|
+
/** An open subscription needs `on` on its root, an open callback `call`: asked again, now. */
|
|
101
|
+
const stillHeld = () => {
|
|
102
|
+
for (const root of subs.values()) if (!can(podId, root, 'on')) return false
|
|
103
|
+
for (const root of callbacks.values()) if (!can(podId, root, 'call')) return false
|
|
104
|
+
return true
|
|
105
|
+
}
|
|
106
|
+
const offWatch = watch ? watch((event) => { if (event?.pubKey === podId && !stillHeld()) revoke() }) : null
|
|
107
|
+
|
|
108
|
+
const guarded = {
|
|
109
|
+
get maxMessageBytes() { return peer.maxMessageBytes },
|
|
110
|
+
get onClose() { return peer.onClose },
|
|
111
|
+
set onClose(fn) { peer.onClose = fn },
|
|
112
|
+
onRequest(method, handler) {
|
|
113
|
+
peer.onRequest(method, async (params, ctx) => {
|
|
114
|
+
const wired = trackOpen(method, params)
|
|
115
|
+
try {
|
|
116
|
+
const result = await handler(params, ctx)
|
|
117
|
+
// A peer is told of the roots it can use on some action, no others.
|
|
118
|
+
return method === 'roots' && Array.isArray(result?.roots)
|
|
119
|
+
? { ...result, roots: result.roots.filter((root) => OBJECT_ACTIONS.some((action) => can(podId, root, action))) }
|
|
120
|
+
: result
|
|
121
|
+
} catch (e) { wired?.undo(); throw e }
|
|
122
|
+
})
|
|
123
|
+
},
|
|
124
|
+
/** Events and callbacks leave through the channel's credit, and only while the grant that allowed them still holds. */
|
|
125
|
+
notify(method, params) {
|
|
126
|
+
if (method === 'event' || method === 'callback') {
|
|
127
|
+
const owner = method === 'event' ? subs : callbacks
|
|
128
|
+
const root = owner.get(params?.id)
|
|
129
|
+
if (root === undefined) { counters.droppedNotifications += 1; return undefined }
|
|
130
|
+
if (!can(podId, root, method === 'event' ? 'on' : 'call')) { revoke(); return undefined }
|
|
131
|
+
}
|
|
132
|
+
return peer.notify(method, params)
|
|
133
|
+
},
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Remember which root an open subscription or callback belongs to (the layer's `subscribe` and `resolve` requests name it). */
|
|
137
|
+
function trackOpen(method, params) {
|
|
138
|
+
if (method === 'subscribe' && Number.isSafeInteger(params?.id) && typeof params.root === 'string') {
|
|
139
|
+
subs.set(params.id, params.root)
|
|
140
|
+
return { undo: () => subs.delete(params.id) }
|
|
141
|
+
}
|
|
142
|
+
if (method === 'unsubscribe') { subs.delete(params?.id); return null }
|
|
143
|
+
if (method === 'releaseCallback') { callbacks.delete(params?.id); return null }
|
|
144
|
+
if (method === 'resolve' && typeof params?.root === 'string' && Array.isArray(params.ops)) {
|
|
145
|
+
const added = []
|
|
146
|
+
for (const op of params.ops) {
|
|
147
|
+
for (const entry of Array.isArray(op?.callbacks) ? op.callbacks : []) {
|
|
148
|
+
const id = Array.isArray(entry) ? entry[1] : undefined
|
|
149
|
+
if (Number.isSafeInteger(id) && !callbacks.has(id)) { callbacks.set(id, params.root); added.push(id) }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return added.length ? { undo: () => { for (const id of added) callbacks.delete(id) } } : null
|
|
153
|
+
}
|
|
154
|
+
return null
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
server.attach(guarded, { who: whoFor(podId) })
|
|
158
|
+
const prior = peer.onClose
|
|
159
|
+
peer.onClose = (reason) => {
|
|
160
|
+
sessions.delete(session)
|
|
161
|
+
offWatch?.()
|
|
162
|
+
const s = peer.stats()
|
|
163
|
+
counters.closedSlow += s.closedSlow
|
|
164
|
+
counters.sendFailures += s.sendFailures
|
|
165
|
+
subs.clear()
|
|
166
|
+
callbacks.clear()
|
|
167
|
+
try { prior?.(reason) } catch { /* the layer's own cleanup must not stop ours */ }
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const stopServing = typeof target === 'function' ? target(accept) : api.serveProtocol(protocol, accept, versions ? { versions } : undefined)
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
protocol,
|
|
175
|
+
authorizer,
|
|
176
|
+
/** Stop serving and end every session. */
|
|
177
|
+
stop() {
|
|
178
|
+
if (typeof stopServing === 'function') stopServing()
|
|
179
|
+
for (const { peer } of [...sessions]) peer.close('objects host stopped')
|
|
180
|
+
},
|
|
181
|
+
sessions: () => sessions.size,
|
|
182
|
+
stats: () => ({ ...counters, openSessions: sessions.size, pendingSends: [...sessions].reduce((n, s) => n + s.peer.stats().pendingSends, 0) }),
|
|
183
|
+
}
|
|
184
|
+
}
|
package/src/who.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* who.mjs -- the caller identity handed to wsh's object layer: the one place
|
|
3
|
+
* where a mesh peer is turned into the layer's notion of "who".
|
|
4
|
+
*
|
|
5
|
+
* Over a mesh channel the caller is the channel's VERIFIED peer: a pod id, the
|
|
6
|
+
* key the session is bound to, never a field of a message. wsh's layer asks
|
|
7
|
+
* for `who: { username, fingerprint }` (the shape of a wsh key login). A pod id
|
|
8
|
+
* is not a wsh fingerprint, and putting one in `fingerprint` would be a lie
|
|
9
|
+
* that other code may rely on (a log line, a revocation by fingerprint), so
|
|
10
|
+
* this adapter does not: `username` and `fingerprint` stay null and the pod id
|
|
11
|
+
* travels in `podId`, the neutral slot (@johnhenry/wsh >= 0.49 names it; on
|
|
12
|
+
* 0.48 the layer passes the object it was given through to `authorize`
|
|
13
|
+
* untouched, which is how this adapter reads it back).
|
|
14
|
+
*
|
|
15
|
+
* Every decision of this package is made from `who.podId` and from nothing
|
|
16
|
+
* else; the layer's own `fingerprint` is never consulted.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** @param {string} podId the channel's verified peer @returns {{ username: null, fingerprint: null, podId: string }} */
|
|
20
|
+
export function whoFor(podId) {
|
|
21
|
+
if (typeof podId !== 'string' || !podId) throw new TypeError('whoFor: the channel has no verified peer')
|
|
22
|
+
return Object.freeze({ username: null, fingerprint: null, podId })
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The pod id a `who` names, or null when it names none (then nothing is allowed). */
|
|
26
|
+
export function podIdOf(who) {
|
|
27
|
+
const id = who?.podId
|
|
28
|
+
return typeof id === 'string' && id ? id : null
|
|
29
|
+
}
|