@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/routes.js ADDED
@@ -0,0 +1,94 @@
1
+ // The routes facet, exported as `@yaks/tunnel/routes`: the machine's end of a
2
+ // tunnel, imported by its `yak` wherever it serves `web`. Its server then
3
+ // answers a request the tunnel's gateway marked only at the paths the config
4
+ // opens (`routes`, URLPattern pathnames), and refuses the rest before any
5
+ // route sees them (./filter.ts). `/apply` and `/query` stay closed to the
6
+ // tunnel unless the machine's owner lists them; a request that did not come
7
+ // through the tunnel is untouched.
8
+ //
9
+ // A marked request is also never one of the machine's own callers. Whatever
10
+ // run it names, it writes `by` the persona the config names for the tunnel's
11
+ // callers and `via` a session standing here for the conversation it came from
12
+ // (its `x-via`, @yaks/session `standIn`), so what a hosted assistant does on
13
+ // the machine is recorded as that assistant's, and never as the machine's
14
+ // person or one of its agents: a `by` it sends a tool, asking for a mark
15
+ // recorded as somebody else's, is dropped from what it writes (@yaks/session
16
+ // `attributing`). And where an opened path lists and runs tools
17
+ // (`/mcp`), it is offered only the ones the config names (`tools`).
18
+ //
19
+ // The config's own `routes`, `tools` and `persona` are what every request
20
+ // through the tunnel gets, an app's worker in the space included. What only
21
+ // one kind of caller gets is under `callers`, by the platform's word for it
22
+ // (./gateway.ts `CALLER`): yaks.app says `operator` for the owner's Operator,
23
+ // `connector` for the owner's own assistant and `app` for an app's worker, so
24
+ // `callers.operator` holds the paths, tools and persona of the Operator alone.
25
+ //
26
+ // A conversation the platform says is held with the tunnel's `owner`
27
+ // (`x-yak-with`) is the machine's person's, and its session says so
28
+ // (`session.person`), so what is news to them is told to it (@yaks/session
29
+ // watch.ts) and passed back up the tunnel's platform (./effects.ts).
30
+ //
31
+ // One kind of marked request is the machine's person's own: one the platform
32
+ // says is the act of the person the config names as the tunnel's `owner`
33
+ // (`x-yak-by`, ./gateway.ts), which it does where a request carries that
34
+ // person's own words and nobody's reading of them. It writes `by` the
35
+ // config's `person` and `via` this process, as what they type at the
36
+ // machine's own page does, and never through a session: a comment written
37
+ // through a session is an agent's, to every reader of the graph. A request
38
+ // said to be anybody else's act is refused.
39
+ import { VIA } from "@yaks/api";
40
+ import { standIn } from "@yaks/session/who";
41
+ import { voice, wear } from "@yaks/persona";
42
+ import { Closed, filter as only, marked, named as opened, offered } from "./filter.js";
43
+ import { BY, WITH } from "./gateway.js";
44
+ /** The session a tunnel's callers stand in is named within this door. */ export let DOOR = 'tunnel';
45
+ /** The tunnel's filter, over the paths the config opens. */ export let filter = (_host, options = {})=>only(options.routes, options.callers);
46
+ // An entity the config names by eid, number or name, as its eid, addressed by
47
+ // the first marked request that needs it: the graph is open by then.
48
+ let naming = (host)=>{
49
+ let found = new Map();
50
+ let address = async (said, kind)=>(await host.graph.address([
51
+ said
52
+ ], kind)).get(said) ?? said;
53
+ return (said, kind)=>said ? found.get(said) ?? found.set(said, address(said, kind)).get(said) : undefined;
54
+ };
55
+ /** Who a request through the tunnel is from: the persona the config names for
56
+ * its caller, or else for every request, through the session standing for the
57
+ * conversation its `x-via` names. One the platform says is the own act of the
58
+ * tunnel's `owner` is from the config's `person`, through this process. */ export let arrived = (host, options = {})=>{
59
+ let named = naming(host);
60
+ return async (request)=>{
61
+ if (!marked(request)) return undefined;
62
+ let caller = opened(options.callers, request);
63
+ let own = request.headers.get(BY);
64
+ let owner = caller.owner ?? options.owner;
65
+ if (own == null) {
66
+ let mine = !!owner && request.headers.get(WITH) == owner;
67
+ return await standIn(host.graph, DOOR, request.headers.get(VIA) ?? '', await named(caller.persona ?? options.persona, 'persona'), mine ? await named(host.config?.person) : undefined);
68
+ }
69
+ let by = own == owner ? await named(host.config?.person) : undefined;
70
+ if (!by) {
71
+ throw new Closed("the tunnel writes as nobody but its machine's owner");
72
+ }
73
+ return {
74
+ by,
75
+ via: host.me
76
+ };
77
+ };
78
+ };
79
+ /** The tools a request through the tunnel is offered: the config's, for every
80
+ * request and for its caller. */ export let offers = (_host, options = {})=>offered(options.tools, options.callers);
81
+ /** What a request through the tunnel is told before a door's own
82
+ * instructions: the text of the persona it writes as, composed as every
83
+ * persona here is (@yaks/persona `wear` and `voice`), and read again for each
84
+ * request that asks, so an edit to it reaches the next one. A request that is
85
+ * the owner's own act writes as no persona, and is told none. */ export let told = (host, options = {})=>{
86
+ let named = naming(host);
87
+ return async (request)=>{
88
+ if (!marked(request) || request.headers.has(BY)) return undefined;
89
+ let persona = await named(opened(options.callers, request).persona ?? options.persona, 'persona');
90
+ let worn = persona && await wear(host.graph.storage, host.graph.vocab)(persona);
91
+ return worn ? voice(host.graph.vocab)(worn) : undefined;
92
+ };
93
+ };
94
+ //# sourceMappingURL=routes.js.map
package/routes.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sources":["./routes.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,0EAA0E;AAC1E,6EAA6E;AAC7E,0EAA0E;AAC1E,0EAA0E;AAC1E,4EAA4E;AAC5E,mCAAmC;AACnC,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,8EAA8E;AAC9E,6EAA6E;AAC7E,0EAA0E;AAC1E,yEAAyE;AACzE,6EAA6E;AAC7E,gEAAgE;AAChE,oEAAoE;AACpE,EAAE;AACF,0EAA0E;AAC1E,4EAA4E;AAC5E,4EAA4E;AAC5E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,EAAE;AACF,qEAAqE;AACrE,oEAAoE;AACpE,2EAA2E;AAC3E,qEAAqE;AACrE,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,yEAAyE;AACzE,sEAAsE;AACtE,qEAAqE;AACrE,0EAA0E;AAC1E,2EAA2E;AAC3E,4CAA4C;AAE5C,SAAS,GAAG,yBAA8B;AAE1C,SAAS,OAAO,iCAAsC;AACtD,SAAS,KAAK,EAAE,IAAI,6BAAkC;AACtD,SAEE,MAAM,EACN,UAAU,IAAI,EACd,MAAM,EACN,SAAS,MAAM,EACf,OAAO,sBAEW;AACpB,SAAS,EAAE,EAAE,IAAI,uBAAsB;AA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AAK,KAAK,EAAE;IAAC;EAC5B;AACF,EAAC;AAED;+BAC+B,GAC/B,OAAO,IAAI,SAAS,CAAC,OAAgB,UAAmB,CAAC,CAAC,GACxD,QAAQ,QAAQ,KAAK,EAAE,QAAQ,OAAO,EAAC;AAEzC;;;;+DAI+D,GAC/D,OAAO,IAAI,OAAO,CAAC,MAAe,UAAmB,CAAC,CAAC;EACrD,IAAI,QAAQ,OAAO;EACnB,OAAO,OAAO;IACZ,IAAI,CAAC,OAAO,YAAY,QAAQ,OAAO,CAAC,GAAG,CAAC,KAAK,OAAO;IACxD,IAAI,UAAU,MAAM,MAClB,OAAO,QAAQ,OAAO,EAAE,SAAS,OAAO,IAAI,QAAQ,OAAO,EAC3D;IAEF,IAAI,OAAO,WACT,MAAM,KAAK,KAAK,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,CAAC,KAAK,EAAE;IACnD,OAAO,OAAO,MAAM,KAAK,KAAK,CAAC,KAAK,EAAE,QAAQ;EAChD;AACF,EAAC"}
package/routes.ts ADDED
@@ -0,0 +1,144 @@
1
+ // The routes facet, exported as `@yaks/tunnel/routes`: the machine's end of a
2
+ // tunnel, imported by its `yak` wherever it serves `web`. Its server then
3
+ // answers a request the tunnel's gateway marked only at the paths the config
4
+ // opens (`routes`, URLPattern pathnames), and refuses the rest before any
5
+ // route sees them (./filter.ts). `/apply` and `/query` stay closed to the
6
+ // tunnel unless the machine's owner lists them; a request that did not come
7
+ // through the tunnel is untouched.
8
+ //
9
+ // A marked request is also never one of the machine's own callers. Whatever
10
+ // run it names, it writes `by` the persona the config names for the tunnel's
11
+ // callers and `via` a session standing here for the conversation it came from
12
+ // (its `x-via`, @yaks/session `standIn`), so what a hosted assistant does on
13
+ // the machine is recorded as that assistant's, and never as the machine's
14
+ // person or one of its agents: a `by` it sends a tool, asking for a mark
15
+ // recorded as somebody else's, is dropped from what it writes (@yaks/session
16
+ // `attributing`). And where an opened path lists and runs tools
17
+ // (`/mcp`), it is offered only the ones the config names (`tools`).
18
+ //
19
+ // The config's own `routes`, `tools` and `persona` are what every request
20
+ // through the tunnel gets, an app's worker in the space included. What only
21
+ // one kind of caller gets is under `callers`, by the platform's word for it
22
+ // (./gateway.ts `CALLER`): yaks.app says `operator` for the owner's Operator,
23
+ // `connector` for the owner's own assistant and `app` for an app's worker, so
24
+ // `callers.operator` holds the paths, tools and persona of the Operator alone.
25
+ //
26
+ // A conversation the platform says is held with the tunnel's `owner`
27
+ // (`x-yak-with`) is the machine's person's, and its session says so
28
+ // (`session.person`), so what is news to them is told to it (@yaks/session
29
+ // watch.ts) and passed back up the tunnel's platform (./effects.ts).
30
+ //
31
+ // One kind of marked request is the machine's person's own: one the platform
32
+ // says is the act of the person the config names as the tunnel's `owner`
33
+ // (`x-yak-by`, ./gateway.ts), which it does where a request carries that
34
+ // person's own words and nobody's reading of them. It writes `by` the
35
+ // config's `person` and `via` this process, as what they type at the
36
+ // machine's own page does, and never through a session: a comment written
37
+ // through a session is an agent's, to every reader of the graph. A request
38
+ // said to be anybody else's act is refused.
39
+ import type { Arrived, Offers, Told } from '@yaks/api'
40
+ import { VIA } from '@yaks/api'
41
+ import type { Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
42
+ import { standIn } from '@yaks/session/who'
43
+ import { voice, wear } from '@yaks/persona'
44
+ import {
45
+ type Callers,
46
+ Closed,
47
+ filter as only,
48
+ marked,
49
+ named as opened,
50
+ offered,
51
+ type Opened,
52
+ } from './filter.js'
53
+ import { BY, WITH } from './gateway.js'
54
+
55
+ /** What a config file can set for this facet: what every request through the
56
+ * tunnel is opened (without a persona it writes as nobody, through its
57
+ * session), and what each kind of caller is on top of that. */
58
+ export type Options = Opened & {
59
+ /** what one kind of caller is opened as well, by the platform's word for
60
+ * it: its paths and tools beside everyone's, and its own persona */
61
+ callers?: Callers
62
+ }
63
+
64
+ /** What this facet reads off the host: the graph a caller's session is kept
65
+ * in, the person the machine's config names, and its own process. */
66
+ export type Hosting = {
67
+ graph: Pick<Graph, 'address' | 'get' | 'apply' | 'storage' | 'vocab'>
68
+ config?: { person?: string }
69
+ me?: Eid
70
+ }
71
+
72
+ /** The session a tunnel's callers stand in is named within this door. */
73
+ export let DOOR = 'tunnel'
74
+
75
+ /** The tunnel's filter, over the paths the config opens. */
76
+ export let filter = (
77
+ _host: unknown,
78
+ options: Options = {},
79
+ ): (req: Request) => void => only(options.routes, options.callers)
80
+
81
+ // An entity the config names by eid, number or name, as its eid, addressed by
82
+ // the first marked request that needs it: the graph is open by then.
83
+ let naming = (host: Hosting) => {
84
+ let found = new Map<string, Promise<Eid>>()
85
+ let address = async (said: string, kind?: string) =>
86
+ ((await host.graph.address([said], kind)).get(said) ?? said) as Eid
87
+ return (said?: string, kind?: string) =>
88
+ said
89
+ ? found.get(said) ?? found.set(said, address(said, kind)).get(said)
90
+ : undefined
91
+ }
92
+
93
+ /** Who a request through the tunnel is from: the persona the config names for
94
+ * its caller, or else for every request, through the session standing for the
95
+ * conversation its `x-via` names. One the platform says is the own act of the
96
+ * tunnel's `owner` is from the config's `person`, through this process. */
97
+ export let arrived = (host: Hosting, options: Options = {}): Arrived => {
98
+ let named = naming(host)
99
+ return async (request) => {
100
+ if (!marked(request)) return undefined
101
+ let caller = opened(options.callers, request)
102
+ let own = request.headers.get(BY)
103
+ let owner = caller.owner ?? options.owner
104
+ if (own == null) {
105
+ let mine = !!owner && request.headers.get(WITH) == owner
106
+ return await standIn(
107
+ host.graph,
108
+ DOOR,
109
+ request.headers.get(VIA) ?? '',
110
+ await named(caller.persona ?? options.persona, 'persona'),
111
+ mine ? await named(host.config?.person) : undefined,
112
+ )
113
+ }
114
+ let by = own == owner ? await named(host.config?.person) : undefined
115
+ if (!by) {
116
+ throw new Closed("the tunnel writes as nobody but its machine's owner")
117
+ }
118
+ return { by, via: host.me }
119
+ }
120
+ }
121
+
122
+ /** The tools a request through the tunnel is offered: the config's, for every
123
+ * request and for its caller. */
124
+ export let offers = (_host: unknown, options: Options = {}): Offers =>
125
+ offered(options.tools, options.callers)
126
+
127
+ /** What a request through the tunnel is told before a door's own
128
+ * instructions: the text of the persona it writes as, composed as every
129
+ * persona here is (@yaks/persona `wear` and `voice`), and read again for each
130
+ * request that asks, so an edit to it reaches the next one. A request that is
131
+ * the owner's own act writes as no persona, and is told none. */
132
+ export let told = (host: Hosting, options: Options = {}): Told => {
133
+ let named = naming(host)
134
+ return async (request) => {
135
+ if (!marked(request) || request.headers.has(BY)) return undefined
136
+ let persona = await named(
137
+ opened(options.callers, request).persona ?? options.persona,
138
+ 'persona',
139
+ )
140
+ let worn = persona &&
141
+ await wear(host.graph.storage, host.graph.vocab)(persona)
142
+ return worn ? voice(host.graph.vocab)(worn) : undefined
143
+ }
144
+ }
package/service.js ADDED
@@ -0,0 +1,119 @@
1
+ import { command as processCommand } from "@yaks/process/command";
2
+ // The machine's end of a tunnel, as a duty: the module a machine's `yak`
3
+ // imports at `@yaks/tunnel/service` to keep its tunnel up for as long as the
4
+ // process that holds the role is (M-39540: one process at a time runs a
5
+ // service).
6
+ //
7
+ // The connector runs `cloudflared` with the tunnel's token and nothing else:
8
+ // the tunnel is configured from the account (./cloudflare.ts), so the machine
9
+ // needs no config file, no open port and no public address. The token rides
10
+ // in the connector's environment (`TUNNEL_TOKEN`), never its arguments, so no
11
+ // process listing shows it. A connector that exits is started again after a
12
+ // pause that grows while it keeps failing; the role ending stops it.
13
+ //
14
+ // The token is a secret the config names (`{"secret": "TUNNEL_TOKEN"}`), read
15
+ // from the vault by whoever composed the host. A config with no token has
16
+ // nothing to run, and the duty ends at once: a machine whose tunnel something
17
+ // else already runs leaves it out.
18
+ import { sleep } from "@yaks/fp";
19
+ import { platformReady } from "./effects.js";
20
+ /** What the connector is started with: run the account-configured tunnel,
21
+ * saying only warnings and failures. */ export let ARGS = [
22
+ 'tunnel',
23
+ '--no-autoupdate',
24
+ '--loglevel',
25
+ 'warn',
26
+ 'run'
27
+ ];
28
+ /** The most the pause before a restart grows to. */ export let MOST = 60_000;
29
+ /** `cloudflared` as a child of this process, its warnings on our stderr. */ export let spawned = (cmd, args, env)=>{
30
+ let child = processCommand(cmd, {
31
+ args,
32
+ env,
33
+ stdin: 'null',
34
+ stdout: 'null',
35
+ stderr: args.includes('json') ? 'piped' : 'inherit'
36
+ }).spawn();
37
+ return {
38
+ status: child.status,
39
+ ...args.includes('json') ? {
40
+ logs: child.stderr
41
+ } : {},
42
+ kill: ()=>{
43
+ try {
44
+ child.kill('SIGTERM');
45
+ } catch {
46
+ // already gone
47
+ }
48
+ }
49
+ };
50
+ };
51
+ let monitor = async (stream, ready)=>{
52
+ let tunnel = '', tail = '';
53
+ let decoder = new TextDecoder();
54
+ for await (let bytes of stream){
55
+ let lines = (tail + decoder.decode(bytes, {
56
+ stream: true
57
+ })).split('\n');
58
+ tail = lines.pop() ?? '';
59
+ for (let line of lines){
60
+ let event;
61
+ try {
62
+ event = JSON.parse(line);
63
+ } catch {
64
+ continue;
65
+ }
66
+ if (event.tunnelID) tunnel = event.tunnelID;
67
+ if (event.level == 'warn' || event.level == 'error') {
68
+ console.error(event.message);
69
+ }
70
+ if (tunnel && event.message == 'Registered tunnel connection') {
71
+ await ready(tunnel);
72
+ }
73
+ }
74
+ }
75
+ };
76
+ // The connector, kept up until the signal aborts.
77
+ let connector = async (options, signal, ready)=>{
78
+ let { token, cloudflared = 'cloudflared', spawn = spawned, pause = 1_000 } = options;
79
+ if (!token) return;
80
+ let wait = pause;
81
+ while(!signal.aborted){
82
+ let started = Date.now();
83
+ let args = ready ? [
84
+ 'tunnel',
85
+ '--no-autoupdate',
86
+ '--loglevel',
87
+ 'info',
88
+ '--logformat',
89
+ 'json',
90
+ 'run'
91
+ ] : ARGS;
92
+ let run = spawn(cloudflared, args, {
93
+ TUNNEL_TOKEN: token
94
+ });
95
+ let stop = ()=>run.kill();
96
+ signal.addEventListener('abort', stop, {
97
+ once: true
98
+ });
99
+ let logs = ready && run.logs && monitor(run.logs, ready);
100
+ let [{ code }] = await Promise.all([
101
+ run.status,
102
+ logs
103
+ ]);
104
+ signal.removeEventListener('abort', stop);
105
+ if (signal.aborted) return;
106
+ console.error(`cloudflared exited ${code}; starting it again`);
107
+ // A connector that stayed up a while failed for a new reason: start the
108
+ // pause over rather than make it wait out an old backoff.
109
+ if (Date.now() - started > MOST) wait = pause;
110
+ await sleep(wait, signal);
111
+ wait = Math.min(wait * 2, MOST);
112
+ }
113
+ };
114
+ /** Keep the tunnel up until the signal aborts; an already-aborted signal
115
+ * starts nothing. */ export let service = (host, options = {}, signal = AbortSignal.abort())=>connector(options, signal, host?.config?.person ? (tunnel)=>platformReady(host, options, tunnel).catch(async (error)=>{
116
+ if (host.report) await host.report(error);
117
+ else console.error('Could not announce tunnel readiness', error);
118
+ }) : undefined);
119
+ //# sourceMappingURL=service.js.map
package/service.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.js","sources":["./service.ts"],"names":[],"mappings":"AAAA,SAAS,WAAW,cAAc,qCAA0C;AAC5E,yEAAyE;AACzE,6EAA6E;AAC7E,wEAAwE;AACxE,YAAY;AACZ,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,8EAA8E;AAC9E,4EAA4E;AAC5E,qEAAqE;AACrE,EAAE;AACF,8EAA8E;AAC9E,0EAA0E;AAC1E,8EAA8E;AAC9E,mCAAmC;AAEnC,SAAS,KAAK,wBAA6B;AAC3C,SAGE,aAAa,uBACM;AA4BrB;sCACsC,GACtC,OAAO,IAAI,OAAO;EAAC;EAAU;EAAmB;EAAc;EAAQ;CAAM,CAAA;AAE5E,kDAAkD,GAClD,OAAO,IAAI,OAAO,OAAM;AAExB,0EAA0E,GAC1E,OAAO,IAAI,UAAiB,CAAC,KAAK,MAAM;EACtC,IAAI,QAAQ,eAAe,KAAK;IAC9B;IACA;IACA,OAAO;IACP,QAAQ;IACR,QAAQ,KAAK,QAAQ,CAAC,UAAU,UAAU;EAC5C,GAAG,KAAK;EACR,OAAO;IACL,QAAQ,MAAM,MAAM;IACpB,G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IACpD,IAAI,OAAO,SAAS,IAAI,IAAI,IAAI,QAAQ,IAAI,IAAI,EAAE;IAClD,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,MAAM,QAAQ,GAAG,CAAC;MAAC,IAAI,MAAM;MAAE;KAAK;IACrD,OAAO,mBAAmB,CAAC,SAAS;IACpC,IAAI,OAAO,OAAO,EAAE;IACpB,QAAQ,KAAK,CAAC,CAAC,mBAAmB,EAAE,KAAK,mBAAmB,CAAC;IAC7D,wEAAwE;IACxE,0DAA0D;IAC1D,IAAI,KAAK,GAAG,KAAK,UAAU,MAAM,OAAO;IACxC,MAAM,MAAM,MAAM;IAClB,OAAO,KAAK,GAAG,CAAC,OAAO,GAAG;EAC5B;AACF;AAEA;mBACmB,GACnB,OAAO,IAAI,UAAU,CACnB,MACA,UAAmB,CAAC,CAAC,EACrB,SAAsB,YAAY,KAAK,EAAE,GAEzC,UACE,SACA,QACA,MAAM,QAAQ,SACV,CAAC,SACD,cAAc,MAAM,SAAS,QAAQ,KAAK,CAAC,OAAO;MAChD,IAAI,KAAK,MAAM,EAAE,MAAM,KAAK,MAAM,CAAC;WAC9B,QAAQ,KAAK,CAAC,uCAAuC;IAC5D,KACA,WACL"}
package/service.ts ADDED
@@ -0,0 +1,164 @@
1
+ import { command as processCommand } from '@yaks/process/command'
2
+ // The machine's end of a tunnel, as a duty: the module a machine's `yak`
3
+ // imports at `@yaks/tunnel/service` to keep its tunnel up for as long as the
4
+ // process that holds the role is (M-39540: one process at a time runs a
5
+ // service).
6
+ //
7
+ // The connector runs `cloudflared` with the tunnel's token and nothing else:
8
+ // the tunnel is configured from the account (./cloudflare.ts), so the machine
9
+ // needs no config file, no open port and no public address. The token rides
10
+ // in the connector's environment (`TUNNEL_TOKEN`), never its arguments, so no
11
+ // process listing shows it. A connector that exits is started again after a
12
+ // pause that grows while it keeps failing; the role ending stops it.
13
+ //
14
+ // The token is a secret the config names (`{"secret": "TUNNEL_TOKEN"}`), read
15
+ // from the vault by whoever composed the host. A config with no token has
16
+ // nothing to run, and the duty ends at once: a machine whose tunnel something
17
+ // else already runs leaves it out.
18
+
19
+ import { sleep } from '@yaks/fp'
20
+ import {
21
+ type Hosting,
22
+ type Options as Platform,
23
+ platformReady,
24
+ } from './effects.js'
25
+
26
+ /** What a config file can set for this plugin. */
27
+ export type Options = Platform & {
28
+ /** the tunnel's token; with none, there is nothing to run */
29
+ token?: string
30
+ /** the `cloudflared` to run (default: the one on PATH) */
31
+ cloudflared?: string
32
+ /** the first pause, in ms, before a failed connector is started again */
33
+ pause?: number
34
+ /** how the connector is started; a test passes its own */
35
+ spawn?: Spawn
36
+ }
37
+
38
+ /** A started connector: when it ends, and how to end it. */
39
+ export type Running = {
40
+ status: Promise<{ code: number }>
41
+ kill: () => void
42
+ logs?: ReadableStream<Uint8Array>
43
+ }
44
+
45
+ /** Start `cmd` with `args` and `env` added to the environment. */
46
+ export type Spawn = (
47
+ cmd: string,
48
+ args: string[],
49
+ env: Record<string, string>,
50
+ ) => Running
51
+
52
+ /** What the connector is started with: run the account-configured tunnel,
53
+ * saying only warnings and failures. */
54
+ export let ARGS = ['tunnel', '--no-autoupdate', '--loglevel', 'warn', 'run']
55
+
56
+ /** The most the pause before a restart grows to. */
57
+ export let MOST = 60_000
58
+
59
+ /** `cloudflared` as a child of this process, its warnings on our stderr. */
60
+ export let spawned: Spawn = (cmd, args, env) => {
61
+ let child = processCommand(cmd, {
62
+ args,
63
+ env,
64
+ stdin: 'null',
65
+ stdout: 'null',
66
+ stderr: args.includes('json') ? 'piped' : 'inherit',
67
+ }).spawn()
68
+ return {
69
+ status: child.status,
70
+ ...args.includes('json') ? { logs: child.stderr } : {},
71
+ kill: () => {
72
+ try {
73
+ child.kill('SIGTERM')
74
+ } catch {
75
+ // already gone
76
+ }
77
+ },
78
+ }
79
+ }
80
+
81
+ let monitor = async (
82
+ stream: ReadableStream<Uint8Array>,
83
+ ready: (tunnel: string) => Promise<void>,
84
+ ) => {
85
+ let tunnel = '', tail = ''
86
+ let decoder = new TextDecoder()
87
+ for await (let bytes of stream) {
88
+ let lines = (tail + decoder.decode(bytes, { stream: true })).split('\n')
89
+ tail = lines.pop() ?? ''
90
+ for (let line of lines) {
91
+ let event: { message?: string; tunnelID?: string; level?: string }
92
+ try {
93
+ event = JSON.parse(line)
94
+ } catch {
95
+ continue
96
+ }
97
+ if (event.tunnelID) tunnel = event.tunnelID
98
+ if (event.level == 'warn' || event.level == 'error') {
99
+ console.error(event.message)
100
+ }
101
+ if (tunnel && event.message == 'Registered tunnel connection') {
102
+ await ready(tunnel)
103
+ }
104
+ }
105
+ }
106
+ }
107
+
108
+ // The connector, kept up until the signal aborts.
109
+ let connector = async (
110
+ options: Options,
111
+ signal: AbortSignal,
112
+ ready?: (tunnel: string) => Promise<void>,
113
+ ) => {
114
+ let { token, cloudflared = 'cloudflared', spawn = spawned, pause = 1_000 } =
115
+ options
116
+ if (!token) return
117
+ let wait = pause
118
+ while (!signal.aborted) {
119
+ let started = Date.now()
120
+ let args = ready
121
+ ? [
122
+ 'tunnel',
123
+ '--no-autoupdate',
124
+ '--loglevel',
125
+ 'info',
126
+ '--logformat',
127
+ 'json',
128
+ 'run',
129
+ ]
130
+ : ARGS
131
+ let run = spawn(cloudflared, args, { TUNNEL_TOKEN: token })
132
+ let stop = () => run.kill()
133
+ signal.addEventListener('abort', stop, { once: true })
134
+ let logs = ready && run.logs && monitor(run.logs, ready)
135
+ let [{ code }] = await Promise.all([run.status, logs])
136
+ signal.removeEventListener('abort', stop)
137
+ if (signal.aborted) return
138
+ console.error(`cloudflared exited ${code}; starting it again`)
139
+ // A connector that stayed up a while failed for a new reason: start the
140
+ // pause over rather than make it wait out an old backoff.
141
+ if (Date.now() - started > MOST) wait = pause
142
+ await sleep(wait, signal)
143
+ wait = Math.min(wait * 2, MOST)
144
+ }
145
+ }
146
+
147
+ /** Keep the tunnel up until the signal aborts; an already-aborted signal
148
+ * starts nothing. */
149
+ export let service = (
150
+ host: (Hosting & { report?: (error: unknown) => unknown }) | null,
151
+ options: Options = {},
152
+ signal: AbortSignal = AbortSignal.abort(),
153
+ ): Promise<void> =>
154
+ connector(
155
+ options,
156
+ signal,
157
+ host?.config?.person
158
+ ? (tunnel) =>
159
+ platformReady(host, options, tunnel).catch(async (error) => {
160
+ if (host.report) await host.report(error)
161
+ else console.error('Could not announce tunnel readiness', error)
162
+ })
163
+ : undefined,
164
+ )
package/vocab.js ADDED
@@ -0,0 +1,16 @@
1
+ // The component declarations, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/tunnel/vocab`. It reaches no network and no
3
+ // runtime, so loading the vocabulary loads nothing else.
4
+ import doc from './vocab.json' with {
5
+ type: 'json'
6
+ };
7
+ import manifest from './package.json' with {
8
+ type: 'json'
9
+ };
10
+ /** The tunnel vocabulary, in the form `loadVocab` accepts. */ export let tunnelDoc = doc;
11
+ /** What this package is: its manifest's description, the one place it is
12
+ * written, which a host stamps on each document here. */ export let description = manifest.description;
13
+ /** Every document this plugin declares. */ export let docs = [
14
+ tunnelDoc
15
+ ];
16
+ //# sourceMappingURL=vocab.js.map
package/vocab.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,yDAAyD;AAGzD,OAAO,SAAS,oBAAoB;EAAE,MAAM;AAAO,EAAC;AACpD,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,4DAA4D,GAC5D,OAAO,IAAI,YAAsB,IAAe;AAEhD;uDACuD,GACvD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,yCAAyC,GACzC,OAAO,IAAI,OAAmB;EAAC;CAAU,CAAA"}
package/vocab.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "$id": "urn:uuid:f4706590-f5e2-4e9f-b54a-ea1adb52753c",
3
+ "$vocabulary": {
4
+ "https://yak.sh/vocab/core": true
5
+ },
6
+ "title": "tunnel",
7
+ "$defs": {
8
+ "tunnel": {
9
+ "$id": "urn:uuid:c847d0d2-3696-4275-8c94-4094e71f8f83",
10
+ "component": true,
11
+ "journal": false,
12
+ "type": "object",
13
+ "wire": false,
14
+ "description": "the Cloudflare Tunnel that reaches a machine from this entity, and the Workers VPC Service the tunnel's gateway reaches it through",
15
+ "properties": {
16
+ "id": {
17
+ "$id": "urn:uuid:bc56c767-4f5e-44dc-b3a0-4a6f4a3b0e97",
18
+ "type": "string",
19
+ "stamped": true,
20
+ "description": "the tunnel's id in the account"
21
+ },
22
+ "service": {
23
+ "$id": "urn:uuid:cdd87c34-6662-4320-885c-a07f66054315",
24
+ "type": "string",
25
+ "stamped": true,
26
+ "description": "the VPC Service's id, which the tunnel's gateway is bound to"
27
+ },
28
+ "adopted": {
29
+ "$id": "urn:uuid:3983c2f9-7030-4ea1-92b5-d4f8f6b60309",
30
+ "type": "boolean",
31
+ "stamped": true,
32
+ "description": "made outside whatever keeps this record, which only records it: removing the record forgets the two ids and never removes or rotates what they name"
33
+ }
34
+ }
35
+ },
36
+ "tunnel_tell": {
37
+ "effect": true,
38
+ "created": [
39
+ "knock"
40
+ ],
41
+ "target": ".knock !notified .knock.target.session.door=tunnel",
42
+ "description": "tell the platform a tunnel's conversations are held on what a knock at the session standing here for one of them says, as the machine's person, and mark it said: the platform's assistant in that conversation hears it (yaks.app takes it in on its Operator's `machine` channel). A knock names what it tells, so it is told once"
43
+ },
44
+ "tunnel_trashed": {
45
+ "$id": "urn:uuid:ed78e3a7-a628-4359-932f-bbf7216e44fe",
46
+ "component": true,
47
+ "wire": false,
48
+ "journal": false,
49
+ "type": "object",
50
+ "description": "a space's tunnel is in the trash; its tunnel and service remain held until restored or its owner confirms a purge",
51
+ "properties": {
52
+ "at": {
53
+ "$id": "urn:uuid:c5f8f6e3-5d8a-497c-8fe5-aac281522f81",
54
+ "type": "string",
55
+ "format": "date-time",
56
+ "stamped": true,
57
+ "description": "when the tunnel was put in the trash"
58
+ }
59
+ }
60
+ }
61
+ }
62
+ }
package/vocab.ts ADDED
@@ -0,0 +1,17 @@
1
+ // The component declarations, and nothing else: the module a server or a
2
+ // browser page imports at `@yaks/tunnel/vocab`. It reaches no network and no
3
+ // runtime, so loading the vocabulary loads nothing else.
4
+
5
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
6
+ import doc from './vocab.json' with { type: 'json' }
7
+ import manifest from './package.json' with { type: 'json' }
8
+
9
+ /** The tunnel vocabulary, in the form `loadVocab` accepts. */
10
+ export let tunnelDoc: VocabDoc = doc as VocabDoc
11
+
12
+ /** What this package is: its manifest's description, the one place it is
13
+ * written, which a host stamps on each document here. */
14
+ export let description: string = manifest.description
15
+
16
+ /** Every document this plugin declares. */
17
+ export let docs: VocabDoc[] = [tunnelDoc]