@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.
Files changed (116) hide show
  1. package/ADOPTING.md +228 -0
  2. package/README.md +130 -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 +309 -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 +333 -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 +38 -0
  79. package/dist/stores.js +48 -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 +191 -0
  86. package/examples/react-native/useStore.ts +11 -0
  87. package/examples/svelte/CadronList.svelte +86 -0
  88. package/examples/svelte/InvitationPanel.svelte +97 -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 +327 -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 +359 -0
  114. package/src/sereus/node-code.ts +80 -0
  115. package/src/store.ts +61 -0
  116. package/src/stores.ts +62 -0
@@ -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
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * `AppRecommendationStore`: the owner app's record that the user allowed another Sereus app to
3
+ * join before that app asked. When the recommended app's join request opened as a link arrives
4
+ * with that app's scheme as its `reply.scheme`, the owner app takes the pre-approval and answers
5
+ * with a targeted invitation without asking again (docs/cadre/apps.md → "Recommending another
6
+ * app").
7
+ *
8
+ * A pre-approval is the security contract: it is used up by the one answer it allows, lasts
9
+ * {@link RECOMMENDATION_TTL_MS}, and is never returned for a party other than the one the user
10
+ * was in when they allowed it. It admits a machine only: the invitation it answers with grants no
11
+ * ownership, and an app with strands to bring joins with a separately redeemed owner grant
12
+ * (whether a link join may also carry ownership is
13
+ * `tickets/blocked/decide-app-link-join-carries-ownership.md`).
14
+ */
15
+ import type { DurableSlot } from '@serfab/cadre-core';
16
+
17
+ /** How long a pre-approval waits for the recommended app's request: enough to install it from the store and open it. */
18
+ export const RECOMMENDATION_TTL_MS = 60 * 60_000;
19
+
20
+ /** The user allowed the app at `scheme` to join `partyId` before it asked. */
21
+ export interface AppRecommendation {
22
+ /** The recommended app's own URL scheme: what its request's `reply.scheme` must be. */
23
+ scheme: string;
24
+ /** The name the owner app showed the user, from its known-apps list, never from a request. */
25
+ appName: string;
26
+ /** The party the owner app was in when the user allowed it. */
27
+ partyId: string;
28
+ approvedAtMs: number;
29
+ }
30
+
31
+ /**
32
+ * Create one per app, over `PhoneNode.recommendationSlot()`: its calls run one at a time, so two
33
+ * deliveries of the same request (the launch URL and a `url` event) cannot both take the
34
+ * pre-approval.
35
+ */
36
+ export class AppRecommendationStore {
37
+ private turn: Promise<unknown> = Promise.resolve();
38
+
39
+ constructor(
40
+ private readonly slot: DurableSlot,
41
+ private readonly now: () => number = Date.now,
42
+ ) {}
43
+
44
+ /** Record a pre-approval, replacing any for the same scheme. */
45
+ approve(entry: Omit<AppRecommendation, 'approvedAtMs'>): Promise<AppRecommendation> {
46
+ return this.inTurn(async () => {
47
+ const approved: AppRecommendation = { ...entry, approvedAtMs: this.now() };
48
+ const others = (await this.readLive(entry.partyId)).filter((live) => live.scheme !== entry.scheme);
49
+ await this.write([approved, ...others]);
50
+ return approved;
51
+ });
52
+ }
53
+
54
+ /** The live pre-approvals for `partyId`, most recently approved first, for the owner app's list. A slot read that fails throws. */
55
+ live(partyId: string): Promise<AppRecommendation[]> {
56
+ return this.inTurn(() => this.readLive(partyId));
57
+ }
58
+
59
+ /** Drop the pre-approval for `scheme`, if any. */
60
+ withdraw(scheme: string): Promise<void> {
61
+ return this.inTurn(async () => {
62
+ // Other parties' entries stay: withdraw names no party, and they are never returned for this one.
63
+ await this.write((await this.readUnexpired()).filter((entry) => entry.scheme !== scheme));
64
+ });
65
+ }
66
+
67
+ /**
68
+ * The live pre-approval for `scheme` in `partyId`, removed as it is returned; null when there is
69
+ * none. Removed even when the caller then fails to mint, so it allows one answer at most.
70
+ */
71
+ take(scheme: string, partyId: string): Promise<AppRecommendation | null> {
72
+ return this.inTurn(async () => {
73
+ const live = await this.readLive(partyId);
74
+ const taken = live.find((entry) => entry.scheme === scheme);
75
+ if (!taken) return null;
76
+ await this.write(live.filter((entry) => entry !== taken));
77
+ return taken;
78
+ });
79
+ }
80
+
81
+ private inTurn<T>(op: () => Promise<T>): Promise<T> {
82
+ const result = this.turn.then(op);
83
+ this.turn = result.catch(() => undefined);
84
+ return result;
85
+ }
86
+
87
+ /** The unexpired entries for `partyId`: what every write keeps, so expired and other parties' entries are pruned by it. */
88
+ private async readLive(partyId: string): Promise<AppRecommendation[]> {
89
+ return (await this.readUnexpired()).filter((entry) => entry.partyId === partyId);
90
+ }
91
+
92
+ private async readUnexpired(): Promise<AppRecommendation[]> {
93
+ const text = await this.slot.load();
94
+ if (text === undefined) return [];
95
+ const now = this.now();
96
+ // NOTE: an entry dated ahead of `now` (the clock set back after approving) stays live until the
97
+ // clock passes its date plus the hour, longer than the hour the user agreed to. If clock changes
98
+ // ever matter here, treat an entry more than a minute in the future as expired.
99
+ return parseRecommendations(text).filter((entry) => now - entry.approvedAtMs <= RECOMMENDATION_TTL_MS);
100
+ }
101
+
102
+ private write(entries: readonly AppRecommendation[]): Promise<void> {
103
+ return this.slot.save(JSON.stringify(entries));
104
+ }
105
+ }
106
+
107
+ /** The saved list, or an empty one, logged, when it is not one: a record that cannot be read allows nothing. */
108
+ function parseRecommendations(text: string): AppRecommendation[] {
109
+ let parsed: unknown;
110
+ try {
111
+ parsed = JSON.parse(text);
112
+ } catch (err) {
113
+ console.warn('[cadre-client/app-link] the app recommendation record is not JSON; reading it as none:', err);
114
+ return [];
115
+ }
116
+ const entries = Array.isArray(parsed) ? parsed.map(parseRecommendation) : null;
117
+ if (!entries?.every((entry): entry is AppRecommendation => entry !== null)) {
118
+ console.warn('[cadre-client/app-link] the app recommendation record has the wrong shape; reading it as none:', text);
119
+ return [];
120
+ }
121
+ return entries;
122
+ }
123
+
124
+ /** Only the named fields are read, so a stored entry carrying a field this shape does not have parses without it. */
125
+ function parseRecommendation(value: unknown): AppRecommendation | null {
126
+ const { scheme, appName, partyId, approvedAtMs } = (typeof value === 'object' && value !== null ? value : {}) as Record<string, unknown>;
127
+ if (typeof scheme !== 'string' || typeof appName !== 'string' || typeof partyId !== 'string'
128
+ || typeof approvedAtMs !== 'number' || !Number.isFinite(approvedAtMs)) {
129
+ return null;
130
+ }
131
+ return { scheme, appName, partyId, approvedAtMs };
132
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Which addresses an invitation names: the few that will reach one of the person's cadrons
3
+ * (the machines of their cadre) from anywhere, in the order a joiner should try them.
4
+ *
5
+ * WORKAROUND(sereus: ranked open invitations, curated published records). cadre-core's
6
+ * `createOpenInvitation` names each other machine's first four addresses in the order the
7
+ * machine published them, and a machine publishes every address libp2p reports, loopback,
8
+ * private and plain TCP first. A cadre-host machine on a VPS so ends up named only by
9
+ * addresses no phone can dial, its public WebSocket address cut. This plans the list itself from the
10
+ * machines' full records, and the app puts it in the invitation before encoding it (the list is
11
+ * not signed; the responder checks only the token).
12
+ *
13
+ * Pure: the evidence comes in (`BootstrapInput`), the plan goes out. `/sereus` gathers it.
14
+ */
15
+ import { addressKind, ADDRESS_KIND_RANK, reachesAnywhere, type CadronAddressKind } from './address.js';
16
+
17
+ /** Where an address of a cadron came from, best evidence first. */
18
+ export type AddressSource =
19
+ /** A connection this device opened to it, with no relay hop, is open now: it answered. */
20
+ | 'connection'
21
+ /** The cadron's own signed, recently published record. */
22
+ | 'record'
23
+ /** What this device was handed when it claimed the cadron, kept until its record arrives. */
24
+ | 'claim';
25
+
26
+ export interface CadronCandidate {
27
+ /** The cadron's control peer id: what an invitation's addresses end in (`/p2p/<peerId>`). */
28
+ peerId: string;
29
+ /** It declares itself always on (its signed record); unknown counts as not. */
30
+ alwaysOn: boolean;
31
+ /** When its record was last published (ms), or null when none has reached this device yet. */
32
+ lastPublishedAt: number | null;
33
+ addrs: ReadonlyArray<{ addr: string; source: AddressSource }>;
34
+ }
35
+
36
+ /** How invitations name the person's cadrons. Kept per device for now. */
37
+ export interface CadronPreferences {
38
+ /**
39
+ * Cadrons to name first, in this order (control peer ids).
40
+ * WORKAROUND(sereus: a party-level bootstrap preference): kept on this device, so each of the
41
+ * person's devices has its own.
42
+ */
43
+ preferred: string[];
44
+ /** The person's own names for their cadrons, by peer id, for screens and the readable invitation. */
45
+ names: Record<string, string>;
46
+ /** How many addresses an invitation names in all (1–8). Fewer: a shorter link, a sparser QR. */
47
+ maxAddrs: number;
48
+ /**
49
+ * This device's own addresses (a phone: its relay addresses): `fallback`, only when no cadron
50
+ * reaches from anywhere; `always`, in the last slot when one is left; `never`.
51
+ */
52
+ thisDevice: 'fallback' | 'always' | 'never';
53
+ /** Name private-network addresses too (a joiner on the same network). Off by default. */
54
+ allowPrivate: boolean;
55
+ }
56
+
57
+ export const DEFAULT_CADRON_PREFERENCES: CadronPreferences = {
58
+ preferred: [], names: {}, maxAddrs: 2, thisDevice: 'fallback', allowPrivate: false,
59
+ };
60
+ export const MAX_BOOTSTRAP_ADDRS = 8;
61
+ /**
62
+ * The stored form's version (`format` beside the fields). The app keeps the text opaque; a later
63
+ * format is read and migrated here, and a field this version does not know is dropped.
64
+ */
65
+ export const CADRON_PREFERENCES_FORMAT = 1;
66
+
67
+ /** Preferences as stored, made whole and in range (missing fields defaulted, ids deduplicated). */
68
+ export function normalizePreferences(raw: Partial<CadronPreferences> | null | undefined): CadronPreferences {
69
+ const p = { ...DEFAULT_CADRON_PREFERENCES, ...(raw ?? {}) };
70
+ const maxAddrs = Number.isInteger(p.maxAddrs) ? Math.min(MAX_BOOTSTRAP_ADDRS, Math.max(1, p.maxAddrs)) : DEFAULT_CADRON_PREFERENCES.maxAddrs;
71
+ return {
72
+ preferred: [...new Set((Array.isArray(p.preferred) ? p.preferred : []).filter(id => typeof id === 'string' && id))],
73
+ names: typeof p.names === 'object' && p.names ? { ...p.names } : {},
74
+ maxAddrs,
75
+ thisDevice: p.thisDevice === 'always' || p.thisDevice === 'never' ? p.thisDevice : 'fallback',
76
+ allowPrivate: p.allowPrivate === true,
77
+ };
78
+ }
79
+
80
+ export interface BootstrapInput {
81
+ cadrons: readonly CadronCandidate[];
82
+ thisDevice: { peerId: string; addrs: readonly string[] };
83
+ prefs: CadronPreferences;
84
+ }
85
+
86
+ export interface BootstrapEntry {
87
+ addr: string;
88
+ peerId: string;
89
+ /** This device rather than one of its cadrons. */
90
+ thisDevice: boolean;
91
+ kind: CadronAddressKind;
92
+ source: AddressSource | 'this-device';
93
+ preferred: boolean;
94
+ alwaysOn: boolean;
95
+ }
96
+
97
+ export type BootstrapWarning =
98
+ /** No cadron has an address that reaches from anywhere: only this device (if anything) answers. */
99
+ | 'no-cadron-reachable-from-anywhere'
100
+ /** A named cadron's address comes from its claim: its signed record has not reached this device yet. */
101
+ | 'cadron-record-not-yet-published'
102
+ /** Nothing at all reaches from anywhere: the invitation works only on the inviter's own network, if at all. */
103
+ | 'unreachable';
104
+
105
+ export interface BootstrapPlan {
106
+ entries: BootstrapEntry[];
107
+ /**
108
+ * Usable addresses the plan left out, best first: cadrons' addresses past the cap, then this
109
+ * device's when it was not wanted. What a person can add to one invitation by hand.
110
+ */
111
+ others: BootstrapEntry[];
112
+ warnings: BootstrapWarning[];
113
+ }
114
+
115
+ const SOURCE_RANK: Record<AddressSource, number> = { connection: 0, record: 1, claim: 2 };
116
+
117
+ /**
118
+ * The plan: preferred cadrons first (in the person's order), then other always-on cadrons, then
119
+ * the rest, each group newest record first; each cadron's addresses best first (reach, then
120
+ * evidence), loopback and undialable ones never; at most `maxAddrs` in all, one address per
121
+ * cadron before any cadron gets a second, so a second cadron backs up the first. This device's
122
+ * addresses go in as `prefs.thisDevice` says.
123
+ */
124
+ export function planBootstrap(input: BootstrapInput): BootstrapPlan {
125
+ const { prefs } = input;
126
+ const usable = (kind: CadronAddressKind | null): kind is CadronAddressKind =>
127
+ kind !== null && kind !== 'loopback' && (reachesAnywhere(kind) || (prefs.allowPrivate && kind === 'private'));
128
+
129
+ const preferredAt = (peerId: string) => {
130
+ const i = prefs.preferred.indexOf(peerId);
131
+ return i < 0 ? Infinity : i;
132
+ };
133
+ const cadrons = input.cadrons
134
+ .filter(c => c.peerId !== input.thisDevice.peerId)
135
+ .map(c => {
136
+ // One entry per address, its best evidence kept.
137
+ const best = new Map<string, AddressSource>();
138
+ for (const { addr, source } of c.addrs) {
139
+ const had = best.get(addr);
140
+ if (had === undefined || SOURCE_RANK[source] < SOURCE_RANK[had]) best.set(addr, source);
141
+ }
142
+ const addrs = [...best]
143
+ .map(([addr, source]) => ({ addr, source, kind: addressKind(addr) }))
144
+ .filter((a): a is { addr: string; source: AddressSource; kind: CadronAddressKind } => usable(a.kind))
145
+ .sort((a, b) => ADDRESS_KIND_RANK[a.kind] - ADDRESS_KIND_RANK[b.kind] || SOURCE_RANK[a.source] - SOURCE_RANK[b.source]);
146
+ return { ...c, addrs, preferred: preferredAt(c.peerId) !== Infinity };
147
+ })
148
+ .filter(c => c.addrs.length > 0)
149
+ .sort((a, b) => preferredAt(a.peerId) - preferredAt(b.peerId)
150
+ || Number(b.alwaysOn) - Number(a.alwaysOn)
151
+ || (b.lastPublishedAt ?? 0) - (a.lastPublishedAt ?? 0));
152
+
153
+ const own = input.thisDevice.addrs
154
+ .map(addr => ({ addr, kind: addressKind(addr) }))
155
+ .filter((a): a is { addr: string; kind: CadronAddressKind } => usable(a.kind))
156
+ .sort((a, b) => ADDRESS_KIND_RANK[a.kind] - ADDRESS_KIND_RANK[b.kind]);
157
+ const ownEntry = (a: { addr: string; kind: CadronAddressKind }): BootstrapEntry => ({
158
+ addr: a.addr, peerId: input.thisDevice.peerId, thisDevice: true, kind: a.kind, source: 'this-device', preferred: false, alwaysOn: false,
159
+ });
160
+
161
+ const anywhereCadron = cadrons.some(c => c.addrs.some(a => reachesAnywhere(a.kind)));
162
+ const wantOwn = prefs.thisDevice === 'always' || (prefs.thisDevice === 'fallback' && !anywhereCadron);
163
+ const cadronSlots = wantOwn && own.length > 0 && cadrons.length > 0 ? Math.max(1, prefs.maxAddrs - 1) : prefs.maxAddrs;
164
+
165
+ // Round robin: each cadron's best address, then each one's second, until the slots are filled.
166
+ const entries: BootstrapEntry[] = [];
167
+ const others: BootstrapEntry[] = [];
168
+ const rounds = Math.max(0, ...cadrons.map(c => c.addrs.length));
169
+ for (let round = 0; round < rounds; round++) {
170
+ for (const c of cadrons) {
171
+ const a = c.addrs[round];
172
+ if (!a) continue;
173
+ const entry: BootstrapEntry = { addr: a.addr, peerId: c.peerId, thisDevice: false, kind: a.kind, source: a.source, preferred: c.preferred, alwaysOn: c.alwaysOn };
174
+ (entries.length < cadronSlots ? entries : others).push(entry);
175
+ }
176
+ }
177
+ for (const a of own) (wantOwn && entries.length < prefs.maxAddrs ? entries : others).push(ownEntry(a));
178
+
179
+ const warnings: BootstrapWarning[] = [];
180
+ if (!anywhereCadron) warnings.push('no-cadron-reachable-from-anywhere');
181
+ if (entries.some(e => e.source === 'claim')) warnings.push('cadron-record-not-yet-published');
182
+ if (!entries.some(e => reachesAnywhere(e.kind))) warnings.push('unreachable');
183
+ return { entries, others, warnings };
184
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The few host globals this package relies on, which every runtime it targets provides
3
+ * (Hermes/React Native, browsers, Node, NativeScript). Declared here rather than pulling
4
+ * in the DOM or Node type libraries, so a browser-only or Node-only API cannot slip in
5
+ * unnoticed.
6
+ */
7
+ declare function setTimeout(handler: () => void, ms?: number): unknown;
8
+ declare function clearTimeout(handle: unknown): void;
9
+
10
+ declare const console: {
11
+ info(...args: unknown[]): void;
12
+ warn(...args: unknown[]): void;
13
+ error(...args: unknown[]): void;
14
+ };
15
+
16
+ /** Text to bytes and back (app-link codecs). */
17
+ declare class TextEncoder {
18
+ encode(input?: string): Uint8Array;
19
+ }
20
+ declare class TextDecoder {
21
+ constructor(label?: string, options?: { fatal?: boolean });
22
+ decode(input?: Uint8Array): string;
23
+ }
24
+
25
+ /** Random bytes (a link request's nonce). React Native gets it from `react-native-get-random-values`. */
26
+ declare const crypto: { getRandomValues<T extends Uint8Array>(array: T): T };
package/src/inbox.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * One node code waiting to be reviewed. A code can arrive at any moment: a link opened while the
3
+ * app starts, a scan, a paste, while another claim is still running. The app hands each arrival to
4
+ * `offer`; the cadre screen takes it when it can show the approval prompt. One slot, the latest
5
+ * arrival wins: a person acts on the code they just opened. Listening for the links themselves is
6
+ * the platform's (on React Native, the app's linking handler); this only holds what arrived.
7
+ */
8
+ import { nodeCodeFromUrl } from './node-code-text.js';
9
+ import { writable, type Readable } from './store.js';
10
+
11
+ export interface NodeCodeInbox {
12
+ /** The code waiting, or null; subscribe to show the prompt when one arrives. Never log its value. */
13
+ pending: Readable<string | null>;
14
+ /** A link or text that may hold a node code: kept (replacing any waiting one) if it does. Returns whether it did. */
15
+ offer(textOrUrl: string | null | undefined): boolean;
16
+ /** The waiting code, removed; null when none. */
17
+ take(): string | null;
18
+ }
19
+
20
+ export function nodeCodeInbox(): NodeCodeInbox {
21
+ const pending = writable<string | null>(null);
22
+ return {
23
+ pending,
24
+ offer(textOrUrl) {
25
+ const code = nodeCodeFromUrl(textOrUrl);
26
+ if (!code) return false;
27
+ pending.set(code);
28
+ return true;
29
+ },
30
+ take() {
31
+ const code = pending.get();
32
+ pending.set(null);
33
+ return code;
34
+ },
35
+ };
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@serfab/cadre-client`: the stack-free half. Types, results, node-code text, address
3
+ * judgement and stores — nothing here loads cadre-core, so a screen or a mock can import
4
+ * it freely. The implementation over a running node is `@serfab/cadre-client/sereus`.
5
+ */
6
+ export * from './result.js';
7
+ export * from './model.js';
8
+ export * from './node-code-text.js';
9
+ export * from './inbox.js';
10
+ export * from './address.js';
11
+ export * from './bootstrap.js';
12
+ export * from './invitation-text.js';
13
+ export * from './store.js';
14
+ export * from './loader.js';
15
+ export * from './stores.js';