@rnzeus/heimdall-sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -141,10 +141,11 @@ disconnect();
141
141
  | `deviceName` | `string` | — | name shown in Heimdall |
142
142
  | `appId` | `string` | — | bundle id or any identifier |
143
143
  | `app` | `{ version?, build?, environment? }` | — | app details shown in Heimdall |
144
+ | `device` | `{ id?, isEmulator? }` | — | details the SDK cannot read without native code, e.g. `getUniqueId()` and `isEmulator()` from `react-native-device-info`; helps the cloud tell devices and simulators apart |
144
145
  | `allowedHosts` | `(string \| RegExp)[]` | — | capture only these hosts |
145
146
  | `ignoreUrls` | `(string \| RegExp)[]` | — | skip by full URL or path |
146
147
  | `captureEarlyEvents` | `boolean` | `false` | buffer events that happen before the connection is up |
147
- | `keepAlive` | `boolean` | `false` | reconnect to the last channel on app start |
148
+ | `keepAlive` | `boolean` | `false` | reconnect on app start: to the last channel, or through the cloud again if the last connection came from it |
148
149
  | `captureConsole` | `boolean` | `true` | console, uncaught errors, unhandled rejections |
149
150
  | `cloud` | `{ url: string }` | — | optional, see [Connecting without typing an address](#connecting-without-typing-an-address) |
150
151
 
@@ -169,6 +170,14 @@ With `cloud` set, the prompt gets a second mode:
169
170
 
170
171
  The cloud only stores accounts, devices and the current address of the desktop. Captured traffic never goes through it. Without `cloud` the prompt works in manual mode only.
171
172
 
173
+ **Encryption.** A connection made through the cloud is encrypted with TLS. The desktop app has its own certificate, the cloud passes it to the app, and the SDK checks it before sending anything, so the app talks only to that desktop. A manual connection is not encrypted. Heimdall shows a lock in its title bar for each case. Older Heimdall versions keep working through the cloud without encryption.
174
+
175
+ ![Connection details in Heimdall: an encrypted connection](https://heimdall.rnzeus.dev/readme/connection.png)
176
+
177
+ **One app at a time.** Through the cloud a desktop accepts one app at a time; another app gets a clear message and can connect once the first one disconnects. To inspect several devices at once, connect them manually.
178
+
179
+ **Devices.** A device in the account is a phone, a tablet or a simulator; several apps (for example dev and stage builds) can be linked to it. Linking an Android app to an iPhone, or an emulator to a real device, asks for confirmation. Pass `device` (see [Options](#options)) to make the iOS simulator recognisable too.
180
+
172
181
  ## Production safety
173
182
 
174
183
  - `enabled` defaults to `__DEV__`. In a release build the SDK does nothing unless you pass `enabled: true`.
@@ -221,8 +230,8 @@ A production bundle built this way contains no `heimdall://` strings — only th
221
230
 
222
231
  ## Your data
223
232
 
224
- - Events go **directly** from the app to the Heimdall desktop app over TCP on your network. Nothing is sent to us or to any third party.
225
- - Headers and bodies are sent **as they are**, including auth tokens. Use the SDK in dev and stage builds, and narrow the capture with `allowedHosts` / `ignoreUrls` where needed.
233
+ - Events go **directly** from the app to the Heimdall desktop app over TCP on your network, encrypted with TLS when connected through the cloud. Nothing is sent to us or to any third party.
234
+ - Headers and bodies are sent **as they are**, including auth tokens; a manual connection carries them unencrypted. Use the SDK in dev and stage builds, and narrow the capture with `allowedHosts` / `ignoreUrls` where needed.
226
235
  - `cloud` is optional and never sees captured traffic — see [Connecting without typing an address](#connecting-without-typing-an-address).
227
236
 
228
237
  ## Testing with Jest
@@ -1,3 +1,4 @@
1
+ import type { InstallDevice } from "../system";
1
2
  export declare class CloudUnauthorizedError extends Error {
2
3
  constructor();
3
4
  }
@@ -24,11 +25,19 @@ export type CloudConnection = {
24
25
  port: number;
25
26
  channel: string;
26
27
  hostName: string;
28
+ tls?: {
29
+ cert: string;
30
+ pubkey: string;
31
+ fingerprint256: string;
32
+ };
33
+ token?: string;
27
34
  };
28
- export declare function createClaim({ baseUrl, appId, platform, }: {
35
+ export declare function createClaim({ baseUrl, appId, platform, installId, device, }: {
29
36
  baseUrl: string;
30
37
  appId?: string;
31
38
  platform?: string;
39
+ installId?: string;
40
+ device?: InstallDevice;
32
41
  }): Promise<CloudClaim>;
33
42
  export declare function pollClaim({ baseUrl, code, }: {
34
43
  baseUrl: string;
@@ -24,12 +24,12 @@ async function request({ baseUrl, path, method = "GET", token, body, }) {
24
24
  clearTimeout(timeout);
25
25
  }
26
26
  }
27
- export async function createClaim({ baseUrl, appId, platform, }) {
27
+ export async function createClaim({ baseUrl, appId, platform, installId, device, }) {
28
28
  const { status, data } = await request({
29
29
  baseUrl,
30
30
  path: "/claims",
31
31
  method: "POST",
32
- body: { appId, platform },
32
+ body: { appId, platform, installId, device },
33
33
  });
34
34
  if (status !== 201)
35
35
  throw new Error(`Cloud error ${status}`);
@@ -1,3 +1,4 @@
1
+ import type { InstallDevice } from "../system";
1
2
  export type LinkDeviceResult = {
2
3
  status: "linked";
3
4
  deviceName: string;
@@ -6,9 +7,11 @@ export type LinkDeviceResult = {
6
7
  } | {
7
8
  status: "cancelled";
8
9
  };
9
- export declare function linkDevice({ baseUrl, appId, platform, isCancelled, }: {
10
+ export declare function linkDevice({ baseUrl, appId, platform, installId, device, isCancelled, }: {
10
11
  baseUrl: string;
11
12
  appId?: string;
12
13
  platform?: string;
14
+ installId?: string;
15
+ device?: InstallDevice;
13
16
  isCancelled: () => boolean;
14
17
  }): Promise<LinkDeviceResult>;
@@ -3,8 +3,14 @@ import { createClaim, pollClaim } from "./client.js";
3
3
  import { saveCloudDevice } from "./storage.js";
4
4
  const POLL_INTERVAL_MS = 2000;
5
5
  const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
6
- export async function linkDevice({ baseUrl, appId, platform, isCancelled, }) {
7
- const claim = await createClaim({ baseUrl, appId, platform });
6
+ export async function linkDevice({ baseUrl, appId, platform, installId, device, isCancelled, }) {
7
+ const claim = await createClaim({
8
+ baseUrl,
9
+ appId,
10
+ platform,
11
+ installId,
12
+ device,
13
+ });
8
14
  await Linking.openURL(claim.url);
9
15
  while (Date.now() < claim.expiresAt) {
10
16
  await delay(POLL_INTERVAL_MS);
@@ -1,2 +1,7 @@
1
1
  import type { HeimdallConnectOptions } from "../../../types";
2
+ import type { ConnectionTarget } from "../resolver";
2
3
  export declare function connect(options: HeimdallConnectOptions): void;
4
+ export declare function connectToCloudTarget({ defaults, target, }: {
5
+ defaults: Omit<HeimdallConnectOptions, "channel">;
6
+ target: ConnectionTarget;
7
+ }): void;
@@ -2,10 +2,13 @@ import { patchXHR } from "../../network/index.js";
2
2
  import { patchWebSocket } from "../../websocket/index.js";
3
3
  import { patchConsole } from "../../console/index.js";
4
4
  import { resolveEnabled, setSdkEnabled } from "../sdk-enabled.js";
5
- import { createSession, setCurrentSession } from "../session/index.js";
5
+ import { createSession, setCurrentSession, } from "../session/index.js";
6
6
  import { connectSocket } from "../socket/index.js";
7
- import { registerCloudUrl } from "../../cloud/state.js";
7
+ import { registerCloudUrl, setLastCloudTarget } from "../../cloud/state.js";
8
8
  export function connect(options) {
9
+ connectWithTransport({ options });
10
+ }
11
+ function connectWithTransport({ options, secure, source, }) {
9
12
  var _a;
10
13
  const enabled = resolveEnabled(options.enabled);
11
14
  if (!enabled) {
@@ -14,7 +17,10 @@ export function connect(options) {
14
17
  }
15
18
  setSdkEnabled(true);
16
19
  registerCloudUrl((_a = options.cloud) === null || _a === void 0 ? void 0 : _a.url);
17
- const session = createSession(options);
20
+ const session = {
21
+ ...createSession(options, source),
22
+ ...(secure ? { secure } : {}),
23
+ };
18
24
  setCurrentSession(session);
19
25
  try {
20
26
  connectSocket(session);
@@ -44,3 +50,16 @@ export function connect(options) {
44
50
  patchConsole();
45
51
  }
46
52
  }
53
+ export function connectToCloudTarget({ defaults, target, }) {
54
+ setLastCloudTarget({ channel: target.channel, hostName: target.hostName });
55
+ connectWithTransport({
56
+ options: {
57
+ ...defaults,
58
+ host: target.host,
59
+ port: target.port,
60
+ channel: target.channel,
61
+ },
62
+ secure: target.secure,
63
+ source: "cloud",
64
+ });
65
+ }
@@ -2,13 +2,24 @@ import { setPromptDefaults } from "../prompt/index.js";
2
2
  import { loadLastConnection } from "../session/index.js";
3
3
  import { setSdkEnabled, resolveEnabled } from "../sdk-enabled.js";
4
4
  import { setupEarlyEvents } from "./early-events.js";
5
- import { connect } from "./connect.js";
5
+ import { connect, connectToCloudTarget } from "./connect.js";
6
6
  import { registerCloudUrl } from "../../cloud/state.js";
7
+ import { createCloudResolver } from "../resolver/index.js";
8
+ async function reconnectThroughCloud({ defaults, baseUrl, }) {
9
+ try {
10
+ const target = await createCloudResolver({ baseUrl }).resolve();
11
+ if (target)
12
+ connectToCloudTarget({ defaults, target });
13
+ }
14
+ catch {
15
+ // stay disconnected: the prompt offers Connect
16
+ }
17
+ }
7
18
  /**
8
19
  * Configure connect prompt + captureEarlyEvents + keepAlive.
9
20
  */
10
21
  export function configureConnectPrompt(defaults) {
11
- var _a;
22
+ var _a, _b;
12
23
  const { captureEarlyEvents, keepAlive, enabled, ...rest } = defaults;
13
24
  const resolvedEnabled = resolveEnabled(enabled);
14
25
  if (!resolvedEnabled) {
@@ -28,7 +39,15 @@ export function configureConnectPrompt(defaults) {
28
39
  // keepAlive: auto-connect, if there is a last connection
29
40
  if (keepAlive) {
30
41
  const last = loadLastConnection();
31
- if (last && last.host && last.port && last.channel) {
42
+ if ((last === null || last === void 0 ? void 0 : last.source) === "cloud") {
43
+ if ((_b = rest.cloud) === null || _b === void 0 ? void 0 : _b.url) {
44
+ void reconnectThroughCloud({
45
+ defaults: { ...rest, enabled: resolvedEnabled },
46
+ baseUrl: rest.cloud.url,
47
+ });
48
+ }
49
+ }
50
+ else if (last && last.host && last.port && last.channel) {
32
51
  connect({
33
52
  ...rest,
34
53
  ...last,
@@ -17,6 +17,9 @@ export function createCloudResolver({ baseUrl, }) {
17
17
  port: connection.port,
18
18
  channel: connection.channel,
19
19
  hostName: connection.hostName,
20
+ ...(connection.tls && connection.token
21
+ ? { secure: { ...connection.tls, token: connection.token } }
22
+ : {}),
20
23
  };
21
24
  }
22
25
  catch (error) {
@@ -1,8 +1,10 @@
1
+ import type { SecureTransport } from "../socket/secure-transport";
1
2
  export type ConnectionTarget = {
2
3
  host: string;
3
4
  port: number;
4
5
  channel: string;
5
6
  hostName?: string;
7
+ secure?: SecureTransport;
6
8
  };
7
9
  export type ConnectionResolver = {
8
10
  resolve: () => Promise<ConnectionTarget | null>;
@@ -4,6 +4,7 @@ export function clearLastConnection() {
4
4
  SESSION_STORAGE.delete(SESSION.KEY_LAST_HOST);
5
5
  SESSION_STORAGE.delete(SESSION.KEY_LAST_PORT);
6
6
  SESSION_STORAGE.delete(SESSION.KEY_LAST_CHANNEL);
7
+ SESSION_STORAGE.delete(SESSION.KEY_LAST_SOURCE);
7
8
  }
8
9
  catch {
9
10
  // ignore
@@ -4,6 +4,7 @@ export declare const SESSION: {
4
4
  KEY_LAST_HOST: string;
5
5
  KEY_LAST_PORT: string;
6
6
  KEY_LAST_CHANNEL: string;
7
+ KEY_LAST_SOURCE: string;
7
8
  };
8
9
  type SessionStorage = {
9
10
  getString(key: string): string | undefined;
@@ -5,6 +5,7 @@ export const SESSION = {
5
5
  KEY_LAST_HOST: "lastHost",
6
6
  KEY_LAST_PORT: "lastPort",
7
7
  KEY_LAST_CHANNEL: "lastChannel",
8
+ KEY_LAST_SOURCE: "lastSource",
8
9
  };
9
10
  function createSessionStorage() {
10
11
  const mmkv = MMKVModule;
@@ -1,3 +1,3 @@
1
1
  import type { HeimdallConnectOptions } from "../../../types";
2
- import type { HeimdallSession } from "./types";
3
- export declare function createSession(options: HeimdallConnectOptions): HeimdallSession;
2
+ import type { ConnectionSource, HeimdallSession } from "./types";
3
+ export declare function createSession(options: HeimdallConnectOptions, source?: ConnectionSource): HeimdallSession;
@@ -1,6 +1,6 @@
1
1
  import { getOrCreateClientId, generateClientId } from "./client-id.js";
2
2
  import { SESSION_STORAGE, SESSION } from "./constants.js";
3
- export function createSession(options) {
3
+ export function createSession(options, source = "manual") {
4
4
  const clientId = getOrCreateClientId();
5
5
  const sessionId = generateClientId();
6
6
  const createdAt = new Date().toISOString();
@@ -8,6 +8,7 @@ export function createSession(options) {
8
8
  SESSION_STORAGE.set(SESSION.KEY_LAST_HOST, options.host);
9
9
  SESSION_STORAGE.set(SESSION.KEY_LAST_PORT, String(options.port));
10
10
  SESSION_STORAGE.set(SESSION.KEY_LAST_CHANNEL, options.channel);
11
+ SESSION_STORAGE.set(SESSION.KEY_LAST_SOURCE, source);
11
12
  }
12
13
  catch {
13
14
  // ignore
@@ -6,9 +6,12 @@ export function loadLastConnection() {
6
6
  const portString = SESSION_STORAGE.getString(SESSION.KEY_LAST_PORT);
7
7
  const channel = (_b = SESSION_STORAGE.getString(SESSION.KEY_LAST_CHANNEL)) !== null && _b !== void 0 ? _b : undefined;
8
8
  const port = portString ? Number(portString) : undefined;
9
+ const source = SESSION_STORAGE.getString(SESSION.KEY_LAST_SOURCE) === "cloud"
10
+ ? "cloud"
11
+ : "manual";
9
12
  if (!host && !port && !channel)
10
13
  return null;
11
- return { host, port, channel };
14
+ return { host, port, channel, source };
12
15
  }
13
16
  catch {
14
17
  return null;
@@ -1,12 +1,17 @@
1
1
  import type { HeimdallConnectOptions } from "../../../types";
2
+ import type { SecureTransport } from "../socket/secure-transport";
2
3
  export type HeimdallSession = {
3
4
  clientId: string;
4
5
  sessionId: string;
5
6
  createdAt: string;
6
7
  options: HeimdallConnectOptions;
8
+ secure?: SecureTransport;
7
9
  };
10
+ export type ConnectionSource = "cloud" | "manual";
8
11
  export type LastConnection = {
9
12
  host?: string;
10
13
  port?: number;
11
14
  channel?: string;
15
+ /** cloud connections are resolved again (fresh certificate and token), never replayed in plaintext */
16
+ source?: ConnectionSource;
12
17
  };
@@ -1,3 +1,4 @@
1
+ import { Platform } from "react-native";
1
2
  import TcpSocket from "react-native-tcp-socket";
2
3
  import { isConnected, getSocket, setConnected, setSocket, setLastError, } from "./state.js";
3
4
  import { handleSocketLost } from "./handle-socket-lost.js";
@@ -7,6 +8,36 @@ import { SOCKET } from "./constants.js";
7
8
  import { getCurrentSession, setCurrentSession, } from "../session/index.js";
8
9
  import { SDK_VERSION } from "../../../version.js";
9
10
  import { normaliseAppInfo, readDeviceInfo } from "../../system/index.js";
11
+ import { CERTIFICATE_MISMATCH, NO_ANSWER, matchesPin, parseHostAnswer, readPeerCertificate, rejectionMessage, } from "./secure-transport.js";
12
+ const HOST_ANSWER_TIMEOUT_MS = 5000;
13
+ function buildHello({ session, options, secure, }) {
14
+ var _a, _b;
15
+ const activeSession = getCurrentSession();
16
+ const hello = {
17
+ kind: "hello",
18
+ v: 1,
19
+ channel: options.channel,
20
+ clientId: (_a = activeSession === null || activeSession === void 0 ? void 0 : activeSession.clientId) !== null && _a !== void 0 ? _a : session.clientId,
21
+ sessionId: (_b = activeSession === null || activeSession === void 0 ? void 0 : activeSession.sessionId) !== null && _b !== void 0 ? _b : session.sessionId,
22
+ deviceName: options.deviceName,
23
+ platform: options.platform,
24
+ appId: options.appId,
25
+ sdkVersion: SDK_VERSION,
26
+ };
27
+ const device = readDeviceInfo();
28
+ if (device)
29
+ hello.device = device;
30
+ const app = normaliseAppInfo(options.app);
31
+ if (app)
32
+ hello.app = app;
33
+ if (secure)
34
+ hello.auth = { token: secure.token };
35
+ return hello;
36
+ }
37
+ function fail(message) {
38
+ setLastError(message);
39
+ handleSocketLost();
40
+ }
10
41
  export function connectSocket(optionsOrSession) {
11
42
  var _a, _b, _c;
12
43
  setLastError(null);
@@ -52,41 +83,64 @@ export function connectSocket(optionsOrSession) {
52
83
  }
53
84
  // Update the current session to the new one
54
85
  setCurrentSession(session);
55
- const newSocket = TcpSocket.createConnection({
56
- host: options.host,
57
- port: options.port,
58
- }, () => {
59
- var _a, _b;
86
+ const secure = session.secure;
87
+ const onPlainConnect = () => {
60
88
  clearTimeout(connectTimeout);
61
89
  setConnected(true);
62
- // Take the actual session (if it changed)
63
- const activeSession = getCurrentSession();
64
- const hello = {
65
- kind: "hello",
66
- v: 1,
67
- channel: options.channel,
68
- clientId: (_a = activeSession === null || activeSession === void 0 ? void 0 : activeSession.clientId) !== null && _a !== void 0 ? _a : session.clientId,
69
- sessionId: (_b = activeSession === null || activeSession === void 0 ? void 0 : activeSession.sessionId) !== null && _b !== void 0 ? _b : session.sessionId,
70
- deviceName: options.deviceName,
71
- platform: options.platform,
72
- appId: options.appId,
73
- sdkVersion: SDK_VERSION,
74
- };
75
- const device = readDeviceInfo();
76
- if (device)
77
- hello.device = device;
78
- const app = normaliseAppInfo(options.app);
79
- if (app)
80
- hello.app = app;
81
90
  try {
82
- newSocket.write(JSON.stringify(hello) + "\r\n");
91
+ newSocket.write(JSON.stringify(buildHello({ session, options })) + "\r\n");
83
92
  }
84
93
  catch {
85
94
  // ignore
86
95
  }
87
- // After successful HELLO, send early events
88
96
  flushEarlyEvents();
89
- });
97
+ };
98
+ const onSecureConnect = async () => {
99
+ const peer = await readPeerCertificate(newSocket);
100
+ if (getSocket() !== newSocket)
101
+ return;
102
+ if (!secure || !matchesPin({ peer, secure, platform: Platform.OS })) {
103
+ clearTimeout(connectTimeout);
104
+ fail(CERTIFICATE_MISMATCH);
105
+ return;
106
+ }
107
+ let pending = "";
108
+ const answerTimeout = setTimeout(() => {
109
+ if (getSocket() === newSocket && !isConnected())
110
+ fail(NO_ANSWER);
111
+ }, HOST_ANSWER_TIMEOUT_MS);
112
+ const onData = (data) => {
113
+ var _a;
114
+ pending += typeof data === "string" ? data : String(data);
115
+ const end = pending.indexOf("\r\n");
116
+ if (end === -1)
117
+ return;
118
+ (_a = newSocket.off) === null || _a === void 0 ? void 0 : _a.call(newSocket, "data", onData);
119
+ clearTimeout(answerTimeout);
120
+ clearTimeout(connectTimeout);
121
+ const answer = parseHostAnswer(pending.slice(0, end));
122
+ if (!answer) {
123
+ fail(NO_ANSWER);
124
+ return;
125
+ }
126
+ if (!answer.accepted) {
127
+ fail(rejectionMessage(answer.reason));
128
+ return;
129
+ }
130
+ setConnected(true);
131
+ flushEarlyEvents();
132
+ };
133
+ newSocket.on("data", onData);
134
+ try {
135
+ newSocket.write(JSON.stringify(buildHello({ session, options, secure })) + "\r\n");
136
+ }
137
+ catch {
138
+ // the error listener reports it
139
+ }
140
+ };
141
+ const newSocket = secure
142
+ ? TcpSocket.connectTLS({ host: options.host, port: options.port, ca: secure.cert }, () => void onSecureConnect())
143
+ : TcpSocket.createConnection({ host: options.host, port: options.port }, onPlainConnect);
90
144
  const connectTimeout = setTimeout(() => {
91
145
  if (getSocket() !== newSocket || isConnected())
92
146
  return;
@@ -0,0 +1,35 @@
1
+ import type { HelloRejectReason } from "@rnzeus/heimdall-protocol";
2
+ /** Host certificate and session token from heimdall-cloud; kept in memory only. */
3
+ export type SecureTransport = {
4
+ cert: string;
5
+ pubkey: string;
6
+ fingerprint256: string;
7
+ token: string;
8
+ };
9
+ export type PeerCertificate = {
10
+ pubkey?: string;
11
+ fingerprint256?: string;
12
+ };
13
+ /**
14
+ * react-native-tcp-socket ignores `ca` on iOS, so the host is pinned here, before anything is sent:
15
+ * iOS exposes the public key, Android the certificate fingerprint.
16
+ */
17
+ export declare function matchesPin({ peer, secure, platform, }: {
18
+ peer: PeerCertificate | null;
19
+ secure: SecureTransport;
20
+ platform: string;
21
+ }): boolean;
22
+ /** Older react-native-tcp-socket reports `secureConnect` before the handshake ends. */
23
+ export declare function readPeerCertificate(socket: {
24
+ getPeerCertificate: () => unknown;
25
+ }): Promise<PeerCertificate | null>;
26
+ export type HostAnswer = {
27
+ accepted: true;
28
+ } | {
29
+ accepted: false;
30
+ reason?: HelloRejectReason;
31
+ };
32
+ export declare function parseHostAnswer(line: string): HostAnswer | null;
33
+ export declare function rejectionMessage(reason?: HelloRejectReason): string;
34
+ export declare const CERTIFICATE_MISMATCH = "Heimdall certificate does not match. Connect again from the prompt.";
35
+ export declare const NO_ANSWER = "Heimdall did not answer. Update Heimdall.";
@@ -0,0 +1,71 @@
1
+ const REJECT_REASONS = [
2
+ "auth",
3
+ "channel",
4
+ "version",
5
+ ];
6
+ const PEER_POLL_ATTEMPTS = 30;
7
+ const PEER_POLL_INTERVAL_MS = 100;
8
+ /**
9
+ * react-native-tcp-socket ignores `ca` on iOS, so the host is pinned here, before anything is sent:
10
+ * iOS exposes the public key, Android the certificate fingerprint.
11
+ */
12
+ export function matchesPin({ peer, secure, platform, }) {
13
+ if (!peer)
14
+ return false;
15
+ if (platform === "ios")
16
+ return peer.pubkey === secure.pubkey;
17
+ return peer.fingerprint256 === secure.fingerprint256;
18
+ }
19
+ /** Older react-native-tcp-socket reports `secureConnect` before the handshake ends. */
20
+ export async function readPeerCertificate(socket) {
21
+ for (let attempt = 0; attempt < PEER_POLL_ATTEMPTS; attempt++) {
22
+ try {
23
+ const peer = (await socket.getPeerCertificate());
24
+ if (peer && (peer.pubkey || peer.fingerprint256))
25
+ return peer;
26
+ }
27
+ catch {
28
+ // not ready yet
29
+ }
30
+ await new Promise((resolve) => setTimeout(() => resolve(), PEER_POLL_INTERVAL_MS));
31
+ }
32
+ return null;
33
+ }
34
+ // Hand-written on purpose: the protocol schemas would pull zod into every consumer app. Mirrors the
35
+ // tolerant HelloAckWireMessageV1Schema: extra fields are ignored, an unknown reason becomes undefined.
36
+ export function parseHostAnswer(line) {
37
+ let json;
38
+ try {
39
+ json = JSON.parse(line);
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ if (!json || typeof json !== "object")
45
+ return null;
46
+ const { kind, v, status, reason } = json;
47
+ if (kind !== "helloAck" || v !== 1)
48
+ return null;
49
+ if (status === "accepted")
50
+ return { accepted: true };
51
+ if (status !== "rejected")
52
+ return null;
53
+ return {
54
+ accepted: false,
55
+ reason: REJECT_REASONS.find((known) => known === reason),
56
+ };
57
+ }
58
+ export function rejectionMessage(reason) {
59
+ switch (reason) {
60
+ case "auth":
61
+ return "Heimdall was restarted. Connect again.";
62
+ case "version":
63
+ return "This Heimdall is too old for the SDK. Update Heimdall.";
64
+ case "channel":
65
+ return "Heimdall is connected to another app. Disconnect it there or in Heimdall, or use manual mode.";
66
+ default:
67
+ return "Heimdall refused the connection.";
68
+ }
69
+ }
70
+ export const CERTIFICATE_MISMATCH = "Heimdall certificate does not match. Connect again from the prompt.";
71
+ export const NO_ANSWER = "Heimdall did not answer. Update Heimdall.";
@@ -1,3 +1,16 @@
1
1
  import type { HelloAppInfo, HelloDeviceInfo } from "../../types";
2
2
  export declare function readDeviceInfo(): HelloDeviceInfo | undefined;
3
+ export type InstallDevice = {
4
+ os?: string;
5
+ osVersion?: string;
6
+ model?: string;
7
+ manufacturer?: string;
8
+ idiom?: string;
9
+ emulator?: boolean;
10
+ id?: string;
11
+ };
12
+ export declare function readInstallDevice(override?: {
13
+ id?: string;
14
+ isEmulator?: boolean;
15
+ }): InstallDevice;
3
16
  export declare function normaliseAppInfo(app: unknown): HelloAppInfo | undefined;
@@ -1,4 +1,5 @@
1
1
  import { Platform } from "react-native";
2
+ import { isAndroidEmulator } from "./emulator.js";
2
3
  const text = (value) => {
3
4
  if (value === null || value === undefined)
4
5
  return undefined;
@@ -34,6 +35,26 @@ export function readDeviceInfo() {
34
35
  return undefined;
35
36
  }
36
37
  }
38
+ export function readInstallDevice(override) {
39
+ var _a;
40
+ const base = { ...readDeviceInfo() };
41
+ try {
42
+ const constants = (_a = Platform.constants) !== null && _a !== void 0 ? _a : {};
43
+ if (Platform.OS === "android")
44
+ base.emulator = isAndroidEmulator(constants);
45
+ else
46
+ base.idiom = text(constants.interfaceIdiom);
47
+ }
48
+ catch {
49
+ // ignore
50
+ }
51
+ if (typeof (override === null || override === void 0 ? void 0 : override.isEmulator) === "boolean")
52
+ base.emulator = override.isEmulator;
53
+ const id = text(override === null || override === void 0 ? void 0 : override.id);
54
+ if (id)
55
+ base.id = id;
56
+ return base;
57
+ }
37
58
  export function normaliseAppInfo(app) {
38
59
  if (!app || typeof app !== "object")
39
60
  return undefined;
@@ -0,0 +1 @@
1
+ export declare function isAndroidEmulator(constants: Record<string, unknown>): boolean;
@@ -0,0 +1,8 @@
1
+ const ANDROID_EMULATOR = /generic|emulator|sdk_gphone|google_sdk|android sdk built for|genymotion|vbox/i;
2
+ const FIELDS = ["Fingerprint", "Model", "Brand", "Manufacturer"];
3
+ export function isAndroidEmulator(constants) {
4
+ return FIELDS.some((key) => {
5
+ const value = constants[key];
6
+ return typeof value === "string" && ANDROID_EMULATOR.test(value);
7
+ });
8
+ }
@@ -1,6 +1,7 @@
1
1
  import { useCallback, useEffect, useRef, useState } from "react";
2
- import { clearCloudDevice, linkDevice, loadCloudDevice, setLastCloudTarget, unlinkDevice, } from "../../../core/cloud/index.js";
3
- import { connect, createCloudResolver, getPromptState, } from "../../../core/connection/index.js";
2
+ import { clearCloudDevice, linkDevice, loadCloudDevice, unlinkDevice, } from "../../../core/cloud/index.js";
3
+ import { connectToCloudTarget, createCloudResolver, getOrCreateClientId, getPromptState, } from "../../../core/connection/index.js";
4
+ import { readInstallDevice } from "../../../core/system/index.js";
4
5
  const useCloudView = ({ baseUrl, visible, startConnecting, }) => {
5
6
  const [deviceName, setDeviceName] = useState(() => { var _a, _b; return (_b = (_a = loadCloudDevice()) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : null; });
6
7
  const [phase, setPhase] = useState("idle");
@@ -25,6 +26,8 @@ const useCloudView = ({ baseUrl, visible, startConnecting, }) => {
25
26
  baseUrl,
26
27
  appId: defaults === null || defaults === void 0 ? void 0 : defaults.appId,
27
28
  platform: defaults === null || defaults === void 0 ? void 0 : defaults.platform,
29
+ installId: getOrCreateClientId(),
30
+ device: readInstallDevice(defaults === null || defaults === void 0 ? void 0 : defaults.device),
28
31
  isCancelled: () => cancelledRef.current,
29
32
  });
30
33
  if (result.status === "linked")
@@ -57,13 +60,7 @@ const useCloudView = ({ baseUrl, visible, startConnecting, }) => {
57
60
  setMessage(`Start Heimdall for ${deviceName !== null && deviceName !== void 0 ? deviceName : "this device"} first.`);
58
61
  return;
59
62
  }
60
- setLastCloudTarget({ channel: target.channel, hostName: target.hostName });
61
- startConnecting(() => connect({
62
- ...defaults,
63
- host: target.host,
64
- port: target.port,
65
- channel: target.channel,
66
- }));
63
+ startConnecting(() => connectToCloudTarget({ defaults, target }));
67
64
  }
68
65
  catch {
69
66
  const stillLinked = loadCloudDevice();
@@ -23,6 +23,14 @@ export type HeimdallConnectOptions = {
23
23
  build?: string;
24
24
  environment?: string;
25
25
  };
26
+ /**
27
+ * device details the SDK cannot read without native code, e.g. from react-native-device-info:
28
+ * `getUniqueId()` and `isEmulator()`; helps Heimdall cloud tell devices and simulators apart
29
+ */
30
+ device?: {
31
+ id?: string;
32
+ isEmulator?: boolean;
33
+ };
26
34
  /** heimdall-cloud service: enables "Find me" device linking in the connect prompt */
27
35
  cloud?: {
28
36
  url: string;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.3.0";
1
+ export declare const SDK_VERSION = "0.4.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.3.0";
1
+ export const SDK_VERSION = "0.4.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rnzeus/heimdall-sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "React Native client for Heimdall — a desktop debug inspector for network, WebSocket, Zustand and console",
5
5
  "license": "MIT",
6
6
  "author": "Volodymyr Dudkevych",
@@ -76,7 +76,8 @@
76
76
  "dev": "tsc -p tsconfig.build.json -w",
77
77
  "typecheck": "node scripts/write-version.mjs && tsc -p tsconfig.json --noEmit",
78
78
  "knip": "knip",
79
- "dupes": "jscpd"
79
+ "dupes": "jscpd",
80
+ "test": "vitest run"
80
81
  },
81
82
  "peerDependencies": {
82
83
  "react": ">=18.0.0",
@@ -91,7 +92,7 @@
91
92
  }
92
93
  },
93
94
  "dependencies": {
94
- "@rnzeus/heimdall-protocol": "^0.2.0"
95
+ "@rnzeus/heimdall-protocol": "^0.3.0"
95
96
  },
96
97
  "devDependencies": {
97
98
  "@types/node": "^25.0.3",
@@ -104,6 +105,8 @@
104
105
  "react-native-tcp-socket": "^6.3.0",
105
106
  "rimraf": "^6.0.0",
106
107
  "typescript": "^5.7.2",
108
+ "vite": "7.3.7",
109
+ "vitest": "^5.0.3",
107
110
  "zustand": "^4.0.0"
108
111
  },
109
112
  "packageManager": "yarn@4.6.0",