@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
@@ -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';
@@ -0,0 +1,156 @@
1
+ /**
2
+ * An invitation in words: what a person sees when they ask what is in the link they are about to
3
+ * hand out (or were handed). Pure: `/sereus` decodes the invitation, this describes it.
4
+ *
5
+ * Besides the addresses it names, it can say which machine each belongs to in the words the
6
+ * person's cadre screen uses (name, status dot, whether it is theirs), and which other addresses
7
+ * of theirs it could name instead, for a screen that lets the person change one invitation's list
8
+ * (`InvitationsModel.rebootstrap`).
9
+ */
10
+ import { addressComponents, addressKind, reachesAnywhere, suggestedName, type CadronAddressKind } from './address.js';
11
+ import { cadronPresence, shortPeerId, type CadreMachine, type CadronPresence } from './model.js';
12
+
13
+ export interface InvitationAddressText {
14
+ /** The cadron's name the person gave it, else its host name, else its short peer id. */
15
+ label: string;
16
+ peerId: string;
17
+ /** This device's own address rather than one of its cadrons'. */
18
+ thisDevice: boolean;
19
+ /** Null for an address no phone can dial (plain TCP, unparsable). */
20
+ kind: CadronAddressKind | null;
21
+ reachesAnywhere: boolean;
22
+ /** The host a joiner dials: the cadron's own, or for a relayed address the relay's. */
23
+ host: string;
24
+ port: number | null;
25
+ /** `ws`, `wss`, `tcp`, or `relay` for an address reached through a relay. */
26
+ via: 'ws' | 'wss' | 'tcp' | 'relay';
27
+ addr: string;
28
+ /** The invitation names it; false for an address it could name instead (`others`). */
29
+ included: boolean;
30
+ }
31
+
32
+ /** A machine an invitation names, or could: the addresses grouped by whose they are. */
33
+ export interface InvitationCadronText {
34
+ peerId: string;
35
+ /** As on each address: the person's name for it, else its host name, else its short peer id. */
36
+ label: string;
37
+ thisDevice: boolean;
38
+ /**
39
+ * One of the person's own cadrons (on their cadron list and not untrusted), or this device.
40
+ * False: a machine that is not theirs, or one since removed. Null when the list was not given.
41
+ */
42
+ yours: boolean | null;
43
+ /** As on the cadre screen (`cadronPresence`); null when the machine is not on the list. */
44
+ presence: CadronPresence | null;
45
+ alwaysOn: boolean | null;
46
+ /** The ones the invitation names first, in its order, then the ones it could. */
47
+ addresses: InvitationAddressText[];
48
+ }
49
+
50
+ export interface InvitationText {
51
+ expiresAt: string;
52
+ /** Length of the text shared (the link), in characters. */
53
+ linkLength: number;
54
+ /** The smallest QR version (1–40) holding the link at error correction M, or null past 40. */
55
+ qrVersion: number | null;
56
+ /** The addresses it names, in its order. */
57
+ addresses: InvitationAddressText[];
58
+ /** The same, and the `others`, grouped by machine: the ones it names first, in its order. */
59
+ cadrons: InvitationCadronText[];
60
+ /** The person's cap on addresses per invitation, when known. */
61
+ maxAddrs: number | null;
62
+ /** Usable addresses of the person's cadrons (not this device) it leaves out. 0: it names all there are. */
63
+ cadronAddrsLeftOut: number;
64
+ }
65
+
66
+ export interface DescribeOptions {
67
+ /** The text actually shared (the link), for its length. */
68
+ link: string;
69
+ /** The person's own names for their cadrons. */
70
+ names?: Record<string, string>;
71
+ thisDevicePeerId?: string | null;
72
+ /** The person's cadron list (`CadreStatus.machines`): whose each address is, and how each is. */
73
+ machines?: readonly CadreMachine[];
74
+ /** Other usable addresses it could name (`BootstrapPlan` entries and others), best first. */
75
+ others?: readonly string[];
76
+ maxAddrs?: number | null;
77
+ now?: number;
78
+ }
79
+
80
+ /** QR byte-mode capacity at error correction level M, versions 1–40. */
81
+ const QR_CAPACITY_M = [14, 26, 42, 62, 84, 106, 122, 152, 180, 213, 251, 287, 331, 362, 412, 450, 504, 560, 624, 666, 711, 779,
82
+ 857, 911, 997, 1059, 1125, 1190, 1264, 1370, 1452, 1538, 1628, 1722, 1809, 1911, 1989, 2099, 2213, 2331];
83
+
84
+ export function qrVersionFor(length: number): number | null {
85
+ const i = QR_CAPACITY_M.findIndex(cap => cap >= length);
86
+ return i < 0 ? null : i + 1;
87
+ }
88
+
89
+ /** The peer an address ends in (its last `/p2p/`), or '' when it names none or does not parse. */
90
+ export function destinationPeerId(addr: string): string {
91
+ const peers = (addressComponents(addr) ?? []).filter(c => c.name === 'p2p');
92
+ return peers[peers.length - 1]?.value ?? '';
93
+ }
94
+
95
+ function hostAndPort(addr: string): { host: string; port: number | null; via: InvitationAddressText['via'] } {
96
+ const components = addressComponents(addr) ?? [];
97
+ const relayed = components.some(c => c.name === 'p2p-circuit');
98
+ const tcp = components.find(c => c.name === 'tcp');
99
+ const port = tcp?.value ? Number(tcp.value) : NaN;
100
+ const names = new Set(components.map(c => c.name));
101
+ const via = relayed ? 'relay' : names.has('wss') || names.has('tls') ? 'wss' : names.has('ws') ? 'ws' : 'tcp';
102
+ return { host: components[0]?.value ?? '', port: Number.isFinite(port) ? port : null, via };
103
+ }
104
+
105
+ export function describeInvitation(
106
+ invitation: { expiration: Date | string; bootstrap: readonly string[] },
107
+ opts: DescribeOptions,
108
+ ): InvitationText {
109
+ const names = opts.names ?? {};
110
+ const machines = new Map((opts.machines ?? []).map(m => [m.peerId, m]));
111
+ const included = new Set(invitation.bootstrap);
112
+ const others = (opts.others ?? []).filter(addr => !included.has(addr));
113
+ const all = [...invitation.bootstrap, ...others];
114
+ // A machine's host name: from its list entry, else from the addresses here.
115
+ const label = (peerId: string) => names[peerId]?.trim()
116
+ || suggestedName(machines.get(peerId) ?? { addresses: all.filter(a => destinationPeerId(a) === peerId) })
117
+ || shortPeerId(peerId);
118
+ const isThisDevice = (peerId: string) => !!opts.thisDevicePeerId && peerId === opts.thisDevicePeerId;
119
+
120
+ const text = (addr: string, inInvitation: boolean): InvitationAddressText => {
121
+ const peerId = destinationPeerId(addr);
122
+ const kind = addressKind(addr);
123
+ return {
124
+ label: label(peerId), peerId, thisDevice: isThisDevice(peerId), kind, reachesAnywhere: reachesAnywhere(kind),
125
+ ...hostAndPort(addr), addr, included: inInvitation,
126
+ };
127
+ };
128
+ const addresses = invitation.bootstrap.map(addr => text(addr, true));
129
+ const extra = others.map(addr => text(addr, false));
130
+
131
+ const cadrons = new Map<string, InvitationCadronText>();
132
+ for (const a of [...addresses, ...extra]) {
133
+ let c = cadrons.get(a.peerId);
134
+ if (!c) {
135
+ const m = machines.get(a.peerId);
136
+ c = {
137
+ peerId: a.peerId, label: a.label, thisDevice: a.thisDevice,
138
+ yours: a.thisDevice ? true : opts.machines ? !!m && m.trusted !== false : null,
139
+ presence: m ? cadronPresence(m, opts.now) : null,
140
+ alwaysOn: m?.alwaysOn ?? null,
141
+ addresses: [],
142
+ };
143
+ cadrons.set(a.peerId, c);
144
+ }
145
+ c.addresses.push(a);
146
+ }
147
+ return {
148
+ expiresAt: new Date(invitation.expiration).toISOString(),
149
+ linkLength: opts.link.length,
150
+ qrVersion: qrVersionFor(opts.link.length),
151
+ addresses,
152
+ cadrons: [...cadrons.values()],
153
+ maxAddrs: opts.maxAddrs ?? null,
154
+ cadronAddrsLeftOut: extra.filter(a => !a.thisDevice).length,
155
+ };
156
+ }