@yaks/tunnel 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +319 -2
  3. package/_dist/cloudflare.d.ts +38 -0
  4. package/_dist/cloudflare.d.ts.map +1 -0
  5. package/_dist/effects.d.ts +37 -0
  6. package/_dist/effects.d.ts.map +1 -0
  7. package/_dist/filter.d.ts +68 -0
  8. package/_dist/filter.d.ts.map +1 -0
  9. package/_dist/gateway.d.ts +14 -0
  10. package/_dist/gateway.d.ts.map +1 -0
  11. package/_dist/hosted.d.ts +101 -0
  12. package/_dist/hosted.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +5 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/routes.d.ts +31 -0
  16. package/_dist/routes.d.ts.map +1 -0
  17. package/_dist/service.d.ts +24 -0
  18. package/_dist/service.d.ts.map +1 -0
  19. package/_dist/vocab.d.ts +6 -0
  20. package/_dist/vocab.d.ts.map +1 -0
  21. package/cloudflare.js +170 -0
  22. package/cloudflare.js.map +1 -0
  23. package/cloudflare.ts +233 -0
  24. package/deno.json +1 -0
  25. package/effects.js +103 -0
  26. package/effects.js.map +1 -0
  27. package/effects.ts +143 -0
  28. package/filter.js +95 -0
  29. package/filter.js.map +1 -0
  30. package/filter.ts +128 -0
  31. package/gateway.js +37 -0
  32. package/gateway.js.map +1 -0
  33. package/gateway.ts +46 -0
  34. package/hosted.js +345 -0
  35. package/hosted.js.map +1 -0
  36. package/hosted.ts +496 -0
  37. package/mod.js +15 -0
  38. package/mod.js.map +1 -0
  39. package/mod.ts +35 -0
  40. package/package.json +45 -4
  41. package/routes.js +94 -0
  42. package/routes.js.map +1 -0
  43. package/routes.ts +144 -0
  44. package/service.js +119 -0
  45. package/service.js.map +1 -0
  46. package/service.ts +164 -0
  47. package/vocab.js +16 -0
  48. package/vocab.js.map +1 -0
  49. package/vocab.json +62 -0
  50. package/vocab.ts +17 -0
