@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/cloudflare.ts ADDED
@@ -0,0 +1,233 @@
1
+ // The account side of a tunnel: the two Cloudflare resources that let a
2
+ // Worker reach a service on somebody's machine, and nothing else.
3
+ //
4
+ // A Cloudflare Tunnel is the machine's outbound connection: `cloudflared` runs
5
+ // there with the tunnel's token (./service.ts) and dials Cloudflare, so the
6
+ // machine needs no open port and no public address. A Workers VPC Service
7
+ // names one host and port behind that tunnel; a Worker bound to it reaches
8
+ // exactly that service and nothing else on the network, whatever URL it
9
+ // fetches (https://developers.cloudflare.com/workers-vpc/api/).
10
+ //
11
+ // A gateway is the third: the Worker in front of a tunnel (./gateway.ts), and
12
+ // the only thing bound to its VPC Service, so that nothing but the platform
13
+ // that uploaded it reaches the machine, and every request it passes on is
14
+ // marked as the tunnel's.
15
+ //
16
+ // The tunnel's token is a credential: whoever holds it can run the tunnel. So
17
+ // this module hands it back to its caller and never keeps or logs it; where it
18
+ // goes next is the caller's business (a vault, a sealed secret).
19
+ //
20
+ // The API token the tunnel and service calls are made with needs Cloudflare
21
+ // Tunnel Write and the Connectivity Directory Admin role
22
+ // (https://developers.cloudflare.com/workers-vpc/configuration/vpc-services/);
23
+ // the one a gateway is uploaded with needs Workers Scripts Edit and the
24
+ // Connectivity Directory Bind role.
25
+ import { GATEWAY } from './gateway.js'
26
+
27
+ /** The account, and the token its calls are made with. */
28
+ export type Api = {
29
+ account: string
30
+ token: string
31
+ /** the fetch the calls go through; the global one when left out */
32
+ fetch?: (url: string, init: RequestInit) => Promise<Response>
33
+ }
34
+
35
+ /** A tunnel as made: its id, and the token `cloudflared` runs it with. */
36
+ export type Made = { id: string; token: string }
37
+
38
+ /** A machine's pair: the tunnel, and the VPC Service behind it. */
39
+ export type Pair = { tunnel: string; service: string }
40
+
41
+ /** Where a VPC Service sends a Worker's requests: a port on the machine, and
42
+ * the address it listens on there (`127.0.0.1` unless said). */
43
+ export type Target = { port: number; host?: string }
44
+
45
+ type Envelope = {
46
+ success?: boolean
47
+ errors?: { message?: string }[]
48
+ result?: unknown
49
+ }
50
+
51
+ /** One call, and what it answered, or the sentence Cloudflare refused it
52
+ * with. Every reply is wrapped `{success, errors, result}`, so a failure is
53
+ * read out of the body and not only off the status. A body is JSON, or a
54
+ * form sent as the multipart it is. */
55
+ let call = async (
56
+ api: Api,
57
+ method: string,
58
+ path: string,
59
+ body?: unknown,
60
+ ): Promise<unknown> => {
61
+ let json = body !== undefined && !(body instanceof FormData)
62
+ let r = await (api.fetch ?? fetch)(
63
+ `https://api.cloudflare.com/client/v4/accounts/${api.account}${path}`,
64
+ {
65
+ method,
66
+ headers: {
67
+ authorization: `Bearer ${api.token}`,
68
+ ...json ? { 'content-type': 'application/json' } : {},
69
+ },
70
+ ...body === undefined
71
+ ? {}
72
+ : { body: json ? JSON.stringify(body) : body as FormData },
73
+ },
74
+ )
75
+ let text = await r.text()
76
+ let said: Envelope | null = null
77
+ try {
78
+ said = JSON.parse(text)
79
+ } catch {
80
+ // not JSON: the status and the text say it
81
+ }
82
+ if (r.ok && said?.success) return said.result
83
+ let why = said?.errors?.map((e) => e.message).filter(Boolean).join('; ')
84
+ throw new Error(`cloudflare: ${why || text.slice(0, 400) || r.status}`)
85
+ }
86
+
87
+ let field = (v: unknown, name: string): string => {
88
+ let got = (v as Record<string, unknown> | null)?.[name]
89
+ if (typeof got != 'string' || !got) {
90
+ throw new Error(`cloudflare: the answer named no ${name}`)
91
+ }
92
+ return got
93
+ }
94
+
95
+ /** A tunnel's secret: 32 random bytes, base64, the size Cloudflare asks
96
+ * for. */
97
+ let secret = () =>
98
+ btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))))
99
+
100
+ /** The account's Cloudflare Tunnels, each run by `cloudflared` with its
101
+ * token and configured from the account rather than a file on the machine. */
102
+ export let tunnels = (api: Api) => ({
103
+ /** A new tunnel, and the token to run it with. */
104
+ create: async (name: string): Promise<Made> => {
105
+ let r = await call(api, 'POST', '/cfd_tunnel', {
106
+ name,
107
+ config_src: 'cloudflare',
108
+ })
109
+ return { id: field(r, 'id'), token: field(r, 'token') }
110
+ },
111
+ /** The token a tunnel runs with now. */
112
+ token: async (id: string): Promise<string> => {
113
+ let r = await call(api, 'GET', `/cfd_tunnel/${id}/token`)
114
+ if (typeof r != 'string' || !r) {
115
+ throw new Error('cloudflare: the answer named no token')
116
+ }
117
+ return r
118
+ },
119
+ /** A new token for the tunnel. The old one opens no new connection, and a
120
+ * connector already running keeps going until it restarts. */
121
+ rotate: async (id: string): Promise<string> =>
122
+ field(
123
+ await call(api, 'PATCH', `/cfd_tunnel/${id}`, {
124
+ tunnel_secret: secret(),
125
+ }),
126
+ 'token',
127
+ ),
128
+ /** The tunnel gone. One that is already gone is not a failure. */
129
+ remove: (id: string): Promise<void> =>
130
+ gone(call(api, 'DELETE', `/cfd_tunnel/${id}`)),
131
+ })
132
+
133
+ /** The account's Workers VPC Services, each one host and port behind one
134
+ * tunnel. */
135
+ export let services = (api: Api) => ({
136
+ /** A new HTTP service behind a tunnel; answers its id. */
137
+ create: async (
138
+ name: string,
139
+ tunnel: string,
140
+ to: Target,
141
+ ): Promise<string> =>
142
+ field(
143
+ await call(api, 'POST', '/connectivity/directory/services', {
144
+ type: 'http',
145
+ name,
146
+ http_port: to.port,
147
+ host: { ipv4: to.host ?? '127.0.0.1', network: { tunnel_id: tunnel } },
148
+ }),
149
+ 'service_id',
150
+ ),
151
+ /** The service gone. One that is already gone is not a failure. */
152
+ remove: (id: string): Promise<void> =>
153
+ gone(call(api, 'DELETE', `/connectivity/directory/services/${id}`)),
154
+ })
155
+
156
+ /** The module a gateway runs, by name, and the date its runtime is pinned
157
+ * to. */
158
+ export let MODULE = 'gateway.js'
159
+ let DATE = '2026-09-01'
160
+
161
+ /** The gateways in one dispatch namespace. */
162
+ export type Gateways = {
163
+ put: (name: string, service: string) => Promise<void>
164
+ remove: (name: string) => Promise<void>
165
+ }
166
+
167
+ /** The gateways in front of tunnels: one Worker per tunnel in a Workers for
168
+ * Platforms dispatch namespace, where only the platform that owns the
169
+ * namespace can call it (./gateway.ts). */
170
+ export let gateways = (api: Api, namespace: string): Gateways => {
171
+ let at = (name: string) =>
172
+ `/workers/dispatch/namespaces/${namespace}/scripts/${name}`
173
+ return {
174
+ /** The gateway `name` in front of the VPC Service `service`, made or
175
+ * made again. */
176
+ put: async (name: string, service: string): Promise<void> => {
177
+ let body = new FormData()
178
+ let meta = {
179
+ main_module: MODULE,
180
+ compatibility_date: DATE,
181
+ bindings: [{ type: 'vpc_service', name: 'BOX', service_id: service }],
182
+ }
183
+ body.append(
184
+ 'metadata',
185
+ new Blob([JSON.stringify(meta)], { type: 'application/json' }),
186
+ )
187
+ body.append(
188
+ MODULE,
189
+ new Blob([GATEWAY], { type: 'application/javascript+module' }),
190
+ MODULE,
191
+ )
192
+ await call(api, 'PUT', at(name), body)
193
+ },
194
+ /** The gateway gone. One that is already gone is not a failure. */
195
+ remove: (name: string): Promise<void> =>
196
+ gone(call(api, 'DELETE', at(name))),
197
+ }
198
+ }
199
+
200
+ // A delete of something already deleted has done what was asked.
201
+ let gone = async (p: Promise<unknown>): Promise<void> => {
202
+ try {
203
+ await p
204
+ } catch (e) {
205
+ if (!/not found|does not exist|404/i.test(String(e))) throw e
206
+ }
207
+ }
208
+
209
+ /**
210
+ * A machine's pair made: a tunnel, and a VPC Service behind it on `to`. Answers
211
+ * both ids and the token. A service that cannot be made takes its tunnel
212
+ * with it, so a failure leaves nothing behind in the account.
213
+ */
214
+ export let connect = async (
215
+ api: Api,
216
+ name: string,
217
+ to: Target,
218
+ ): Promise<Pair & { token: string }> => {
219
+ let made = await tunnels(api).create(name)
220
+ try {
221
+ let service = await services(api).create(name, made.id, to)
222
+ return { tunnel: made.id, service, token: made.token }
223
+ } catch (e) {
224
+ await tunnels(api).remove(made.id)
225
+ throw e
226
+ }
227
+ }
228
+
229
+ /** A machine's pair removed: the service first, since it names the tunnel. */
230
+ export let disconnect = async (api: Api, pair: Pair): Promise<void> => {
231
+ await services(api).remove(pair.service)
232
+ await tunnels(api).remove(pair.tunnel)
233
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/tunnel","version":"0.2.36","license":"Apache-2.0","description":"Reaches a machine from a hosted space through a Cloudflare Tunnel and a Workers VPC Service: the account calls that make one, the hosting platform's door onto them and the requests it passes through one, the connector that runs it on the machine, the machine's word on what comes through: the paths it opened, the tools it offers and who a caller writes as, and what the machine tells the platform back.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./routes":"./routes.ts","./hosted":"./hosted.ts","./service":"./service.ts","./effects":"./effects.ts"},"imports":{"@yaks/tunnel":"./mod.ts","@yaks/tunnel/vocab":"./vocab.ts","@yaks/tunnel/routes":"./routes.ts","@yaks/tunnel/hosted":"./hosted.ts","@yaks/tunnel/service":"./service.ts","@yaks/tunnel/effects":"./effects.ts"}}
package/effects.js ADDED
@@ -0,0 +1,103 @@
1
+ // The effects facet, exported as `@yaks/tunnel/effects`: what the machine
2
+ // says back up its tunnel. A session standing here for a conversation held on
3
+ // the tunnel's platform (@yaks/session `standIn`, at ./routes.ts `DOOR`) has
4
+ // no process to hear a knock with, so a knock at it is news for that
5
+ // conversation. Only one held with the machine's person is told, since it is
6
+ // told through their own connection (a space that adopted this machine's
7
+ // tunnel but is somebody else's has no such conversation there): `tunnel_tell` gives its words to the platform, as the
8
+ // machine's person through their own connection to it, naming the
9
+ // conversation and the knock, and marks the knock said. yaks.app takes it in
10
+ // as a request on the Operator's `machine` channel (workers/yak/tunnel.ts),
11
+ // and its Operator decides whether its person hears of it. The knock names
12
+ // the request, so a run tried again tells it once.
13
+ import { accountCredential } from "@yaks/connections";
14
+ import { DOOR } from "./routes.js";
15
+ /** The platform a tunnel's conversations are held on, unless the config says
16
+ * another. */ export let PLATFORM = 'https://yaks.app';
17
+ /** Where the platform hears its machine. */ export let TELL = '/api/tunnel';
18
+ let comp = (b, name)=>b?.[name] ?? {};
19
+ let str = (v)=>typeof v == 'string' ? v : '';
20
+ /** What the knock `eid` tells the platform, or nothing where it is said
21
+ * already or is not at a session standing at this door for a conversation
22
+ * held with the machine's person (`session.person`). */ export let telling = async (g, eid)=>{
23
+ let [knock] = await g.get([
24
+ eid
25
+ ], [
26
+ 'knock',
27
+ 'doc',
28
+ 'notified'
29
+ ]);
30
+ if (!knock?.knock || knock.notified) return;
31
+ let [at] = await g.get([
32
+ str(comp(knock, 'knock').target)
33
+ ], [
34
+ 'session'
35
+ ]);
36
+ let session = comp(at, 'session');
37
+ let conversation = str(session.source);
38
+ // Only a conversation held with the machine's person is told: it is told
39
+ // through their own connection, and the platform holds nobody else's there.
40
+ if (session.door != DOOR || !conversation || !session.person) return;
41
+ let about = str(comp(knock, 'knock').about);
42
+ let outcome = str(comp(knock, 'knock').outcome);
43
+ return {
44
+ conversation,
45
+ key: eid,
46
+ text: str(comp(knock, 'doc').body),
47
+ ...about ? {
48
+ about
49
+ } : {},
50
+ ...outcome ? {
51
+ outcome
52
+ } : {}
53
+ };
54
+ };
55
+ /** Tell the platform what the knock `eid` says, and mark it said. */ export let tellOf = async (g, tell, eid)=>{
56
+ let told = await telling(g, eid);
57
+ if (!told) return;
58
+ await tell(told);
59
+ await g.apply([
60
+ {
61
+ entity: {
62
+ eid
63
+ },
64
+ notified: {}
65
+ }
66
+ ], {
67
+ trusted: true
68
+ });
69
+ };
70
+ /** Telling the platform at `options.platform` as the config's person, through
71
+ * their connection to it. */ export let platformTell = (host, options = {}, fetching = fetch)=>(told)=>post(host, options, {
72
+ do: 'tell',
73
+ ...told
74
+ }, fetching);
75
+ export let platformReady = (host, options, tunnel)=>post(host, options, {
76
+ do: 'ready',
77
+ tunnel
78
+ }, fetch);
79
+ let post = async (host, options, form, fetching)=>{
80
+ let origin = new URL(options.platform ?? PLATFORM);
81
+ let said = host.config?.person;
82
+ if (!said) throw new Error('the tunnel tells its platform as nobody');
83
+ let owner = (await host.graph.address([
84
+ said
85
+ ])).get(said) ?? said;
86
+ let integration = origin.hostname == 'yaks.app' ? 'yaks.app' : origin.origin;
87
+ let at = await accountCredential(host, owner, integration, options.as);
88
+ if (!at) throw new Error(`no ${integration} connection to tell it through`);
89
+ let r = await fetching(new URL(TELL, origin), {
90
+ method: 'POST',
91
+ headers: {
92
+ authorization: `Bearer ${at.bearer}`
93
+ },
94
+ body: new URLSearchParams(form)
95
+ });
96
+ if (r.ok) return void await r.body?.cancel();
97
+ let body = await r.text();
98
+ throw new Error(`${origin.host} said ${r.status} to tunnel ${form.do}: ${body}`);
99
+ };
100
+ /** The effect behind `tunnel_tell`. */ export let effects = (host, options = {})=>({
101
+ tunnel_tell: (e)=>tellOf(host.graph, platformTell(host, options), e.entity.eid)
102
+ });
103
+ //# sourceMappingURL=effects.js.map
package/effects.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effects.js","sources":["./effects.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,6EAA6E;AAC7E,qEAAqE;AACrE,6EAA6E;AAC7E,yEAAyE;AACzE,uHAAuH;AACvH,kEAAkE;AAClE,6EAA6E;AAC7E,4EAA4E;AAC5E,2EAA2E;AAC3E,mDAAmD;AAKnD,SAAS,iBAAiB,iCAAsC;AAChE,SAAS,IAAI,sBAAqB;AAgClC;YACY,GACZ,OAAO,IAAI,WAAW,mBAAkB;AAExC,0CAA0C,GAC1C,OAAO,IAAI,OAAO,cAAa;AAE/B,IAAI,OAAO,CAAC,GAAuB,OAChC,GAAG,CAAC,KAAK,IAAI,CAAC;AACjB,IAAI,MAAM,CAAC,IAAuB,OAAO,KAAK,WAAW,IAAI;AAE7D;;sDAEsD,GACtD,OAAO,IAAI,UAAU,OACnB,GACA;EAEA,IAAI,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,CAAC;IAAC;GAAI,EAAE;IAAC;IAAS;IAAO;GAAW;EAC7D,IAAI,CAAC,OAAO,SAAS,MAAM,QAAQ,EAAE;EACrC,IAAI,CAAC,GAAG,G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AAM,MAAM,IAAI,MAAM;EAC3B,IAAI,QAAS,CAAC,MAAM,KAAK,KAAK,CAAC,OAAO,CAAC;IAAC;GAAK,CAAC,EAAE,GAAG,CAAC,SAAS;EAC7D,IAAI,cAAc,OAAO,QAAQ,IAAI,aAAa,aAAa,OAAO,MAAM;EAC5E,IAAI,KAAK,MAAM,kBAAkB,MAAM,OAAO,aAAa,QAAQ,EAAE;EACrE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,CAAC,GAAG,EAAE,YAAY,8BAA8B,CAAC;EAC1E,IAAI,IAAI,MAAM,SAAS,IAAI,IAAI,MAAM,SAAS;IAC5C,QAAQ;IACR,SAAS;MAAE,eAAe,CAAC,OAAO,EAAE,GAAG,MAAM,EAAE;IAAC;IAChD,MAAM,IAAI,gBAAgB;EAC5B;EACA,IAAI,EAAE,EAAE,EAAE,OAAO,KAAK,MAAM,EAAE,IAAI,EAAE;EACpC,IAAI,OAAO,MAAM,EAAE,IAAI;EACvB,MAAM,IAAI,MACR,GAAG,OAAO,IAAI,CAAC,MAAM,EAAE,EAAE,MAAM,CAAC,WAAW,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM;AAEnE;AAEA,qCAAqC,GACrC,OAAO,IAAI,UAAU,CAAC,MAAe,UAAmB,CAAC,CAAC,GAAe,CAAC;IACxE,aAAa,CAAC,IACZ,OAAO,KAAK,KAAK,EAAE,aAAa,MAAM,UAAU,EAAE,MAAM,CAAC,GAAG;EAChE,CAAC,EAAC"}
package/effects.ts ADDED
@@ -0,0 +1,143 @@
1
+ // The effects facet, exported as `@yaks/tunnel/effects`: what the machine
2
+ // says back up its tunnel. A session standing here for a conversation held on
3
+ // the tunnel's platform (@yaks/session `standIn`, at ./routes.ts `DOOR`) has
4
+ // no process to hear a knock with, so a knock at it is news for that
5
+ // conversation. Only one held with the machine's person is told, since it is
6
+ // told through their own connection (a space that adopted this machine's
7
+ // tunnel but is somebody else's has no such conversation there): `tunnel_tell` gives its words to the platform, as the
8
+ // machine's person through their own connection to it, naming the
9
+ // conversation and the knock, and marks the knock said. yaks.app takes it in
10
+ // as a request on the Operator's `machine` channel (workers/yak/tunnel.ts),
11
+ // and its Operator decides whether its person hears of it. The knock names
12
+ // the request, so a run tried again tells it once.
13
+
14
+ import type { Handlers } from 'jsr:@yaks/effects@0.2.36'
15
+ import type { Bundle, Comp, Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
16
+ import type { Vault } from 'jsr:@yaks/secrets@0.2.36'
17
+ import { accountCredential } from '@yaks/connections'
18
+ import { DOOR } from './routes.js'
19
+
20
+ /** What a config file can set for this facet, beside ./routes.ts's own. */
21
+ export type Options = {
22
+ /** the platform the tunnel's conversations are held on */
23
+ platform?: string
24
+ /** which of the person's connections to it to speak as (its account) */
25
+ as?: string
26
+ }
27
+
28
+ /** What a knock tells the platform: the conversation it is news for, the
29
+ * knock that names it, its words, and what it tells of, where it names one
30
+ * entity here (`knock{about}`), so an alert about it opens at its row. */
31
+ export type Told = {
32
+ conversation: string
33
+ key: Eid
34
+ text: string
35
+ about?: Eid
36
+ outcome?: string
37
+ }
38
+
39
+ /** Telling the platform one thing. */
40
+ export type Tell = (told: Told) => Promise<void>
41
+
42
+ /** What this facet reads off the host: the graph, the vault the person's
43
+ * connection is kept in, and the person the config names. */
44
+ export type Hosting = {
45
+ graph: Pick<Graph, 'get' | 'apply' | 'read' | 'address'>
46
+ vault: Vault
47
+ config?: { person?: string }
48
+ }
49
+
50
+ /** The platform a tunnel's conversations are held on, unless the config says
51
+ * another. */
52
+ export let PLATFORM = 'https://yaks.app'
53
+
54
+ /** Where the platform hears its machine. */
55
+ export let TELL = '/api/tunnel'
56
+
57
+ let comp = (b: Bundle | undefined, name: string): Comp =>
58
+ (b?.[name] ?? {}) as Comp
59
+ let str = (v: unknown): string => typeof v == 'string' ? v : ''
60
+
61
+ /** What the knock `eid` tells the platform, or nothing where it is said
62
+ * already or is not at a session standing at this door for a conversation
63
+ * held with the machine's person (`session.person`). */
64
+ export let telling = async (
65
+ g: Pick<Graph, 'get'>,
66
+ eid: Eid,
67
+ ): Promise<Told | undefined> => {
68
+ let [knock] = await g.get([eid], ['knock', 'doc', 'notified'])
69
+ if (!knock?.knock || knock.notified) return
70
+ let [at] = await g.get([str(comp(knock, 'knock').target)], ['session'])
71
+ let session = comp(at, 'session')
72
+ let conversation = str(session.source)
73
+ // Only a conversation held with the machine's person is told: it is told
74
+ // through their own connection, and the platform holds nobody else's there.
75
+ if (session.door != DOOR || !conversation || !session.person) return
76
+ let about = str(comp(knock, 'knock').about)
77
+ let outcome = str(comp(knock, 'knock').outcome)
78
+ return {
79
+ conversation,
80
+ key: eid,
81
+ text: str(comp(knock, 'doc').body),
82
+ ...about ? { about } : {},
83
+ ...outcome ? { outcome } : {},
84
+ }
85
+ }
86
+
87
+ /** Tell the platform what the knock `eid` says, and mark it said. */
88
+ export let tellOf = async (
89
+ g: Pick<Graph, 'get' | 'apply'>,
90
+ tell: Tell,
91
+ eid: Eid,
92
+ ): Promise<void> => {
93
+ let told = await telling(g, eid)
94
+ if (!told) return
95
+ await tell(told)
96
+ await g.apply([{ entity: { eid }, notified: {} }], { trusted: true })
97
+ }
98
+
99
+ /** Telling the platform at `options.platform` as the config's person, through
100
+ * their connection to it. */
101
+ export let platformTell = (
102
+ host: Hosting,
103
+ options: Options = {},
104
+ fetching: typeof fetch = fetch,
105
+ ): Tell =>
106
+ (told) => post(host, options, { do: 'tell', ...told }, fetching)
107
+
108
+ export let platformReady = (
109
+ host: Hosting,
110
+ options: Options,
111
+ tunnel: string,
112
+ ): Promise<void> => post(host, options, { do: 'ready', tunnel }, fetch)
113
+
114
+ let post = async (
115
+ host: Hosting,
116
+ options: Options,
117
+ form: Record<string, string>,
118
+ fetching: typeof fetch,
119
+ ): Promise<void> => {
120
+ let origin = new URL(options.platform ?? PLATFORM)
121
+ let said = host.config?.person
122
+ if (!said) throw new Error('the tunnel tells its platform as nobody')
123
+ let owner = ((await host.graph.address([said])).get(said) ?? said) as Eid
124
+ let integration = origin.hostname == 'yaks.app' ? 'yaks.app' : origin.origin
125
+ let at = await accountCredential(host, owner, integration, options.as)
126
+ if (!at) throw new Error(`no ${integration} connection to tell it through`)
127
+ let r = await fetching(new URL(TELL, origin), {
128
+ method: 'POST',
129
+ headers: { authorization: `Bearer ${at.bearer}` },
130
+ body: new URLSearchParams(form),
131
+ })
132
+ if (r.ok) return void await r.body?.cancel()
133
+ let body = await r.text()
134
+ throw new Error(
135
+ `${origin.host} said ${r.status} to tunnel ${form.do}: ${body}`,
136
+ )
137
+ }
138
+
139
+ /** The effect behind `tunnel_tell`. */
140
+ export let effects = (host: Hosting, options: Options = {}): Handlers => ({
141
+ tunnel_tell: (e) =>
142
+ tellOf(host.graph, platformTell(host, options), e.entity.eid),
143
+ })
package/filter.js ADDED
@@ -0,0 +1,95 @@
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
+ /** What the caller this request is from was opened, on top of what every
16
+ * request through the tunnel is: the entry for the platform's word on it, or
17
+ * nothing. */ export let named = (callers = {}, req)=>{
18
+ let word = req.headers.get(CALLER) ?? '';
19
+ return Object.hasOwn(callers, word) ? callers[word] : {};
20
+ };
21
+ /** Whether the gateway marked this request: it came through the tunnel. */ export let marked = (req)=>req.headers.has(HEADER);
22
+ // Patterns depend on their pathname, not the mutable list of opened routes.
23
+ let patterns = new Map();
24
+ let pattern = (pathname)=>{
25
+ let found = patterns.get(pathname);
26
+ if (found) return found;
27
+ let compiled = new URLPattern({
28
+ pathname
29
+ });
30
+ patterns.set(pathname, compiled);
31
+ if (patterns.size > 256) patterns.delete(patterns.keys().next().value);
32
+ return compiled;
33
+ };
34
+ /** Whether the tunnel answers at `path`: `routes` are URLPattern pathnames
35
+ * (`/mail/inbound`, `/hooks/*`), and none opens nothing.
36
+ *
37
+ * ```ts
38
+ * import { assert } from '@std/assert'
39
+ * assert(opens(['/mail/inbound', '/hooks/*'], '/hooks/github'))
40
+ * assert(!opens(['/mail/inbound'], '/apply'))
41
+ * ```
42
+ */ export let opens = (routes = [], path)=>routes.some((pathname)=>pattern(pathname).test({
43
+ pathname: path
44
+ }));
45
+ /** A marked request at a path the machine did not open. Its name is the
46
+ * policy refusal's, so a server answers it 403. */ export class Closed extends Error {
47
+ name = 'Denied';
48
+ }
49
+ /** The machine's word on the tunnel: a marked request passes only at a path
50
+ * opened to every request (`routes`) or to the caller the platform says it is
51
+ * from (`callers`), and an unmarked one always does.
52
+ *
53
+ * ```ts
54
+ * import { assertThrows } from '@std/assert'
55
+ * import { CALLER, HEADER } from './gateway.ts'
56
+ * let only = filter(['/mail/inbound'], { operator: { routes: ['/mcp'] } })
57
+ * let through = (path: string, caller = 'app') =>
58
+ * new Request(`http://box${path}`, {
59
+ * headers: { [HEADER]: '1', [CALLER]: caller },
60
+ * })
61
+ * only(new Request('http://box/apply'))
62
+ * only(through('/mail/inbound'))
63
+ * only(through('/mcp', 'operator'))
64
+ * assertThrows(() => only(through('/mcp')))
65
+ * assertThrows(() => only(through('/apply', 'operator')))
66
+ * ```
67
+ */ export let filter = (routes = [], callers)=>(req)=>{
68
+ if (!marked(req)) return;
69
+ let { pathname } = new URL(req.url);
70
+ if (!opens(routes, pathname) && !opens(named(callers, req).routes, pathname)) {
71
+ throw new Closed(`the tunnel does not answer ${pathname}`);
72
+ }
73
+ };
74
+ /** The tools a request is offered, by name: for a marked request the ones the
75
+ * machine's owner named for every request (`tools`) and for the caller the
76
+ * platform says it is from (`callers`), and none names nothing; an unmarked
77
+ * request is not narrowed (`undefined`).
78
+ *
79
+ * ```ts
80
+ * import { assertEquals } from '@std/assert'
81
+ * import { CALLER, HEADER } from './gateway.ts'
82
+ * let tools = offered(['task_list'], { operator: { tools: ['task_new'] } })
83
+ * let through = (caller: string) =>
84
+ * new Request('http://box/mcp', {
85
+ * headers: { [HEADER]: '1', [CALLER]: caller },
86
+ * })
87
+ * assertEquals(tools(new Request('http://box/mcp')), undefined)
88
+ * assertEquals(tools(through('app')), ['task_list'])
89
+ * assertEquals(tools(through('operator')), ['task_list', 'task_new'])
90
+ * ```
91
+ */ export let offered = (tools = [], callers)=>(req)=>marked(req) ? [
92
+ ...tools,
93
+ ...named(callers, req).tools ?? []
94
+ ] : undefined;
95
+ //# sourceMappingURL=filter.js.map
package/filter.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter.js","sources":["./filter.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,2EAA2E;AAC3E,6EAA6E;AAC7E,8EAA8E;AAC9E,wEAAwE;AACxE,uEAAuE;AACvE,iEAAiE;AACjE,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,+EAA+E;AAC/E,yCAAyC;AACzC,SAAS,MAAM,EAAE,MAAM,uBAAsB;AAuB7C;;YAEY,GACZ,OAAO,IAAI,QAAQ,CAAC,UAAmB,CAAC,CAAC,EAAE;EACzC,IAAI,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW;EACtC,OAAO,OAAO,MAAM,CAAC,SAAS,QAAQ,OAAO,CAAC,KAAK,GAAG,CAAC;AACzD,EAAC;AAED,yEAAyE,GACzE,OAAO,IAAI,SAAS,CAAC,MAA0B,IAAI,OAAO,CAAC,GAAG,CAAC,QAAO;AAEtE,4EAA4E;AAC5E,IAAI,WAAW,IAAI;AACnB,IAAI,UAAU,C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