Line data Source code
1 : import type * as connection from '@ankoh/dashql-jsonschema/connection.js';
2 :
3 : /// Hosts of this machine, e.g. of `hyperd run --ui`
4 1 : const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
5 :
6 : /// A Hyper that a link points the app at, e.g. the hyperd of `hyperd run --ui`.
7 : /// The link is an app event, `?data=` with the base64url JSON `{"hyperLink": {"endpoint": ..., "token": ...}}`.
8 : export interface HyperLinkTarget {
9 : /// The base url of the HTTP v3 API of the Hyper
10 : endpoint: string;
11 : /// The bearer token of the Hyper
12 : token: string;
13 : }
14 :
15 : /// Parse the target of a Hyper link, null unless it names an endpoint and a token.
16 : /// An endpoint on this machine may speak http, any other endpoint must speak https.
17 1 : export function parseHyperLinkTarget(endpoint: string | null, token: string | null): HyperLinkTarget | null {
18 1 : if (endpoint == null || token == null || token.length === 0) return null;
19 1 : let url: URL;
20 1 : try {
21 1 : url = new URL(endpoint);
22 1 : } catch {
23 1 : return null;
24 1 : }
25 1 : if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))) return null;
26 1 : return { endpoint: url.origin, token };
27 1 : }
28 :
29 : /// Does the link point at a Hyper on this machine?
30 1 : export function isLoopbackHyperLink(target: HyperLinkTarget): boolean {
31 1 : return LOOPBACK_HOSTS.has(new URL(target.endpoint).hostname);
32 1 : }
33 :
34 : /// The params of the channel to the Hyper of a link, its HTTP v3 API with the token of the link
35 1 : export function hyperLinkChannelParams(params: connection.HyperConnectionParams, token: string): connection.HyperConnectionParams {
36 1 : return {
37 1 : ...params,
38 1 : protocol: 'V3_HTTP',
39 1 : metadata: {
40 1 : 'x-hyperdb-workload': 'dashql',
41 1 : ...params.metadata,
42 1 : authorization: `Bearer ${token}`,
43 1 : },
44 1 : };
45 1 : }
|