@serfab/cadre-client 0.0.0-stage → 2.0.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.
Files changed (116) hide show
  1. package/ADOPTING.md +220 -0
  2. package/README.md +129 -3
  3. package/dist/address.d.ts +45 -0
  4. package/dist/address.js +109 -0
  5. package/dist/address.js.map +1 -0
  6. package/dist/app-link/index.d.ts +16 -0
  7. package/dist/app-link/index.js +17 -0
  8. package/dist/app-link/index.js.map +1 -0
  9. package/dist/app-link/join-response.d.ts +31 -0
  10. package/dist/app-link/join-response.js +87 -0
  11. package/dist/app-link/join-response.js.map +1 -0
  12. package/dist/app-link/known-apps.d.ts +32 -0
  13. package/dist/app-link/known-apps.js +51 -0
  14. package/dist/app-link/known-apps.js.map +1 -0
  15. package/dist/app-link/link-request-store.d.ts +50 -0
  16. package/dist/app-link/link-request-store.js +101 -0
  17. package/dist/app-link/link-request-store.js.map +1 -0
  18. package/dist/app-link/links.d.ts +47 -0
  19. package/dist/app-link/links.js +76 -0
  20. package/dist/app-link/links.js.map +1 -0
  21. package/dist/app-link/recommend-links.d.ts +30 -0
  22. package/dist/app-link/recommend-links.js +33 -0
  23. package/dist/app-link/recommend-links.js.map +1 -0
  24. package/dist/app-link/recommendation-store.d.ts +54 -0
  25. package/dist/app-link/recommendation-store.js +99 -0
  26. package/dist/app-link/recommendation-store.js.map +1 -0
  27. package/dist/bootstrap.d.ts +106 -0
  28. package/dist/bootstrap.js +106 -0
  29. package/dist/bootstrap.js.map +1 -0
  30. package/dist/inbox.d.ts +10 -0
  31. package/dist/inbox.js +28 -0
  32. package/dist/inbox.js.map +1 -0
  33. package/dist/index.d.ts +15 -0
  34. package/dist/index.js +16 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/invitation-text.d.ts +81 -0
  37. package/dist/invitation-text.js +80 -0
  38. package/dist/invitation-text.js.map +1 -0
  39. package/dist/lifecycle/background-runner.d.ts +94 -0
  40. package/dist/lifecycle/background-runner.js +278 -0
  41. package/dist/lifecycle/background-runner.js.map +1 -0
  42. package/dist/lifecycle/index.d.ts +9 -0
  43. package/dist/lifecycle/index.js +10 -0
  44. package/dist/lifecycle/index.js.map +1 -0
  45. package/dist/loader.d.ts +47 -0
  46. package/dist/loader.js +93 -0
  47. package/dist/loader.js.map +1 -0
  48. package/dist/model.d.ts +284 -0
  49. package/dist/model.js +22 -0
  50. package/dist/model.js.map +1 -0
  51. package/dist/node-code-text.d.ts +10 -0
  52. package/dist/node-code-text.js +30 -0
  53. package/dist/node-code-text.js.map +1 -0
  54. package/dist/result.d.ts +79 -0
  55. package/dist/result.js +84 -0
  56. package/dist/result.js.map +1 -0
  57. package/dist/sereus/client.d.ts +49 -0
  58. package/dist/sereus/client.js +420 -0
  59. package/dist/sereus/client.js.map +1 -0
  60. package/dist/sereus/edge-host.d.ts +22 -0
  61. package/dist/sereus/edge-host.js +61 -0
  62. package/dist/sereus/edge-host.js.map +1 -0
  63. package/dist/sereus/host.d.ts +57 -0
  64. package/dist/sereus/host.js +2 -0
  65. package/dist/sereus/host.js.map +1 -0
  66. package/dist/sereus/index.d.ts +8 -0
  67. package/dist/sereus/index.js +9 -0
  68. package/dist/sereus/index.js.map +1 -0
  69. package/dist/sereus/invitations.d.ts +16 -0
  70. package/dist/sereus/invitations.js +196 -0
  71. package/dist/sereus/invitations.js.map +1 -0
  72. package/dist/sereus/node-code.d.ts +52 -0
  73. package/dist/sereus/node-code.js +51 -0
  74. package/dist/sereus/node-code.js.map +1 -0
  75. package/dist/store.d.ts +27 -0
  76. package/dist/store.js +51 -0
  77. package/dist/store.js.map +1 -0
  78. package/dist/stores.d.ts +37 -0
  79. package/dist/stores.js +45 -0
  80. package/dist/stores.js.map +1 -0
  81. package/examples/README.md +20 -0
  82. package/examples/nativescript/cadrons-page.xml +24 -0
  83. package/examples/nativescript/cadrons-view-model.ts +68 -0
  84. package/examples/react-native/CadronList.tsx +204 -0
  85. package/examples/react-native/InvitationPanel.tsx +162 -0
  86. package/examples/react-native/useStore.ts +11 -0
  87. package/examples/svelte/CadronList.svelte +86 -0
  88. package/examples/svelte/InvitationPanel.svelte +79 -0
  89. package/package.json +65 -3
  90. package/src/address.ts +125 -0
  91. package/src/app-link/index.ts +45 -0
  92. package/src/app-link/join-response.ts +109 -0
  93. package/src/app-link/known-apps.ts +70 -0
  94. package/src/app-link/link-request-store.ts +129 -0
  95. package/src/app-link/links.ts +90 -0
  96. package/src/app-link/recommend-links.ts +49 -0
  97. package/src/app-link/recommendation-store.ts +132 -0
  98. package/src/bootstrap.ts +184 -0
  99. package/src/globals.d.ts +26 -0
  100. package/src/inbox.ts +36 -0
  101. package/src/index.ts +15 -0
  102. package/src/invitation-text.ts +156 -0
  103. package/src/lifecycle/background-runner.ts +363 -0
  104. package/src/lifecycle/index.ts +17 -0
  105. package/src/loader.ts +103 -0
  106. package/src/model.ts +299 -0
  107. package/src/node-code-text.ts +25 -0
  108. package/src/result.ts +131 -0
  109. package/src/sereus/client.ts +454 -0
  110. package/src/sereus/edge-host.ts +81 -0
  111. package/src/sereus/host.ts +56 -0
  112. package/src/sereus/index.ts +8 -0
  113. package/src/sereus/invitations.ts +206 -0
  114. package/src/sereus/node-code.ts +80 -0
  115. package/src/store.ts +61 -0
  116. package/src/stores.ts +59 -0
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
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The links two Sereus apps on one phone open each other with: the asking app's join request,
3
+ * and the owner app's answer opened back at the asking app's own scheme.
4
+ *
5
+ * - Android: the request text itself (`sereus-join-request:1.…`), which every opted-in Sereus app
6
+ * registers, so the system app chooser lists every installed owner app.
7
+ * - iOS: `<owner scheme>://cadre-join-request/<request text>`, one owner app chosen by its scheme.
8
+ * - The answer, both platforms: `<reply scheme>://cadre-join-response/<response text>`. The owner
9
+ * app builds it from the request's `reply.scheme`; it never opens a URL a request supplied.
10
+ * - A recommendation, both platforms: `<recommended app's scheme>://cadre-recommended-by/<own scheme>`,
11
+ * opened by an owner app at a recommended app that is already installed.
12
+ */
13
+ import { CADRE_JOIN_REQUEST_PREFIX, requireCadreJoinReply } from '@serfab/cadre-core';
14
+ import { encodeCadreJoinResponse, type CadreJoinResponse } from './join-response.js';
15
+ import type { SereusApp } from './known-apps.js';
16
+
17
+ /**
18
+ * Longest answering link {@link joinResponseLink} builds. An invitation names at most six machine
19
+ * addresses, which puts a response link at about 4 KB by its shape (not measured); the limit
20
+ * guards against invitations growing past what an intent or a URL reliably carries.
21
+ */
22
+ export const CADRE_LINK_MAX_LENGTH = 32_768;
23
+
24
+ const REQUEST_PATH = 'cadre-join-request';
25
+ const RESPONSE_PATH = 'cadre-join-response';
26
+ const RECOMMENDED_BY_PATH = 'cadre-recommended-by';
27
+
28
+ /** `<scheme>://<path>/<text>` for any scheme, where the path names the link's kind. */
29
+ const SCHEME_LINK = new RegExp(`^[a-z][a-z0-9+.-]*://(${REQUEST_PATH}|${RESPONSE_PATH}|${RECOMMENDED_BY_PATH})/(.+)$`, 'i');
30
+
31
+ /**
32
+ * What an incoming URL carries: a join request to answer, the answer to this app's own, or the
33
+ * scheme of the app that recommended this one. That scheme is unverified: the app trusts it only
34
+ * when it is on its own known-apps list, and names that app from the list.
35
+ */
36
+ export type CadreLink =
37
+ | { kind: 'join-request'; text: string }
38
+ | { kind: 'join-response'; text: string }
39
+ | { kind: 'recommended-by'; text: string };
40
+
41
+ const KIND_BY_PATH: Readonly<Record<string, CadreLink['kind']>> = {
42
+ [REQUEST_PATH]: 'join-request',
43
+ [RESPONSE_PATH]: 'join-response',
44
+ [RECOMMENDED_BY_PATH]: 'recommended-by',
45
+ };
46
+
47
+ /** {@link joinResponseLink} refused to build a link longer than {@link CADRE_LINK_MAX_LENGTH}; show the invitation for copying instead. */
48
+ export class CadreLinkTooLongError extends Error {
49
+ constructor(readonly length: number) {
50
+ super(`A join response link of ${length} characters is longer than ${CADRE_LINK_MAX_LENGTH}`);
51
+ this.name = 'CadreLinkTooLongError';
52
+ }
53
+ }
54
+
55
+ /**
56
+ * What an incoming URL is, or null for anything else, a node code (`sereus-join:1.…`) and an
57
+ * invitation included, so an app's other link routing is untouched. Recognizes only the forms
58
+ * this module builds, under any scheme (a second install of an app has a scheme of its own).
59
+ * Returns the text undecoded: decoding, and refusing, is the caller's step.
60
+ */
61
+ export function parseCadreLink(url: string): CadreLink | null {
62
+ const trimmed = url.trim();
63
+ if (trimmed.startsWith(CADRE_JOIN_REQUEST_PREFIX)) return { kind: 'join-request', text: trimmed };
64
+ const match = SCHEME_LINK.exec(trimmed);
65
+ if (!match) return null;
66
+ const [, path, text] = match;
67
+ return { kind: KIND_BY_PATH[path.toLowerCase()], text };
68
+ }
69
+
70
+ /** Android (`ownerApp` null): the request text itself. iOS: `<ownerApp.scheme>://cadre-join-request/<text>`. */
71
+ export function joinRequestLink(requestText: string, ownerApp: SereusApp | null): string {
72
+ return ownerApp ? `${ownerApp.scheme}://${REQUEST_PATH}/${requestText}` : requestText;
73
+ }
74
+
75
+ /**
76
+ * `<reply.scheme>://cadre-join-response/<response text>`. Checks the scheme and the nonce again
77
+ * (a web or system scheme throws), and throws {@link CadreLinkTooLongError} above
78
+ * {@link CADRE_LINK_MAX_LENGTH}.
79
+ */
80
+ export function joinResponseLink(reply: { scheme: string }, response: CadreJoinResponse): string {
81
+ const { scheme } = requireCadreJoinReply({ scheme: reply.scheme, nonce: response.nonce });
82
+ const link = `${scheme}://${RESPONSE_PATH}/${encodeCadreJoinResponse(response)}`;
83
+ if (link.length > CADRE_LINK_MAX_LENGTH) throw new CadreLinkTooLongError(link.length);
84
+ return link;
85
+ }
86
+
87
+ /** `<app.scheme>://cadre-recommended-by/<ownScheme>`: opened at a recommended app already installed, it names the recommending app as the install referrer would. */
88
+ export function recommendedByLink(app: SereusApp, ownScheme: string): string {
89
+ return `${app.scheme}://${RECOMMENDED_BY_PATH}/${ownScheme}`;
90
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * What an owner app opens to recommend a Sereus app the user does not have yet: the app's store
3
+ * page, which on Android names the recommending app in the install referrer. The recommended
4
+ * app reads the referrer at first launch (`recommendedBySchemeFromReferrer`) to name the app that
5
+ * recommended it and open it directly. For an app already installed the owner app opens
6
+ * `recommendedByLink` (links.ts) instead.
7
+ *
8
+ * The scheme a referrer or a link carries is a hint, never trusted: anyone can build a Play link
9
+ * with any referrer. The recommended app drops a scheme that is not on its own known-apps list,
10
+ * and names the app from that list.
11
+ */
12
+ import type { SereusApp } from './known-apps.js';
13
+
14
+ /** The install referrer an owner app's Play link carries, followed by the owner app's own scheme. */
15
+ export const RECOMMENDED_BY_REFERRER_PREFIX = 'sereus-recommended-by:1.';
16
+
17
+ /** The platforms with an app store a link can open; the app passes `Platform.OS`. */
18
+ export type StorePlatform = 'android' | 'ios';
19
+
20
+ /** `sereus-recommended-by:1.<ownScheme>`: the install referrer naming the recommending app. */
21
+ export function recommendedByReferrer(ownScheme: string): string {
22
+ return `${RECOMMENDED_BY_REFERRER_PREFIX}${ownScheme}`;
23
+ }
24
+
25
+ /**
26
+ * The recommending app's scheme when the install referrer is exactly the token an owner app's
27
+ * store link carries, and null otherwise: an install no Sereus link started reads
28
+ * `utm_source=google-play&utm_medium=organic`. Unverified: see the module comment.
29
+ */
30
+ export function recommendedBySchemeFromReferrer(referrer: string): string | null {
31
+ const trimmed = referrer.trim();
32
+ if (!trimmed.startsWith(RECOMMENDED_BY_REFERRER_PREFIX)) return null;
33
+ const scheme = trimmed.slice(RECOMMENDED_BY_REFERRER_PREFIX.length);
34
+ return scheme.length > 0 ? scheme : null;
35
+ }
36
+
37
+ /**
38
+ * The app's store page, or null when the app has no store id for `platform`. Android: its Play
39
+ * page, with the install referrer naming `ownScheme`. iOS: its App Store page, with nothing about
40
+ * the recommending app, since iOS has no install referrer.
41
+ */
42
+ export function storePageLink(app: SereusApp, platform: StorePlatform, ownScheme: string): string | null {
43
+ if (platform === 'android') {
44
+ if (!app.androidPackage) return null;
45
+ const referrer = encodeURIComponent(recommendedByReferrer(ownScheme));
46
+ return `https://play.google.com/store/apps/details?id=${encodeURIComponent(app.androidPackage)}&referrer=${referrer}`;
47
+ }
48
+ return app.iosAppStoreId ? `https://apps.apple.com/app/id${app.iosAppStoreId}` : null;
49
+ }