@serfab/cadre-client 0.0.0-stage → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +228 -0
- package/README.md +130 -3
- package/dist/address.d.ts +45 -0
- package/dist/address.js +109 -0
- package/dist/address.js.map +1 -0
- package/dist/app-link/index.d.ts +16 -0
- package/dist/app-link/index.js +17 -0
- package/dist/app-link/index.js.map +1 -0
- package/dist/app-link/join-response.d.ts +31 -0
- package/dist/app-link/join-response.js +87 -0
- package/dist/app-link/join-response.js.map +1 -0
- package/dist/app-link/known-apps.d.ts +32 -0
- package/dist/app-link/known-apps.js +51 -0
- package/dist/app-link/known-apps.js.map +1 -0
- package/dist/app-link/link-request-store.d.ts +50 -0
- package/dist/app-link/link-request-store.js +101 -0
- package/dist/app-link/link-request-store.js.map +1 -0
- package/dist/app-link/links.d.ts +47 -0
- package/dist/app-link/links.js +76 -0
- package/dist/app-link/links.js.map +1 -0
- package/dist/app-link/recommend-links.d.ts +30 -0
- package/dist/app-link/recommend-links.js +33 -0
- package/dist/app-link/recommend-links.js.map +1 -0
- package/dist/app-link/recommendation-store.d.ts +54 -0
- package/dist/app-link/recommendation-store.js +99 -0
- package/dist/app-link/recommendation-store.js.map +1 -0
- package/dist/bootstrap.d.ts +106 -0
- package/dist/bootstrap.js +106 -0
- package/dist/bootstrap.js.map +1 -0
- package/dist/inbox.d.ts +10 -0
- package/dist/inbox.js +28 -0
- package/dist/inbox.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/invitation-text.d.ts +81 -0
- package/dist/invitation-text.js +80 -0
- package/dist/invitation-text.js.map +1 -0
- package/dist/lifecycle/background-runner.d.ts +94 -0
- package/dist/lifecycle/background-runner.js +278 -0
- package/dist/lifecycle/background-runner.js.map +1 -0
- package/dist/lifecycle/index.d.ts +9 -0
- package/dist/lifecycle/index.js +10 -0
- package/dist/lifecycle/index.js.map +1 -0
- package/dist/loader.d.ts +47 -0
- package/dist/loader.js +93 -0
- package/dist/loader.js.map +1 -0
- package/dist/model.d.ts +309 -0
- package/dist/model.js +22 -0
- package/dist/model.js.map +1 -0
- package/dist/node-code-text.d.ts +10 -0
- package/dist/node-code-text.js +30 -0
- package/dist/node-code-text.js.map +1 -0
- package/dist/result.d.ts +79 -0
- package/dist/result.js +84 -0
- package/dist/result.js.map +1 -0
- package/dist/sereus/client.d.ts +49 -0
- package/dist/sereus/client.js +420 -0
- package/dist/sereus/client.js.map +1 -0
- package/dist/sereus/edge-host.d.ts +22 -0
- package/dist/sereus/edge-host.js +61 -0
- package/dist/sereus/edge-host.js.map +1 -0
- package/dist/sereus/host.d.ts +57 -0
- package/dist/sereus/host.js +2 -0
- package/dist/sereus/host.js.map +1 -0
- package/dist/sereus/index.d.ts +8 -0
- package/dist/sereus/index.js +9 -0
- package/dist/sereus/index.js.map +1 -0
- package/dist/sereus/invitations.d.ts +16 -0
- package/dist/sereus/invitations.js +333 -0
- package/dist/sereus/invitations.js.map +1 -0
- package/dist/sereus/node-code.d.ts +52 -0
- package/dist/sereus/node-code.js +51 -0
- package/dist/sereus/node-code.js.map +1 -0
- package/dist/store.d.ts +27 -0
- package/dist/store.js +51 -0
- package/dist/store.js.map +1 -0
- package/dist/stores.d.ts +38 -0
- package/dist/stores.js +48 -0
- package/dist/stores.js.map +1 -0
- package/examples/README.md +20 -0
- package/examples/nativescript/cadrons-page.xml +24 -0
- package/examples/nativescript/cadrons-view-model.ts +68 -0
- package/examples/react-native/CadronList.tsx +204 -0
- package/examples/react-native/InvitationPanel.tsx +191 -0
- package/examples/react-native/useStore.ts +11 -0
- package/examples/svelte/CadronList.svelte +86 -0
- package/examples/svelte/InvitationPanel.svelte +97 -0
- package/package.json +65 -3
- package/src/address.ts +125 -0
- package/src/app-link/index.ts +45 -0
- package/src/app-link/join-response.ts +109 -0
- package/src/app-link/known-apps.ts +70 -0
- package/src/app-link/link-request-store.ts +129 -0
- package/src/app-link/links.ts +90 -0
- package/src/app-link/recommend-links.ts +49 -0
- package/src/app-link/recommendation-store.ts +132 -0
- package/src/bootstrap.ts +184 -0
- package/src/globals.d.ts +26 -0
- package/src/inbox.ts +36 -0
- package/src/index.ts +15 -0
- package/src/invitation-text.ts +156 -0
- package/src/lifecycle/background-runner.ts +363 -0
- package/src/lifecycle/index.ts +17 -0
- package/src/loader.ts +103 -0
- package/src/model.ts +327 -0
- package/src/node-code-text.ts +25 -0
- package/src/result.ts +131 -0
- package/src/sereus/client.ts +454 -0
- package/src/sereus/edge-host.ts +81 -0
- package/src/sereus/host.ts +56 -0
- package/src/sereus/index.ts +8 -0
- package/src/sereus/invitations.ts +359 -0
- package/src/sereus/node-code.ts +80 -0
- package/src/store.ts +61 -0
- package/src/stores.ts +62 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
Example (Svelte 5): beside an invitation the app has just minted: whether it is ready to hand
|
|
3
|
+
out, the machines it names (each address a checkbox; the unchecked ones it could name too, a
|
|
4
|
+
change re-encoding it through `invitations.rebootstrap`), and its QR code full screen on a click. Copy and adapt; it is not
|
|
5
|
+
built or published. The QR code here comes from the `qrcode` package (`toDataURL`).
|
|
6
|
+
Props as in the React Native example: `token` (encoded, after `invitations.withBootstrap`),
|
|
7
|
+
`link` (the text shared), `onRebootstrap(token)` (the person changed its addresses: the app
|
|
8
|
+
rebuilds the link from the new token and keeps it).
|
|
9
|
+
-->
|
|
10
|
+
<script lang="ts">
|
|
11
|
+
import QRCode from 'qrcode';
|
|
12
|
+
import { invitationReadinessStore, type FormationReadinessGap, type InvitationReadiness, type InvitationText } from '@serfab/cadre-client';
|
|
13
|
+
import type { CadreClient } from '@serfab/cadre-client/sereus';
|
|
14
|
+
|
|
15
|
+
const { client, token, link, onRebootstrap }:
|
|
16
|
+
{ client: CadreClient; token: string; link: string; onRebootstrap(token: string): void } = $props();
|
|
17
|
+
|
|
18
|
+
const readiness = $derived(invitationReadinessStore(client, token));
|
|
19
|
+
let details = $state<InvitationText | null>(null);
|
|
20
|
+
let open = $state(false);
|
|
21
|
+
let full = $state(false);
|
|
22
|
+
let qr = $state('');
|
|
23
|
+
|
|
24
|
+
$effect(() => { void QRCode.toDataURL(link, { margin: 2, width: 720 }).then(url => { qr = url; }); });
|
|
25
|
+
$effect(() => {
|
|
26
|
+
if (!open) return;
|
|
27
|
+
void client.invitations.describe(token, link).then(r => { if (r.ok) details = r.value; });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
async function toggle(addr: string, include: boolean) {
|
|
31
|
+
if (!details) return;
|
|
32
|
+
const now = details.addresses.map(a => a.addr);
|
|
33
|
+
const next = include ? [...now, addr] : now.filter(a => a !== addr);
|
|
34
|
+
if (next.length === 0) return;
|
|
35
|
+
const r = await client.invitations.rebootstrap(token, next);
|
|
36
|
+
if (r.ok) onRebootstrap(r.value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const READINESS: Record<InvitationReadiness['state'], string> = {
|
|
40
|
+
ready: 'Ready to hand out: your machine can answer even while this device sleeps.',
|
|
41
|
+
waiting: 'Not ready to hand out yet: no other machine of yours can let them in on its own.',
|
|
42
|
+
'no-cadron': 'Only this device can answer it: keep the app open until they join, or add a machine that stays on.',
|
|
43
|
+
spent: 'This invitation can no longer be used: it has expired, or it has been used up. Make a new one.',
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// Each thing a machine can still be missing, as the step the person is waiting for. Phrased
|
|
47
|
+
// without a subject: `missing` is the union over every machine the invitation names.
|
|
48
|
+
const MISSING: Record<FormationReadinessGap, string> = {
|
|
49
|
+
'invitation-record': 'being told about this invitation',
|
|
50
|
+
'strand-record': 'being told about the conversation',
|
|
51
|
+
'membership-key': 'a key for the conversation, to sign your guest in',
|
|
52
|
+
'strand-runtime': 'running the conversation',
|
|
53
|
+
'strand-database': 'its own copy of the conversation',
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// Why it is not ready, when the machines said: a person waiting wants the reason, not a spinner.
|
|
57
|
+
const detail = $derived($readiness.state !== 'waiting' ? null
|
|
58
|
+
: $readiness.missing.length === 0 ? 'None of the machines it names has answered: one may be offline, or still starting.'
|
|
59
|
+
: `Still needed on the machines it names: ${$readiness.missing.map(gap => MISSING[gap]).join('; ')}.`);
|
|
60
|
+
</script>
|
|
61
|
+
|
|
62
|
+
{#if qr}
|
|
63
|
+
<button class="qr" onclick={() => { full = true; }} aria-label="Enlarge the QR code"><img src={qr} alt="Invitation QR code" width="180" /></button>
|
|
64
|
+
{/if}
|
|
65
|
+
<p class:ready={$readiness.state === 'ready'} class:spent={$readiness.state === 'spent'}>{READINESS[$readiness.state]}</p>
|
|
66
|
+
{#if detail}<p class="muted">{detail}</p>{/if}
|
|
67
|
+
|
|
68
|
+
<button class="link" onclick={() => { open = !open; }}>{open ? 'Hide the details' : "What's in this invitation"}</button>
|
|
69
|
+
{#if open && details}
|
|
70
|
+
{#each details.cadrons as c (c.peerId)}
|
|
71
|
+
<p><strong>{c.thisDevice ? 'This device' : c.label}</strong>
|
|
72
|
+
<span class="muted">{c.thisDevice ? '' : c.yours === false ? 'Not one of your machines' : 'Your machine'}{c.presence ? ` · ${c.presence}` : ''}</span></p>
|
|
73
|
+
{#each c.addresses as a (a.addr)}
|
|
74
|
+
<label class:muted={!a.reachesAnywhere}>
|
|
75
|
+
<input type="checkbox" checked={a.included} onchange={() => toggle(a.addr, !a.included)} />
|
|
76
|
+
{a.kind ?? 'not usable by a phone'}{a.via === 'wss' ? ', secure' : ''} ·
|
|
77
|
+
{a.via === 'relay' ? `through relay ${a.host}` : `${a.host}, port ${a.port ?? '?'}`}
|
|
78
|
+
</label>
|
|
79
|
+
{/each}
|
|
80
|
+
{/each}
|
|
81
|
+
<p class="muted">Expires {new Date(details.expiresAt).toLocaleString()} · link {details.linkLength} characters</p>
|
|
82
|
+
{/if}
|
|
83
|
+
|
|
84
|
+
{#if full}
|
|
85
|
+
<button class="full" onclick={() => { full = false; }} aria-label="Close"><img src={qr} alt="Invitation QR code" /></button>
|
|
86
|
+
{/if}
|
|
87
|
+
|
|
88
|
+
<style>
|
|
89
|
+
.qr, .link, .full { background: none; border: 0; padding: 0; cursor: pointer; }
|
|
90
|
+
.link { color: #0066cc; }
|
|
91
|
+
.ready { color: #2c8a3f; }
|
|
92
|
+
.spent { color: #b3261e; }
|
|
93
|
+
.muted { color: #777; }
|
|
94
|
+
label { display: block; }
|
|
95
|
+
.full { position: fixed; inset: 0; background: #fff; display: grid; place-items: center; }
|
|
96
|
+
.full img { width: min(90vw, 90vh); height: auto; }
|
|
97
|
+
</style>
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@serfab/cadre-client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Cadre management for Sereus apps, without UI: cadrons (the cadre's machines), claiming a node by its code, owner key backup, relays, reachability, and which cadrons an invitation names",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"dist",
|
|
11
|
+
"examples",
|
|
12
|
+
"ADOPTING.md",
|
|
13
|
+
"!**/*.tsbuildinfo"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./sereus": {
|
|
21
|
+
"types": "./dist/sereus/index.d.ts",
|
|
22
|
+
"import": "./dist/sereus/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./app-link": {
|
|
25
|
+
"types": "./dist/app-link/index.d.ts",
|
|
26
|
+
"import": "./dist/app-link/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./lifecycle": {
|
|
29
|
+
"types": "./dist/lifecycle/index.d.ts",
|
|
30
|
+
"import": "./dist/lifecycle/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./package.json": "./package.json"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://github.com/gotchoices/sereus.git",
|
|
37
|
+
"directory": "packages/cadre-client"
|
|
38
|
+
},
|
|
39
|
+
"keywords": [
|
|
40
|
+
"sereus",
|
|
41
|
+
"cadre",
|
|
42
|
+
"cadron",
|
|
43
|
+
"invitation"
|
|
44
|
+
],
|
|
45
|
+
"scripts": {
|
|
46
|
+
"clean": "rimraf dist",
|
|
47
|
+
"build": "tsc -p tsconfig.build.json",
|
|
48
|
+
"typecheck": "tsc -p tsconfig.typecheck.json --noEmit",
|
|
49
|
+
"test": "vitest run",
|
|
50
|
+
"dev:test": "vitest"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@multiformats/multiaddr": "^13.0.3",
|
|
54
|
+
"uint8arrays": "^6.1.1"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@serfab/cadre-core": "^2.1.0"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@serfab/cadre-core": "^2.1.0",
|
|
61
|
+
"@types/node": "^25.0.10",
|
|
62
|
+
"rimraf": "^6.1.2",
|
|
63
|
+
"typescript": "^5.9.3",
|
|
64
|
+
"vitest": "^4.0.17"
|
|
65
|
+
},
|
|
66
|
+
"author": "Got Choices Foundation",
|
|
67
|
+
"license": "MIT"
|
|
6
68
|
}
|
package/src/address.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Judging an address for a phone dialing it: from anywhere, only on the same network, or not at
|
|
3
|
+
* all. Parsed with `@multiformats/multiaddr`; the private-range check is a small built-in one, so
|
|
4
|
+
* this entry point loads no stack code.
|
|
5
|
+
*/
|
|
6
|
+
import { multiaddr } from '@multiformats/multiaddr';
|
|
7
|
+
import type { NodeReach } from './model.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* How far an address reaches for a phone dialing it, as cadre-core's `classifyDialAddress` judges
|
|
11
|
+
* it, with one difference (below):
|
|
12
|
+
*
|
|
13
|
+
* - `relay`: through a relay (`/p2p-circuit`) reached over a WebSocket, from anywhere while the
|
|
14
|
+
* reservation holds;
|
|
15
|
+
* - `webrtc`: a relay hop then WebRTC, from anywhere only if ICE finds a path;
|
|
16
|
+
* - `name` / `public`: a DNS name or public IP with a WebSocket, from anywhere;
|
|
17
|
+
* - `private`: a private-network IP, only from the same network;
|
|
18
|
+
* - `loopback`: the machine itself, never from another one.
|
|
19
|
+
*
|
|
20
|
+
* Null when no phone can dial it at all: plain TCP (phones dial WebSocket and relays only), a
|
|
21
|
+
* relay reached over plain TCP, the unspecified address, or anything unparsable. The relay hop is
|
|
22
|
+
* the difference: `classifyDialAddress` calls any relayed address `relay`.
|
|
23
|
+
*/
|
|
24
|
+
export type CadronAddressKind = 'relay' | 'webrtc' | 'name' | 'public' | 'private' | 'loopback';
|
|
25
|
+
|
|
26
|
+
interface Component { name: string; value?: string }
|
|
27
|
+
|
|
28
|
+
/** The address's components, or null when it does not parse. */
|
|
29
|
+
export function addressComponents(addr: string): Component[] | null {
|
|
30
|
+
try {
|
|
31
|
+
return multiaddr(addr).getComponents().map(c => ({ name: c.name, value: c.value }));
|
|
32
|
+
} catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const DNS = new Set(['dns', 'dns4', 'dns6', 'dnsaddr']);
|
|
38
|
+
const hasWebSocket = (components: Component[]) => components.some(c => c.name === 'ws' || c.name === 'wss');
|
|
39
|
+
|
|
40
|
+
export function addressKind(addr: string): CadronAddressKind | null {
|
|
41
|
+
const components = addressComponents(addr);
|
|
42
|
+
if (!components) return null;
|
|
43
|
+
const circuit = components.findIndex(c => c.name === 'p2p-circuit');
|
|
44
|
+
if (circuit >= 0) {
|
|
45
|
+
// The hop to the relay is dialed like any other address: a phone reaches a relay over a
|
|
46
|
+
// WebSocket only, never plain TCP.
|
|
47
|
+
if (!hasWebSocket(components.slice(0, circuit))) return null;
|
|
48
|
+
return components.slice(circuit + 1).some(c => c.name === 'webrtc') ? 'webrtc' : 'relay';
|
|
49
|
+
}
|
|
50
|
+
if (!hasWebSocket(components)) return null;
|
|
51
|
+
return hostKind(components[0]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function hostKind(host: Component | undefined): CadronAddressKind | null {
|
|
55
|
+
if (!host?.value) return null;
|
|
56
|
+
if (DNS.has(host.name)) return host.value === 'localhost' ? 'loopback' : 'name';
|
|
57
|
+
if (host.name === 'ip4') {
|
|
58
|
+
if (host.value === '0.0.0.0') return null;
|
|
59
|
+
if (host.value.startsWith('127.')) return 'loopback';
|
|
60
|
+
return isPrivateIp4(host.value) ? 'private' : 'public';
|
|
61
|
+
}
|
|
62
|
+
if (host.name === 'ip6') {
|
|
63
|
+
const ip = host.value.toLowerCase();
|
|
64
|
+
if (ip === '::') return null;
|
|
65
|
+
if (ip === '::1') return 'loopback';
|
|
66
|
+
return isPrivateIp6(ip) ? 'private' : 'public';
|
|
67
|
+
}
|
|
68
|
+
return host.name === 'ip6zone' ? 'private' : null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Reaches from anywhere: what an invitation should name. */
|
|
72
|
+
export function reachesAnywhere(kind: CadronAddressKind | null): boolean {
|
|
73
|
+
return kind === 'name' || kind === 'public' || kind === 'relay' || kind === 'webrtc';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Best first for an invitation: a direct name or public address, then a relay, then WebRTC, then private. */
|
|
77
|
+
export const ADDRESS_KIND_RANK: Record<CadronAddressKind, number> = { name: 0, public: 0, relay: 1, webrtc: 2, private: 3, loopback: 4 };
|
|
78
|
+
|
|
79
|
+
/** `anywhere` when at least one address names a public IP or a DNS name, else `home-network`. */
|
|
80
|
+
export function nodeReach(multiaddrs: readonly string[]): NodeReach {
|
|
81
|
+
return multiaddrs.some(isPublicAddress) ? 'anywhere' : 'home-network';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The address's host is a DNS name or a public IP. The host is its first component, so a relayed
|
|
86
|
+
* address is judged by its relay.
|
|
87
|
+
*/
|
|
88
|
+
export function isPublicAddress(addr: string): boolean {
|
|
89
|
+
const kind = hostKind(addressComponents(addr)?.[0]);
|
|
90
|
+
return kind === 'name' || kind === 'public';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function isPrivateIp4(ip: string): boolean {
|
|
94
|
+
const o = ip.split('.').map(Number);
|
|
95
|
+
if (o.length !== 4 || o.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return true; // unparsable: not public
|
|
96
|
+
const [a, b] = o;
|
|
97
|
+
return a === 10 || a === 127 || a === 0
|
|
98
|
+
|| (a === 172 && b >= 16 && b <= 31)
|
|
99
|
+
|| (a === 192 && b === 168)
|
|
100
|
+
|| (a === 169 && b === 254)
|
|
101
|
+
|| (a === 100 && b >= 64 && b <= 127); // carrier-grade NAT, Tailscale
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isPrivateIp6(ip: string): boolean {
|
|
105
|
+
if (ip.startsWith('::ffff:')) return isPrivateIp4(ip.slice(7));
|
|
106
|
+
const first = parseInt(ip.split(':')[0] || '0', 16);
|
|
107
|
+
return (first & 0xfe00) === 0xfc00 // fc00::/7 unique local
|
|
108
|
+
|| (first & 0xffc0) === 0xfe80; // fe80::/10 link local
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A name for a machine from its addresses: the first DNS host it is reached at directly
|
|
113
|
+
* (`server.example.com`), or null. A relayed address names the relay, not the machine, so it is skipped;
|
|
114
|
+
* so is `localhost`. For the claim prompt ("Add server.example.com?"), a row's subtitle, and the name
|
|
115
|
+
* dialog's starting text.
|
|
116
|
+
*/
|
|
117
|
+
export function suggestedName(machine: { addresses: readonly string[] }): string | null {
|
|
118
|
+
for (const addr of machine.addresses) {
|
|
119
|
+
const components = addressComponents(addr);
|
|
120
|
+
if (!components || components.some(c => c.name === 'p2p-circuit')) continue;
|
|
121
|
+
const host = components[0];
|
|
122
|
+
if (host && DNS.has(host.name) && host.value && host.value !== 'localhost') return host.value;
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@serfab/cadre-client/app-link` — what two Sereus apps on one device need to hand a join request
|
|
3
|
+
* and its answer to each other by opening each other with a link, and for one to recommend another.
|
|
4
|
+
* See docs/cadre/apps.md → "Between apps on one phone".
|
|
5
|
+
*
|
|
6
|
+
* Platform-neutral: the app passes its platform's pieces in (`Linking.canOpenURL` on React Native,
|
|
7
|
+
* a storage slot), so this runs anywhere, a Node test included. Listening for incoming links and
|
|
8
|
+
* registering the URL schemes stay with the platform (on React Native, `@serfab/cadre-rn`'s config
|
|
9
|
+
* plugin and the app's linking handler).
|
|
10
|
+
*/
|
|
11
|
+
export { installedSereusApps, KNOWN_SEREUS_APPS, type SereusApp } from './known-apps.js';
|
|
12
|
+
export {
|
|
13
|
+
CADRE_JOIN_RESPONSE_PREFIX,
|
|
14
|
+
decodeCadreJoinResponse,
|
|
15
|
+
encodeCadreJoinResponse,
|
|
16
|
+
type CadreJoinResponse,
|
|
17
|
+
type JoinRefusal,
|
|
18
|
+
} from './join-response.js';
|
|
19
|
+
export {
|
|
20
|
+
CADRE_LINK_MAX_LENGTH,
|
|
21
|
+
CadreLinkTooLongError,
|
|
22
|
+
joinRequestLink,
|
|
23
|
+
joinResponseLink,
|
|
24
|
+
parseCadreLink,
|
|
25
|
+
recommendedByLink,
|
|
26
|
+
type CadreLink,
|
|
27
|
+
} from './links.js';
|
|
28
|
+
export {
|
|
29
|
+
LINK_REQUEST_TTL_MS,
|
|
30
|
+
LinkRequestStore,
|
|
31
|
+
UnsolicitedJoinResponseError,
|
|
32
|
+
type OpenLinkRequest,
|
|
33
|
+
} from './link-request-store.js';
|
|
34
|
+
export {
|
|
35
|
+
AppRecommendationStore,
|
|
36
|
+
RECOMMENDATION_TTL_MS,
|
|
37
|
+
type AppRecommendation,
|
|
38
|
+
} from './recommendation-store.js';
|
|
39
|
+
export {
|
|
40
|
+
RECOMMENDED_BY_REFERRER_PREFIX,
|
|
41
|
+
recommendedByReferrer,
|
|
42
|
+
recommendedBySchemeFromReferrer,
|
|
43
|
+
storePageLink,
|
|
44
|
+
type StorePlatform,
|
|
45
|
+
} from './recommend-links.js';
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The join response: the owner app's answer to a join request that arrived as a link, carried in
|
|
3
|
+
* the link it opens back to the asking app. Either an invitation targeted at the request's peer
|
|
4
|
+
* id or the reason there is none.
|
|
5
|
+
*
|
|
6
|
+
* `sereus-join-response:1.<base64url of canonical JSON>`, the join request's own encoding. The
|
|
7
|
+
* nonce is the request's `reply.nonce`, so the asking app takes only an answer to a request it
|
|
8
|
+
* has open (`LinkRequestStore.take`). Nothing in it is signed: `appName` is what the answering
|
|
9
|
+
* app calls itself, for the asking app's messages only.
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
CADRE_INVITATION_PREFIX,
|
|
13
|
+
CADRE_JOIN_REQUEST_MAX_APP_NAME,
|
|
14
|
+
CADRE_JOIN_REQUEST_PREFIX,
|
|
15
|
+
canonicalJson,
|
|
16
|
+
} from '@serfab/cadre-core';
|
|
17
|
+
import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
|
|
18
|
+
|
|
19
|
+
/** Version 1 of the join response; the only one either side reads. */
|
|
20
|
+
export const CADRE_JOIN_RESPONSE_PREFIX = 'sereus-join-response:1.';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Why the owner app minted no invitation: the user declined (`denied`), it has no cadre
|
|
24
|
+
* (`no-cadre`), it is not an owner of its cadre (`not-owner`), or the request's peer id is
|
|
25
|
+
* already a member (`already-member`).
|
|
26
|
+
*/
|
|
27
|
+
export type JoinRefusal = 'denied' | 'no-cadre' | 'not-owner' | 'already-member';
|
|
28
|
+
|
|
29
|
+
const JOIN_REFUSALS: readonly string[] = ['denied', 'no-cadre', 'not-owner', 'already-member'] satisfies JoinRefusal[];
|
|
30
|
+
|
|
31
|
+
export type CadreJoinResponse =
|
|
32
|
+
/** `invitation` is an encoded `sereus-invite:1.` text; the asking app's join decodes it fully. */
|
|
33
|
+
| { v: 1; nonce: string; appName: string; invitation: string }
|
|
34
|
+
| { v: 1; nonce: string; appName: string; refused: JoinRefusal };
|
|
35
|
+
|
|
36
|
+
/** Encode a response as the text the owner app's link carries. Refuses what {@link decodeCadreJoinResponse} would. */
|
|
37
|
+
export function encodeCadreJoinResponse(response: CadreJoinResponse): string {
|
|
38
|
+
const json = canonicalJson(requireCadreJoinResponse(response));
|
|
39
|
+
return `${CADRE_JOIN_RESPONSE_PREFIX}${uint8ArrayToString(new TextEncoder().encode(json), 'base64url')}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Decode the text an answering link carried. Refuses, naming the problem: a join request,
|
|
44
|
+
* any prefix but version 1's, a body that is not base64url JSON of the response's shape, an
|
|
45
|
+
* empty nonce, an `appName` that is empty or longer than 64 characters once trimmed, an
|
|
46
|
+
* `invitation` that is not an invitation's text, an unknown refusal, and both or neither of
|
|
47
|
+
* `invitation` and `refused`.
|
|
48
|
+
*/
|
|
49
|
+
export function decodeCadreJoinResponse(text: string): CadreJoinResponse {
|
|
50
|
+
const trimmed = text.trim();
|
|
51
|
+
if (trimmed.startsWith(CADRE_JOIN_REQUEST_PREFIX)) {
|
|
52
|
+
throw new Error('This is a join request, not the answer to one');
|
|
53
|
+
}
|
|
54
|
+
if (!trimmed.startsWith(CADRE_JOIN_RESPONSE_PREFIX)) {
|
|
55
|
+
throw new Error(`A join response must start with "${CADRE_JOIN_RESPONSE_PREFIX}" (this one starts with "${trimmed.slice(0, CADRE_JOIN_RESPONSE_PREFIX.length)}")`);
|
|
56
|
+
}
|
|
57
|
+
let parsed: unknown;
|
|
58
|
+
try {
|
|
59
|
+
parsed = JSON.parse(new TextDecoder().decode(uint8ArrayFromString(trimmed.slice(CADRE_JOIN_RESPONSE_PREFIX.length), 'base64url')));
|
|
60
|
+
} catch (error) {
|
|
61
|
+
throw new Error('A join response must carry base64url-encoded JSON after its prefix', { cause: error });
|
|
62
|
+
}
|
|
63
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
64
|
+
throw new Error('A join response must decode to a JSON object');
|
|
65
|
+
}
|
|
66
|
+
const { v, nonce, appName, invitation, refused } = parsed as Record<string, unknown>;
|
|
67
|
+
if (v !== 1) throw new Error(`A join response must be version 1 (this one says ${JSON.stringify(v)})`);
|
|
68
|
+
if (typeof nonce !== 'string') throw new Error('A join response must carry its request\'s nonce');
|
|
69
|
+
if (typeof appName !== 'string') throw new Error('A join response must carry the answering app\'s name');
|
|
70
|
+
if (invitation !== undefined && typeof invitation !== 'string') throw new Error('A join response\'s invitation must be text');
|
|
71
|
+
if (refused !== undefined && typeof refused !== 'string') throw new Error('A join response\'s refusal must be text');
|
|
72
|
+
return requireCadreJoinResponse({ nonce, appName, invitation, refused });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A response's fields before the shape rules settle which of the two kinds it is. */
|
|
76
|
+
interface ResponseFields {
|
|
77
|
+
nonce: string;
|
|
78
|
+
appName: string;
|
|
79
|
+
invitation?: string;
|
|
80
|
+
refused?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The shape rules both directions apply. Returns the response with its name trimmed. */
|
|
84
|
+
function requireCadreJoinResponse(fields: ResponseFields): CadreJoinResponse {
|
|
85
|
+
const { nonce, invitation, refused } = fields;
|
|
86
|
+
if (nonce.length === 0) throw new Error('A join response must carry its request\'s nonce');
|
|
87
|
+
const appName = fields.appName.trim();
|
|
88
|
+
if (appName.length === 0) throw new Error('A join response must name the answering app');
|
|
89
|
+
if (appName.length > CADRE_JOIN_REQUEST_MAX_APP_NAME) {
|
|
90
|
+
throw new Error(`A join response's app name must be at most ${CADRE_JOIN_REQUEST_MAX_APP_NAME} characters (this one has ${appName.length})`);
|
|
91
|
+
}
|
|
92
|
+
if ((invitation === undefined) === (refused === undefined)) {
|
|
93
|
+
throw new Error('A join response must carry exactly one of an invitation and a refusal');
|
|
94
|
+
}
|
|
95
|
+
if (invitation !== undefined) {
|
|
96
|
+
if (!invitation.startsWith(CADRE_INVITATION_PREFIX)) {
|
|
97
|
+
throw new Error(`A join response's invitation must start with "${CADRE_INVITATION_PREFIX}"`);
|
|
98
|
+
}
|
|
99
|
+
return { v: 1, nonce, appName, invitation };
|
|
100
|
+
}
|
|
101
|
+
if (!isJoinRefusal(refused)) {
|
|
102
|
+
throw new Error(`A join response's refusal must be one of ${JOIN_REFUSALS.join(', ')} (this one is ${JSON.stringify(refused)})`);
|
|
103
|
+
}
|
|
104
|
+
return { v: 1, nonce, appName, refused };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function isJoinRefusal(value: string | undefined): value is JoinRefusal {
|
|
108
|
+
return value !== undefined && JOIN_REFUSALS.includes(value);
|
|
109
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Sereus apps one app can open at their own URL scheme, and the lookup of which of them are
|
|
3
|
+
* installed. iOS has no app chooser for a scheme several apps register, so an app asking to join
|
|
4
|
+
* opens one owner app by that app's own scheme, chosen from this list.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A Sereus app another can open at its own URL scheme. */
|
|
8
|
+
export interface SereusApp {
|
|
9
|
+
/** The name the asking app shows in its list of owner apps. */
|
|
10
|
+
name: string;
|
|
11
|
+
/** The app's own custom URL scheme (`expo.scheme`), lowercase. */
|
|
12
|
+
scheme: string;
|
|
13
|
+
/** The app's Play application id, for its store page; absent while it is not on Play. */
|
|
14
|
+
androidPackage?: string;
|
|
15
|
+
/** The app's numeric App Store id, for its store page; absent while it is not on the App Store. */
|
|
16
|
+
iosAppStoreId?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The Sereus apps the kit knows; one entry per published app. A new app is added here by a pull
|
|
21
|
+
* request and a kit release; until then an app passes it as an extra (`appLinks.extraApps` in
|
|
22
|
+
* the config plugin, and the `apps` argument of {@link installedSereusApps}).
|
|
23
|
+
*
|
|
24
|
+
* `app.plugin.cjs` keeps a copy (`withCadre.KNOWN_SEREUS_APPS`), because the CommonJS plugin
|
|
25
|
+
* cannot load this ESM build; `test/app-link/app-link.spec.ts` keeps the two equal.
|
|
26
|
+
*/
|
|
27
|
+
export const KNOWN_SEREUS_APPS: readonly SereusApp[] = [
|
|
28
|
+
{ name: 'Sereus P2P Chat', scheme: 'sereus-chat' },
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The apps in `apps` that `canOpenURL('<scheme>://')` reports installed, minus `ownScheme`, in
|
|
33
|
+
* the order given and one per scheme. For iOS, where each queried scheme must be listed in
|
|
34
|
+
* `LSApplicationQueriesSchemes`: React Native's `canOpenURL` rejects for a scheme that is not, and
|
|
35
|
+
* such an app is counted as not installed, with one warning naming the schemes to add.
|
|
36
|
+
*/
|
|
37
|
+
export async function installedSereusApps(
|
|
38
|
+
apps: readonly SereusApp[],
|
|
39
|
+
ownScheme: string,
|
|
40
|
+
canOpenURL: (url: string) => Promise<boolean>,
|
|
41
|
+
): Promise<SereusApp[]> {
|
|
42
|
+
const candidates = oneAppPerScheme(apps).filter((app) => app.scheme !== ownScheme);
|
|
43
|
+
const unqueryable: { scheme: string; error: unknown }[] = [];
|
|
44
|
+
const installed = await Promise.all(candidates.map(async (app) => {
|
|
45
|
+
try {
|
|
46
|
+
return await canOpenURL(`${app.scheme}://`);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
unqueryable.push({ scheme: app.scheme, error });
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}));
|
|
52
|
+
if (unqueryable.length > 0) {
|
|
53
|
+
console.warn(
|
|
54
|
+
`[cadre-client/app-link] canOpenURL refused ${unqueryable.map((entry) => entry.scheme).join(', ')}; ` +
|
|
55
|
+
'add each to LSApplicationQueriesSchemes (the config plugin\'s appLinks.extraApps does)',
|
|
56
|
+
unqueryable,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return candidates.filter((_app, index) => installed[index]);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The first app listed for each scheme: the known list and an app's extras may name one twice. */
|
|
63
|
+
function oneAppPerScheme(apps: readonly SereusApp[]): SereusApp[] {
|
|
64
|
+
const seen = new Set<string>();
|
|
65
|
+
return apps.filter((app) => {
|
|
66
|
+
if (seen.has(app.scheme)) return false;
|
|
67
|
+
seen.add(app.scheme);
|
|
68
|
+
return true;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `LinkRequestStore`: the asking app's record of the join request it opened as a link, so it
|
|
3
|
+
* takes only the answer to that request, once. The record is saved before the owner app opens,
|
|
4
|
+
* in the app-private node-local database (`PhoneNode.linkRequestSlot()`), so an asking app the
|
|
5
|
+
* OS killed while the owner app was in front still takes the answer when the link starts it.
|
|
6
|
+
*
|
|
7
|
+
* The nonce is the security contract: an answer carrying any other nonce, a second answer to the
|
|
8
|
+
* same request, and an answer after {@link LINK_REQUEST_TTL_MS} are refused with
|
|
9
|
+
* {@link UnsolicitedJoinResponseError}, so a link no request asked for cannot hand the app an
|
|
10
|
+
* invitation.
|
|
11
|
+
*/
|
|
12
|
+
import type { DurableSlot } from '@serfab/cadre-core';
|
|
13
|
+
import { toString as uint8ArrayToString } from 'uint8arrays';
|
|
14
|
+
import { decodeCadreJoinResponse, type CadreJoinResponse } from './join-response.js';
|
|
15
|
+
|
|
16
|
+
/** How long an open request takes an answer: long enough to unlock the owner app and confirm. */
|
|
17
|
+
export const LINK_REQUEST_TTL_MS = 30 * 60_000;
|
|
18
|
+
|
|
19
|
+
/** The slot's text while no request is open: the slot cannot be deleted, only written. */
|
|
20
|
+
const NO_OPEN_REQUEST = '';
|
|
21
|
+
|
|
22
|
+
/** Random bytes in a nonce: 128 bits, 22 base64url characters. */
|
|
23
|
+
const NONCE_BYTES = 16;
|
|
24
|
+
|
|
25
|
+
/** The join request the app opened as a link and has not taken an answer to. */
|
|
26
|
+
export interface OpenLinkRequest {
|
|
27
|
+
/** The request's `reply.nonce`; the answer must carry it. */
|
|
28
|
+
nonce: string;
|
|
29
|
+
/** The owner app opened (iOS), for the app's messages; null when the Android chooser picked it. */
|
|
30
|
+
ownerAppName: string | null;
|
|
31
|
+
startedAtMs: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** An answer that is not to the request this app has open: none is open, it expired, it was answered already, or the nonce differs. */
|
|
35
|
+
export class UnsolicitedJoinResponseError extends Error {
|
|
36
|
+
constructor(message: string) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = 'UnsolicitedJoinResponseError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Create one per app, over `PhoneNode.linkRequestSlot()`: its calls run one at a time, so two
|
|
44
|
+
* deliveries of the same answer (the launch URL and a `url` event) cannot both take it.
|
|
45
|
+
*/
|
|
46
|
+
export class LinkRequestStore {
|
|
47
|
+
private turn: Promise<unknown> = Promise.resolve();
|
|
48
|
+
|
|
49
|
+
constructor(
|
|
50
|
+
private readonly slot: DurableSlot,
|
|
51
|
+
private readonly now: () => number = Date.now,
|
|
52
|
+
) {}
|
|
53
|
+
|
|
54
|
+
/** Open a request, or return the open one unchanged (same nonce) so an answer to an earlier tap still lands. */
|
|
55
|
+
begin(ownerAppName: string | null): Promise<OpenLinkRequest> {
|
|
56
|
+
return this.inTurn(async () => {
|
|
57
|
+
const open = await this.readOpen();
|
|
58
|
+
if (open) return open;
|
|
59
|
+
const request: OpenLinkRequest = { nonce: newLinkNonce(), ownerAppName, startedAtMs: this.now() };
|
|
60
|
+
await this.slot.save(JSON.stringify(request));
|
|
61
|
+
return request;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The open request, or null when none is open or it is older than {@link LINK_REQUEST_TTL_MS}. A slot read that fails throws. */
|
|
66
|
+
current(): Promise<OpenLinkRequest | null> {
|
|
67
|
+
return this.inTurn(() => this.readOpen());
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
cancel(): Promise<void> {
|
|
71
|
+
return this.inTurn(() => this.slot.save(NO_OPEN_REQUEST));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The decoded response when its nonce is the open request's, clearing the request; else throws
|
|
76
|
+
* {@link UnsolicitedJoinResponseError}. A malformed response throws the codec's error and leaves
|
|
77
|
+
* the request open; a slot read that fails throws, rather than reading as no request.
|
|
78
|
+
*/
|
|
79
|
+
take(responseText: string): Promise<CadreJoinResponse> {
|
|
80
|
+
return this.inTurn(async () => {
|
|
81
|
+
const response = decodeCadreJoinResponse(responseText);
|
|
82
|
+
const open = await this.readOpen();
|
|
83
|
+
if (!open) {
|
|
84
|
+
throw new UnsolicitedJoinResponseError('This answer is not to a join request this app has open: none is open, it expired, or it was answered already');
|
|
85
|
+
}
|
|
86
|
+
if (open.nonce !== response.nonce) {
|
|
87
|
+
throw new UnsolicitedJoinResponseError('This answer is to a different join request than the one this app has open');
|
|
88
|
+
}
|
|
89
|
+
await this.slot.save(NO_OPEN_REQUEST);
|
|
90
|
+
return response;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private inTurn<T>(op: () => Promise<T>): Promise<T> {
|
|
95
|
+
const result = this.turn.then(op);
|
|
96
|
+
this.turn = result.catch(() => undefined);
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private async readOpen(): Promise<OpenLinkRequest | null> {
|
|
101
|
+
const text = await this.slot.load();
|
|
102
|
+
if (text === undefined || text === NO_OPEN_REQUEST) return null;
|
|
103
|
+
const request = parseOpenLinkRequest(text);
|
|
104
|
+
if (!request) return null;
|
|
105
|
+
return this.now() - request.startedAtMs > LINK_REQUEST_TTL_MS ? null : request;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The saved record, or null, logged, when it is not one: a record no answer can match is no open request. */
|
|
110
|
+
function parseOpenLinkRequest(text: string): OpenLinkRequest | null {
|
|
111
|
+
let parsed: unknown;
|
|
112
|
+
try {
|
|
113
|
+
parsed = JSON.parse(text);
|
|
114
|
+
} catch (err) {
|
|
115
|
+
console.warn('[cadre-client/app-link] the open link request record is not JSON; reading it as none:', err);
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const { nonce, ownerAppName, startedAtMs } = (typeof parsed === 'object' && parsed !== null ? parsed : {}) as Record<string, unknown>;
|
|
119
|
+
if (typeof nonce !== 'string' || (ownerAppName !== null && typeof ownerAppName !== 'string') || typeof startedAtMs !== 'number' || !Number.isFinite(startedAtMs)) {
|
|
120
|
+
console.warn('[cadre-client/app-link] the open link request record has the wrong shape; reading it as none:', text);
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
return { nonce, ownerAppName, startedAtMs };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 16 random bytes, base64url: the form a join request's `reply.nonce` takes. */
|
|
127
|
+
function newLinkNonce(): string {
|
|
128
|
+
return uint8ArrayToString(crypto.getRandomValues(new Uint8Array(NONCE_BYTES)), 'base64url');
|
|
129
|
+
}
|