package/filter.ts ADDED
@@ -0,0 +1,128 @@
1
+ // The tunnel's machine end: the filter the machine's own server puts in front
2
+ // of its routes (./routes.ts). A request the gateway marked (./gateway.ts)
3
+ // passes only at the paths the machine's owner opened to the tunnel, and the
4
+ // rest are refused before any route sees them. Where an opened path lists and
5
+ // runs tools, a marked request is offered only the ones the owner named
6
+ // (`offered`). An unmarked request did not come through the tunnel, so
7
+ // everything the machine already answered locally it still does.
8
+ //
9
+ // The platform says who is asking (./gateway.ts `CALLER`), and the owner can
10
+ // open more to one kind of caller than to the rest (`Callers`): a path every
11
+ // app in the space may reach, and beside it a path only the owner's assistant
12
+ // may. A request saying no word, or one the owner named nothing for, gets what
13
+ // every request through the tunnel does.
14
+ import { CALLER, HEADER } from './gateway.js'
15
+
16
+ /** What a machine's owner opens to requests through the tunnel: the paths
17
+ * answered, the tools offered where a path runs them, and the persona written
18
+ * as. */
19
+ export type Opened = {
20
+ /** the paths answered, as URLPattern pathnames; none opens nothing */
21
+ routes?: string[]
22
+ /** the tools offered at a path that runs them, by name; none offers
23
+ * nothing */
24
+ tools?: string[]
25
+ /** the persona written as, by eid, number or name */
26
+ persona?: string
27
+ /** the platform's id for the person the machine's own config names as its
28
+ * `person`: a request the platform says is that person's own act
29
+ * (./gateway.ts `BY`) writes as them. Without one no request does */
30
+ owner?: string
31
+ }
32
+
33
+ /** What a machine's owner opens to one kind of caller on top of what every
34
+ * request through the tunnel gets, by the platform's word for the caller. */
35
+ export type Callers = Record<string, Opened>
36
+
37
+ /** What the caller this request is from was opened, on top of what every
38
+ * request through the tunnel is: the entry for the platform's word on it, or
39
+ * nothing. */
40
+ export let named = (callers: Callers = {}, req: Request): Opened => {
41
+ let word = req.headers.get(CALLER) ?? ''
42
+ return Object.hasOwn(callers, word) ? callers[word] : {}
43
+ }
44
+
45
+ /** Whether the gateway marked this request: it came through the tunnel. */
46
+ export let marked = (req: Request): boolean => req.headers.has(HEADER)
47
+
48
+ // Patterns depend on their pathname, not the mutable list of opened routes.
49
+ let patterns = new Map<string, URLPattern>()
50
+ let pattern = (pathname: string): URLPattern => {
51
+ let found = patterns.get(pathname)
52
+ if (found) return found
53
+ let compiled = new URLPattern({ pathname })
54
+ patterns.set(pathname, compiled)
55
+ if (patterns.size > 256) patterns.delete(patterns.keys().next().value!)
56
+ return compiled
57
+ }
58
+
59
+ /** Whether the tunnel answers at `path`: `routes` are URLPattern pathnames
60
+ * (`/mail/inbound`, `/hooks/*`), and none opens nothing.
61
+ *
62
+ * ```ts
63
+ * import { assert } from '@std/assert'
64
+ * assert(opens(['/mail/inbound', '/hooks/*'], '/hooks/github'))
65
+ * assert(!opens(['/mail/inbound'], '/apply'))
66
+ * ```
67
+ */
68
+ export let opens = (routes: string[] = [], path: string): boolean =>
69
+ routes.some((pathname) => pattern(pathname).test({ pathname: path }))
70
+
71
+ /** A marked request at a path the machine did not open. Its name is the
72
+ * policy refusal's, so a server answers it 403. */
73
+ export class Closed extends Error {
74
+ override name = 'Denied'
75
+ }
76
+
77
+ /** The machine's word on the tunnel: a marked request passes only at a path
78
+ * opened to every request (`routes`) or to the caller the platform says it is
79
+ * from (`callers`), and an unmarked one always does.
80
+ *
81
+ * ```ts
82
+ * import { assertThrows } from '@std/assert'
83
+ * import { CALLER, HEADER } from './gateway.ts'
84
+ * let only = filter(['/mail/inbound'], { operator: { routes: ['/mcp'] } })
85
+ * let through = (path: string, caller = 'app') =>
86
+ * new Request(`http://box${path}`, {
87
+ * headers: { [HEADER]: '1', [CALLER]: caller },
88
+ * })
89
+ * only(new Request('http://box/apply'))
90
+ * only(through('/mail/inbound'))
91
+ * only(through('/mcp', 'operator'))
92
+ * assertThrows(() => only(through('/mcp')))
93
+ * assertThrows(() => only(through('/apply', 'operator')))
94
+ * ```
95
+ */
96
+ export let filter =
97
+ (routes: string[] = [], callers?: Callers) => (req: Request): void => {
98
+ if (!marked(req)) return
99
+ let { pathname } = new URL(req.url)
100
+ if (
101
+ !opens(routes, pathname) && !opens(named(callers, req).routes, pathname)
102
+ ) {
103
+ throw new Closed(`the tunnel does not answer ${pathname}`)
104
+ }
105
+ }
106
+
107
+ /** The tools a request is offered, by name: for a marked request the ones the
108
+ * machine's owner named for every request (`tools`) and for the caller the
109
+ * platform says it is from (`callers`), and none names nothing; an unmarked
110
+ * request is not narrowed (`undefined`).
111
+ *
112
+ * ```ts
113
+ * import { assertEquals } from '@std/assert'
114
+ * import { CALLER, HEADER } from './gateway.ts'
115
+ * let tools = offered(['task_list'], { operator: { tools: ['task_new'] } })
116
+ * let through = (caller: string) =>
117
+ * new Request('http://box/mcp', {
118
+ * headers: { [HEADER]: '1', [CALLER]: caller },
119
+ * })
120
+ * assertEquals(tools(new Request('http://box/mcp')), undefined)
121
+ * assertEquals(tools(through('app')), ['task_list'])
122
+ * assertEquals(tools(through('operator')), ['task_list', 'task_new'])
123
+ * ```
124
+ */
125
+ export let offered =
126
+ (tools: string[] = [], callers?: Callers) =>
127
+ (req: Request): string[] | undefined =>
128
+ marked(req) ? [...tools, ...named(callers, req).tools ?? []] : undefined
package/gateway.js ADDED
@@ -0,0 +1,37 @@
1
+ // The tunnel's cloud end: the gateway, a Worker the hosting platform uploads
2
+ // for each tunnel (./cloudflare.ts `gateways`) and the only thing bound to its
3
+ // VPC Service. The platform hands it a request only once it has decided the
4
+ // app may reach the machine, and the gateway marks every request it passes on
5
+ // with `x-yak-tunnel`, over whatever the request said. An app never holds the
6
+ // binding, so all it can send the machine is what the platform passes on, and
7
+ // always marked. The machine's end is ./filter.ts.
8
+ //
9
+ // The platform also says who is asking, in `x-yak-caller`: a word of its own
10
+ // for each kind of caller it passes on (an app's worker, its owner's
11
+ // assistant), set on every request it hands the gateway and taken off
12
+ // whatever a caller sent. The gateway passes it on as it came, and the
13
+ // machine opens a path to the callers it names (./filter.ts `Callers`).
14
+ // Where a request carries its owner's own words, the platform says who that
15
+ // is too, in `x-yak-by`, and where it was made in a conversation, whose that
16
+ // is, in `x-yak-with`.
17
+ /** The header the gateway marks every request with. */ export let HEADER = 'x-yak-tunnel';
18
+ /** The header the platform says who is asking in: its own word for the kind of
19
+ * caller, which only it sets. */ export let CALLER = 'x-yak-caller';
20
+ /** The header the platform names a person in, by its own id for them: the
21
+ * request is that person's own act (their words, their answer), where one
22
+ * without it is their assistant's. Only the platform says it, as it does
23
+ * `x-yak-caller`. The machine's end decides whose act it then is
24
+ * (./routes.ts). */ export let BY = 'x-yak-by';
25
+ /** The header the platform names the person a request's conversation is
26
+ * held with, by its own id for them: whose assistant is asking, where
27
+ * `x-via` names the conversation. Only the platform says it. */ export let WITH = 'x-yak-with';
28
+ /** The gateway's one module: the request as the platform passed it on, marked
29
+ * as the tunnel's, to the machine behind the VPC Service (`BOX`). */ export let GATEWAY = `export default {
30
+ fetch(req, env) {
31
+ let headers = new Headers(req.headers)
32
+ headers.set('${HEADER}', '1')
33
+ return env.BOX.fetch(new Request(req, { headers }))
34
+ },
35
+ }
36
+ `;
37
+ //# sourceMappingURL=gateway.js.map
package/gateway.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway.js","sources":["./gateway.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,+EAA+E;AAC/E,4EAA4E;AAC5E,8EAA8E;AAC9E,8EAA8E;AAC9E,8EAA8E;AAC9E,mDAAmD;AACnD,EAAE;AACF,6EAA6E;AAC7E,qEAAqE;AACrE,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,4EAA4E;AAC5E,6EAA6E;AAC7E,uBAAuB;AAEvB,qDAAqD,GACrD,OAAO,IAAI,SAAS,eAAc;AAElC;+BAC+B,GAC/B,OAAO,IAAI,SAAS,eAAc;AAElC;;;;kBAIkB,GAClB,OAAO,IAAI,KAAK,WAAU;AAE1B;;8DAE8D,GAC9D,OAAO,IAAI,OAAO,aAAY;AAE9B;mEACmE,GACnE,OAAO,IAAI,UAAU,CAAC;;;iBAGL,EAAE,OAAO;;;;AAI1B,CAAC,CAAA"}
package/gateway.ts ADDED
@@ -0,0 +1,46 @@
1
+ // The tunnel's cloud end: the gateway, a Worker the hosting platform uploads
2
+ // for each tunnel (./cloudflare.ts `gateways`) and the only thing bound to its
3
+ // VPC Service. The platform hands it a request only once it has decided the
4
+ // app may reach the machine, and the gateway marks every request it passes on
5
+ // with `x-yak-tunnel`, over whatever the request said. An app never holds the
6
+ // binding, so all it can send the machine is what the platform passes on, and
7
+ // always marked. The machine's end is ./filter.ts.
8
+ //
9
+ // The platform also says who is asking, in `x-yak-caller`: a word of its own
10
+ // for each kind of caller it passes on (an app's worker, its owner's
11
+ // assistant), set on every request it hands the gateway and taken off
12
+ // whatever a caller sent. The gateway passes it on as it came, and the
13
+ // machine opens a path to the callers it names (./filter.ts `Callers`).
14
+ // Where a request carries its owner's own words, the platform says who that
15
+ // is too, in `x-yak-by`, and where it was made in a conversation, whose that
16
+ // is, in `x-yak-with`.
17
+
18
+ /** The header the gateway marks every request with. */
19
+ export let HEADER = 'x-yak-tunnel'
20
+
21
+ /** The header the platform says who is asking in: its own word for the kind of
22
+ * caller, which only it sets. */
23
+ export let CALLER = 'x-yak-caller'
24
+
25
+ /** The header the platform names a person in, by its own id for them: the
26
+ * request is that person's own act (their words, their answer), where one
27
+ * without it is their assistant's. Only the platform says it, as it does
28
+ * `x-yak-caller`. The machine's end decides whose act it then is
29
+ * (./routes.ts). */
30
+ export let BY = 'x-yak-by'
31
+
32
+ /** The header the platform names the person a request's conversation is
33
+ * held with, by its own id for them: whose assistant is asking, where
34
+ * `x-via` names the conversation. Only the platform says it. */
35
+ export let WITH = 'x-yak-with'
36
+
37
+ /** The gateway's one module: the request as the platform passed it on, marked
38
+ * as the tunnel's, to the machine behind the VPC Service (`BOX`). */
39
+ export let GATEWAY = `export default {
40
+ fetch(req, env) {
41
+ let headers = new Headers(req.headers)
42
+ headers.set('${HEADER}', '1')
43
+ return env.BOX.fetch(new Request(req, { headers }))
44
+ },
45
+ }
46
+ `
package/hosted.js ADDED
@@ -0,0 +1,345 @@
1
+ // The hosting half, exported as `@yaks/tunnel/hosted`: what a platform that
2
+ // hosts spaces answers about the tunnels they have to machines, and how it
3
+ // passes a request through one. ./routes.ts is the machine's end; this is the
4
+ // other.
5
+ //
6
+ // The platform's door (`door`, at ./effects.ts `TELL`) answers a space's
7
+ // tunnel to its owner and to the platform's own owner, and changes it:
8
+ //
9
+ // GET ?space=ada the tunnel, or null
10
+ // POST space=ada do=connect port=N a new tunnel, service and gateway; the
11
+ // token once
12
+ // POST space=ada do=rotate the gateway put again, and a new token
13
+ // for a tunnel the platform made, once
14
+ // POST space=ada do=disconnect keep the tunnel in the trash
15
+ // POST space=ada do=restore restore the same tunnel
16
+ // POST space=ada do=purge ask its owner to confirm a permanent purge
17
+ // POST space=ada do=adopt tunnel=… service=… record a pair made elsewhere,
18
+ // with a gateway in front
19
+ // POST do=tell conversation=… key=… text=… [about=…] the machine telling
20
+ // its owner what changed there
21
+ // (./effects.ts)
22
+ //
23
+ // The space's owner connects, rotates and disconnects. Adopting is the
24
+ // platform owner's alone: the ids name resources in the platform's account,
25
+ // and a space that could write any service id could reach somebody else's
26
+ // machine. Disconnecting keeps the pair and its names in the trash and
27
+ // removes only its regenerable gateway. Restoring puts the gateway again.
28
+ // Purging an adopted pair forgets its ids; whoever made it removes it.
29
+ // A tunnel’s token is answered once and never kept.
30
+ //
31
+ // A request reaches a machine two ways: an app's own worker asking for it
32
+ // (`reach`), built in the space and never an installed copy, and the space's
33
+ // owner asking with no app between (`machine`), by their connector or their
34
+ // Operator, which reaches only its own space's machine (`owners`). Either way
35
+ // the request goes on to the space's gateway (./gateway.ts) with the
36
+ // platform's own words taken off and its word on who is asking put on
37
+ // (`onward`), and every way it can fail to arrive is an answer.
38
+ //
39
+ // What only the host can do comes in as data: who is asking and where they
40
+ // stand (`Keeping`), and the call that hands a request to a gateway
41
+ // (`Relay`), which is a Workers for Platforms dispatch binding on yaks.app.
42
+ import { VIA } from "@yaks/api";
43
+ import { connect, disconnect, tunnels } from "./cloudflare.js";
44
+ import { BY, CALLER, WITH } from "./gateway.js";
45
+ /** The name of the gateway in front of the tunnel of the space `eid`, in the
46
+ * namespace the host uploads gateways to (./cloudflare.ts `gateways`). */ export let gatewayOf = (eid)=>`tunnel-${eid}`;
47
+ /** Where an app's worker asks for its space's machine, under the app's own
48
+ * doors: `/tunneled/mail/inbound` is `/mail/inbound` on the machine. */ export let TUNNELED = '/tunneled/';
49
+ let ending = (e)=>Response.json({
50
+ error: {
51
+ code: e.code,
52
+ message: e.message
53
+ }
54
+ }, {
55
+ status: e.status
56
+ });
57
+ let refused = (status, code, message)=>ending({
58
+ status,
59
+ code,
60
+ message
61
+ });
62
+ // How a call that reached no machine ends, said the same to an app's worker
63
+ // and to the tunnel's owner.
64
+ let NO_TUNNEL = (space)=>({
65
+ status: 404,
66
+ code: 'no_tunnel',
67
+ message: `${space.slug} has no tunnel to a machine; its owner makes one first`
68
+ });
69
+ let NO_GATEWAY = (space)=>({
70
+ status: 503,
71
+ code: 'no_gateway',
72
+ message: `${space.slug}'s tunnel has no gateway; its owner rotates the tunnel to make one`
73
+ });
74
+ let UNREACHED = (space)=>({
75
+ status: 502,
76
+ code: 'unreached',
77
+ message: `the machine ${space.slug}'s tunnel goes to did not answer`
78
+ });
79
+ // ── A request on its way to a machine ───────────────────────────────────────
80
+ // The platform's own words about a request (the grants, who is looking), none
81
+ // of which is the machine's business, and the words it says to the machine
82
+ // itself: no caller's request names the conversation it was made in, or who
83
+ // is asking.
84
+ let OURS = /^(cookie|x-via)$|^x-yak-/;
85
+ /** A request as it goes on to a machine: `req`'s method, body and headers at
86
+ * `path` there, with the platform's own words taken off and its word on who
87
+ * is asking put on: the conversation it was made in (`via`), whose that is
88
+ * (`with`, only beside `via`) and whose own act it is (`by`). */ export let onward = (path, req, caller, said = {})=>{
89
+ let headers = new Headers();
90
+ for (let [k, v] of req.headers)if (!OURS.test(k)) headers.set(k, v);
91
+ headers.set(CALLER, caller);
92
+ if (said.via) headers.set(VIA, said.via);
93
+ if (said.via && said.with) headers.set(WITH, said.with);
94
+ if (said.by) headers.set(BY, said.by);
95
+ return new Request(`http://machine${path}`, {
96
+ method: req.method,
97
+ headers,
98
+ body: req.body,
99
+ redirect: 'manual',
100
+ signal: req.signal
101
+ });
102
+ };
103
+ // `out` through the relay, or how it failed to arrive; a throw is told to
104
+ // `report` where there is one.
105
+ let relayed = async (space, relay, out, report)=>{
106
+ try {
107
+ return await relay(out) ?? ending(NO_GATEWAY(space));
108
+ } catch (e) {
109
+ report?.(e);
110
+ return ending(UNREACHED(space));
111
+ }
112
+ };
113
+ /** Why `app` may not reach the machine its space's tunnel goes to, or null
114
+ * where it may: only an app built in the space reaches it, since an installed
115
+ * copy's code was written elsewhere and a tunnel reaches into the owner's own
116
+ * machine, and only while the space has a tunnel. */ export let barred = (space, app)=>app.installed ? {
117
+ status: 403,
118
+ code: 'installed',
119
+ message: `${app.slug} is an installed copy, and only an app built in ${space.slug} reaches the machine its tunnel goes to`
120
+ } : !space.tunnel || space.tunnelTrashed ? NO_TUNNEL(space) : null;
121
+ /** An app's own worker reaching the machine its space's tunnel goes to, at
122
+ * `path` under its doors, or null for a path not at `TUNNELED`. `itself` is
123
+ * whether the host knows the request for the app's own worker: nothing a
124
+ * visitor holds opens it. The request goes on as an `app`'s, and the machine
125
+ * decides what it answers. A throw from the relay is told to `report`. */ export let reach = async (req, path, at, relay, report)=>{
126
+ if (!path.startsWith(TUNNELED)) return null;
127
+ if (!at.itself) {
128
+ return refused(403, 'not_the_app', "only the app's own worker reaches the machine its space's tunnel goes to");
129
+ }
130
+ let bar = barred(at.space, at.app);
131
+ if (bar) return ending(bar);
132
+ let rest = path.slice(TUNNELED.length - 1) + new URL(req.url).search;
133
+ return await relayed(at.space, relay, onward(rest, req, 'app'), report);
134
+ };
135
+ /** Whether `asking` reaches the machine of the space `at` for a person seated
136
+ * there as `role`: its owner alone, and their Operator only from that space,
137
+ * since another space's members shape its instructions and memory. */ export let owners = (role, at, asking)=>role == 'owner' && (asking.caller != 'operator' || asking.space == at);
138
+ /** The machine `space`'s tunnel goes to, as a `fetch` for its owner `person`,
139
+ * asked as `asking` says (whom the host has found `owners`). Only the path of
140
+ * what it is asked for is meant. Every ending is an answer: a space with no
141
+ * tunnel, a tunnel with no gateway and a machine that is off are the machine
142
+ * being unavailable to its owner. */ export let machine = (space, person, asking, relay)=>async (input, init)=>{
143
+ if (!space.tunnel || space.tunnelTrashed) return ending(NO_TUNNEL(space));
144
+ let req = new Request(input, init);
145
+ let { pathname, search } = new URL(req.url);
146
+ let out = onward(pathname + search, req, asking.caller, {
147
+ via: await asking.via?.(),
148
+ with: person,
149
+ by: asking.own ? person : undefined
150
+ });
151
+ return await relayed(space, relay, out);
152
+ };
153
+ // A Cloudflare id, as the API spells one: a uuid. An eid is spelled the same.
154
+ let UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
155
+ let NO_ACCOUNT = 'the platform has no account token to make tunnels with';
156
+ let NO_UPLOAD = "the platform has no token to upload a tunnel's gateway with";
157
+ let shown = (space, tunnel, more = {})=>Response.json({
158
+ space: space.slug,
159
+ tunnel,
160
+ ...more
161
+ });
162
+ /** The platform's door onto its spaces' tunnels, as the header says. */ export let door = async (req, host)=>{
163
+ if (req.method != 'GET' && req.method != 'POST') {
164
+ return refused(405, 'method_not_allowed', 'get the tunnel, or post a change');
165
+ }
166
+ let form = req.method == 'POST' ? await req.formData() : null;
167
+ let said = (k)=>String(form?.get(k) ?? new URL(req.url).searchParams.get(k) ?? '');
168
+ let person = await host.who();
169
+ if (form && said('do') == 'tell') return await heard(host, person, said);
170
+ if (form && said('do') == 'ready') {
171
+ let tunnel = said('tunnel');
172
+ if (!person) {
173
+ return refused(403, 'not_owner', 'Sign in to report readiness.');
174
+ }
175
+ if (!UUID.test(tunnel)) {
176
+ return refused(400, 'bad_ids', 'Give the tunnel id.');
177
+ }
178
+ await host.ready?.(person, tunnel);
179
+ return new Response(null, {
180
+ status: 204
181
+ });
182
+ }
183
+ let space = said('space') ? await host.find(said('space'), person) : null;
184
+ if (!space) {
185
+ return refused(404, 'no_space', `no space is called ${said('space') || '""'}`);
186
+ }
187
+ if (!space.owner && !space.platform) {
188
+ return refused(403, 'not_owner', `${space.slug}'s machine is its owner's`);
189
+ }
190
+ if (req.method == 'GET') {
191
+ return shown(space, space.tunnelTrashed ? null : space.tunnel, {
192
+ ...space.tunnelTrashed ? {
193
+ trashed: space.tunnelTrashed
194
+ } : {}
195
+ });
196
+ }
197
+ return await changed(host, space, said);
198
+ };
199
+ // A knock from the machine (./effects.ts `platformTell`): only its owner
200
+ // tells it, by their own connection, and it names its conversation and
201
+ // itself, and says something. What it tells of rides with it where it is an
202
+ // eid.
203
+ let heard = async (host, person, said)=>{
204
+ if (!person) {
205
+ return refused(403, 'not_owner', "a machine tells only its owner's Operator");
206
+ }
207
+ let [conversation, key, text, about] = [
208
+ 'conversation',
209
+ 'key',
210
+ 'text',
211
+ 'about'
212
+ ].map(said);
213
+ if (!conversation || !key || !text.trim()) {
214
+ return refused(400, 'bad_tell', 'a knock names its conversation and itself, and says something');
215
+ }
216
+ let told = {
217
+ conversation,
218
+ key: key,
219
+ text,
220
+ ...UUID.test(about) ? {
221
+ about: about
222
+ } : {},
223
+ ...[
224
+ 'settled',
225
+ 'failed',
226
+ 'stopped',
227
+ 'open'
228
+ ].includes(said('outcome')) ? {
229
+ outcome: said('outcome')
230
+ } : {}
231
+ };
232
+ let answer = await host.tell(person, told);
233
+ return answer ? Response.json(answer) : refused(404, 'no_conversation', `no space of yours with a tunnel holds ${conversation}`);
234
+ };
235
+ // A change to `space`'s tunnel, by its owner or the platform's.
236
+ let changed = async (host, space, said)=>{
237
+ let held = space.tunnel;
238
+ let act = said('do');
239
+ let gateway = gatewayOf(space.eid);
240
+ if (act == 'adopt') {
241
+ if (!space.platform) {
242
+ return refused(403, 'not_platform', "adopting names the platform's own resources, so the platform's owner does it");
243
+ }
244
+ // Replacing either kind of pair would lose its saved identifiers.
245
+ if (held && (!held.adopted || space.tunnelTrashed || held.id != said('tunnel') || held.service != said('service'))) {
246
+ return refused(409, 'has_tunnel', `${space.slug} has a tunnel; restore it or confirm its purge before adopting another`);
247
+ }
248
+ let [id, service] = [
249
+ said('tunnel'),
250
+ said('service')
251
+ ];
252
+ if (!UUID.test(id) || !UUID.test(service)) {
253
+ return refused(400, 'bad_ids', 'tunnel and service are each a uuid');
254
+ }
255
+ if (!host.gateways) return refused(503, 'no_token', NO_UPLOAD);
256
+ await host.gateways.put(gateway, service);
257
+ let row = {
258
+ id,
259
+ service,
260
+ adopted: true
261
+ };
262
+ await host.write(space.eid, row);
263
+ return shown(space, row);
264
+ }
265
+ if (!space.owner) {
266
+ return refused(403, 'not_owner', `${space.slug}'s machine is its owner's`);
267
+ }
268
+ if (act == 'connect') {
269
+ if (held) {
270
+ return refused(409, 'has_tunnel', `${space.slug} has a tunnel already`);
271
+ }
272
+ let port = Number(said('port'));
273
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
274
+ return refused(400, 'bad_port', 'port is the one the machine serves on');
275
+ }
276
+ let { account, gateways } = host;
277
+ if (!account) return refused(503, 'no_token', NO_ACCOUNT);
278
+ if (!gateways) return refused(503, 'no_token', NO_UPLOAD);
279
+ let made = await connect(account, `space-${space.eid}`, {
280
+ port
281
+ });
282
+ let row = {
283
+ id: made.tunnel,
284
+ service: made.service,
285
+ adopted: false
286
+ };
287
+ try {
288
+ await gateways.put(gateway, made.service);
289
+ await host.write(space.eid, row);
290
+ } catch (e) {
291
+ await gateways.remove(gateway);
292
+ await disconnect(account, made);
293
+ throw e;
294
+ }
295
+ return shown(space, row, {
296
+ token: made.token
297
+ });
298
+ }
299
+ if (![
300
+ 'rotate',
301
+ 'disconnect',
302
+ 'restore',
303
+ 'purge'
304
+ ].includes(act)) {
305
+ return refused(400, 'bad_do', 'do is connect, rotate, disconnect, restore, purge, adopt or tell');
306
+ }
307
+ if (!held) return refused(404, 'no_tunnel', `${space.slug} has no tunnel`);
308
+ if (act == 'purge') {
309
+ if (!space.tunnelTrashed) {
310
+ return refused(409, 'not_trashed', 'disconnect the tunnel into the trash first');
311
+ }
312
+ return shown(space, null, {
313
+ trashed: space.tunnelTrashed,
314
+ message: await host.purge(space)
315
+ });
316
+ }
317
+ if (space.tunnelTrashed && act == 'rotate') {
318
+ return refused(409, 'trashed', 'restore the tunnel from the trash first');
319
+ }
320
+ let { account, gateways } = host;
321
+ if (!gateways) return refused(503, 'no_token', NO_UPLOAD);
322
+ if (act == 'rotate' && !held.adopted && !account) {
323
+ return refused(503, 'no_token', NO_ACCOUNT);
324
+ }
325
+ if (act == 'restore') {
326
+ await gateways.put(gateway, held.service);
327
+ await host.trash(space.eid, null);
328
+ return shown(space, held);
329
+ }
330
+ if (act == 'rotate') {
331
+ // An adopted tunnel is rotated where it was made; its gateway is ours.
332
+ let token = account && !held.adopted ? await tunnels(account).rotate(held.id) : undefined;
333
+ await gateways.put(gateway, held.service);
334
+ return shown(space, held, {
335
+ token
336
+ });
337
+ }
338
+ let at = space.tunnelTrashed ?? new Date().toISOString();
339
+ await host.trash(space.eid, at);
340
+ await gateways.remove(gateway);
341
+ return shown(space, null, {
342
+ trashed: at
343
+ });
344
+ };
345
+ //# sourceMappingURL=hosted.js.map
package/hosted.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted.js","sources":["./hosted.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,2EAA2E;AAC3E,8EAA8E;AAC9E,SAAS;AACT,EAAE;AACF,yEAAyE;AACzE,uEAAuE;AACvE,EAAE;AACF,2DAA2D;AAC3D,8EAA8E;AAC9E,kDAAkD;AAClD,8EAA8E;AAC9E,4EAA4E;AAC5E,oEAAoE;AACpE,+DAA+D;AAC/D,kFAAkF;AAClF,+EAA+E;AAC/E,+DAA+D;AAC/D,6EAA6E;AAC7E,oEAAoE;AACpE,sDAAsD;AACtD,EAAE;AACF,uEAAuE;AACvE,4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