@rnzeus/heimdall-sdk 0.2.4 → 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.
Files changed (38) hide show
  1. package/README.md +56 -4
  2. package/dist/core/cloud/client.d.ts +10 -1
  3. package/dist/core/cloud/client.js +2 -2
  4. package/dist/core/cloud/link-device.d.ts +4 -1
  5. package/dist/core/cloud/link-device.js +8 -2
  6. package/dist/core/connection/lifecycle/connect.d.ts +5 -0
  7. package/dist/core/connection/lifecycle/connect.js +22 -3
  8. package/dist/core/connection/lifecycle/keep-alive.js +22 -3
  9. package/dist/core/connection/resolver/cloud.js +3 -0
  10. package/dist/core/connection/resolver/types.d.ts +2 -0
  11. package/dist/core/connection/session/clear-last-connection.js +1 -0
  12. package/dist/core/connection/session/constants.d.ts +1 -0
  13. package/dist/core/connection/session/constants.js +1 -0
  14. package/dist/core/connection/session/create-session.d.ts +2 -2
  15. package/dist/core/connection/session/create-session.js +2 -1
  16. package/dist/core/connection/session/load-last-connection.js +4 -1
  17. package/dist/core/connection/session/types.d.ts +5 -0
  18. package/dist/core/connection/socket/connect-socket.js +81 -27
  19. package/dist/core/connection/socket/secure-transport.d.ts +35 -0
  20. package/dist/core/connection/socket/secure-transport.js +71 -0
  21. package/dist/core/system/device-info.d.ts +13 -0
  22. package/dist/core/system/device-info.js +21 -0
  23. package/dist/core/system/emulator.d.ts +1 -0
  24. package/dist/core/system/emulator.js +8 -0
  25. package/dist/noop/index.d.ts +7 -0
  26. package/dist/noop/index.js +10 -0
  27. package/dist/noop/zustand.d.ts +2 -0
  28. package/dist/noop/zustand.js +1 -0
  29. package/dist/public/prompt/views/use-cloud-view.js +6 -9
  30. package/dist/types/options.d.ts +8 -0
  31. package/dist/version.d.ts +1 -1
  32. package/dist/version.js +1 -1
  33. package/metro/index.cjs +91 -0
  34. package/noop/index.d.ts +1 -0
  35. package/noop/index.js +1 -0
  36. package/noop/zustand.d.ts +1 -0
  37. package/noop/zustand.js +1 -0
  38. package/package.json +28 -5
package/README.md CHANGED
@@ -83,7 +83,7 @@ Host to use:
83
83
  | Android emulator | `10.0.2.2` |
84
84
  | Real device | LAN IP of the machine running Heimdall |
85
85
 
86
- On a real iOS device the first connection triggers the Local Network permission dialog, so `NSLocalNetworkUsageDescription` must be set in `Info.plist`.
86
+ On a real iOS device the first connection triggers the Local Network permission dialog. `NSLocalNetworkUsageDescription` in `Info.plist` sets the text of that dialog; it is optional — without it iOS shows a generic message.
87
87
 
88
88
  ## Zustand
89
89
 
@@ -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,17 +170,68 @@ 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`.
175
184
  - When disabled there are no patches, no sockets and no subscriptions.
176
185
  - Patches are transparent: original behaviour and return values are preserved, and SDK errors never reach your app.
177
186
  - Payloads are capped: JSON bodies at 500 KB, text at 200 KB, everything else at 50 KB, console messages at 8 KB.
187
+ - `enabled: false` turns the SDK off, but its code and native modules stay in the build. To remove them, see below.
188
+
189
+ ## Removing the SDK from production builds
190
+
191
+ This is optional: without it the SDK works as described above. With `enabled: false` the SDK is off, but its code and `react-native-tcp-socket` are still in the build. To leave them out of production builds:
192
+
193
+ **1. Replace the SDK with no-ops in `metro.config.js`:**
194
+
195
+ ```js
196
+ const { getDefaultConfig, mergeConfig } = require("@react-native/metro-config");
197
+ const { withHeimdall } = require("@rnzeus/heimdall-sdk/metro");
198
+
199
+ const config = mergeConfig(getDefaultConfig(__dirname), {
200
+ // your config
201
+ });
202
+
203
+ module.exports = withHeimdall(config, {
204
+ include: process.env.APP_ENV !== "production",
205
+ });
206
+ ```
207
+
208
+ - `include: false` — `@rnzeus/heimdall-sdk` and `@rnzeus/heimdall-sdk/zustand` are replaced with modules that have the same API and do nothing: `connect` and the other calls are no-ops, `<HeimdallConnectPrompt />` renders nothing, `heimdallZustand` returns your store creator as is. Your code does not change.
209
+ - `include: true` — the config is returned unchanged.
210
+ - The `include` option has no default, so the choice is always explicit. Wrap your final config, after any other wrappers.
211
+ - Any other runtime import of the SDK, such as `@rnzeus/heimdall-sdk/dist/...`, fails the build with an error that names the file. Type-only imports (`import type`) are fine.
212
+
213
+ **2. Leave the native module out** in `react-native.config.js`:
214
+
215
+ ```js
216
+ const production = process.env.APP_ENV === "production";
217
+
218
+ module.exports = {
219
+ dependencies: production
220
+ ? { "react-native-tcp-socket": { platforms: { ios: null, android: null } } }
221
+ : {},
222
+ };
223
+ ```
224
+
225
+ Do this only together with step 1, otherwise the app crashes on the missing native module. The setting applies to the whole `pod install` run, so run `pod install` again without the variable before a dev or stage build. Leave `react-native-mmkv` alone if your app uses it for anything else.
226
+
227
+ **Which variable to use.** Both files read environment variables of the build process. Use one that is set for the whole build — usually a variable of your CI job, such as the build stage. Values from `.env` files are not visible here. `APP_ENV` above is only an example.
228
+
229
+ A production bundle built this way contains no `heimdall://` strings — only the no-op names, such as `heimdallZustand`. With Expo, step 1 works as is; for step 2 use your own config plugin.
178
230
 
179
231
  ## Your data
180
232
 
181
- - 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.
182
- - 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.
183
235
  - `cloud` is optional and never sees captured traffic — see [Connecting without typing an address](#connecting-without-typing-an-address).
184
236
 
185
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
+ }
@@ -0,0 +1,7 @@
1
+ import type * as Sdk from "../index";
2
+ export type { HeimdallConnectOptions } from "../types/public";
3
+ export type { Channel } from "../core/public";
4
+ export declare const connect: typeof Sdk.connect, disconnect: typeof Sdk.disconnect, configureConnectPrompt: typeof Sdk.configureConnectPrompt, showSDKConnectPrompt: typeof Sdk.showSDKConnectPrompt, HeimdallConnectPrompt: {
5
+ ({ onCopyToClipboard, }: import("../public/prompt/types").Props): import("react").JSX.Element | null;
6
+ displayName: string;
7
+ };
@@ -0,0 +1,10 @@
1
+ const noop = {
2
+ connect: () => { },
3
+ disconnect: () => { },
4
+ configureConnectPrompt: () => { },
5
+ showSDKConnectPrompt: () => { },
6
+ HeimdallConnectPrompt: Object.assign(() => null, {
7
+ displayName: "HeimdallConnectPrompt",
8
+ }),
9
+ };
10
+ export const { connect, disconnect, configureConnectPrompt, showSDKConnectPrompt, HeimdallConnectPrompt, } = noop;
@@ -0,0 +1,2 @@
1
+ import type * as Sdk from "../zustand";
2
+ export declare const heimdallZustand: typeof Sdk.heimdallZustand;
@@ -0,0 +1 @@
1
+ export const heimdallZustand = (_storeName, createState) => createState;
@@ -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.2.4";
1
+ export declare const SDK_VERSION = "0.4.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.2.4";
1
+ export const SDK_VERSION = "0.4.0";
@@ -0,0 +1,91 @@
1
+ const path = require("node:path");
2
+
3
+ const PACKAGE = "@rnzeus/heimdall-sdk";
4
+
5
+ const NOOP_FILES = {
6
+ [PACKAGE]: path.resolve(__dirname, "../dist/noop/index.js"),
7
+ [`${PACKAGE}/zustand`]: path.resolve(__dirname, "../dist/noop/zustand.js"),
8
+ };
9
+
10
+ const NOOP_ENTRIES = new Set([`${PACKAGE}/noop`, `${PACKAGE}/noop/zustand`]);
11
+
12
+ const isSdkImport = (moduleName) =>
13
+ moduleName === PACKAGE || moduleName.startsWith(`${PACKAGE}/`);
14
+
15
+ const unsupportedImportError = ({ moduleName, originModulePath }) => {
16
+ const origin = originModulePath
17
+ ? path.relative(process.cwd(), originModulePath)
18
+ : "<unknown file>";
19
+
20
+ return new Error(
21
+ [
22
+ `[heimdall] Unsupported import of the Heimdall SDK in a build that excludes it.`,
23
+ ``,
24
+ ` File: ${origin}`,
25
+ ` Import: "${moduleName}"`,
26
+ ``,
27
+ `withHeimdall(config, { include: false }) in metro.config.js replaces the SDK with no-ops,`,
28
+ `so none of its code, its native modules or its dependencies end up in this bundle.`,
29
+ `Only these imports can be replaced:`,
30
+ ``,
31
+ ` "${PACKAGE}" -> no-op connect / disconnect / prompt`,
32
+ ` "${PACKAGE}/zustand" -> heimdallZustand passes the store creator through`,
33
+ ``,
34
+ `"${moduleName}" is not one of them. Letting it through would put the real SDK into this bundle,`,
35
+ `and if react-native-tcp-socket is unlinked for this build, the app would crash at runtime.`,
36
+ ``,
37
+ `How to fix:`,
38
+ ` - import from "${PACKAGE}" or "${PACKAGE}/zustand" instead;`,
39
+ ` - type-only imports are fine anywhere: use "import type { ... }";`,
40
+ ` - if this build should include Heimdall, pass { include: true } to withHeimdall.`,
41
+ ].join("\n")
42
+ );
43
+ };
44
+
45
+ /**
46
+ * Wraps a Metro config. With `include: false` imports of the SDK resolve to no-op modules,
47
+ * so the SDK is not bundled. With `include: true` the config is returned unchanged.
48
+ *
49
+ * @template T
50
+ * @param {T} config
51
+ * @param {{ include: boolean }} options
52
+ * @returns {T}
53
+ */
54
+ function withHeimdall(config, options) {
55
+ if (typeof options?.include !== "boolean") {
56
+ throw new Error(
57
+ `[heimdall] withHeimdall(config, { include }) needs "include" set to true or false explicitly, ` +
58
+ `e.g. { include: process.env.APP_ENV !== "production" }.`
59
+ );
60
+ }
61
+
62
+ if (options.include) return config;
63
+
64
+ const resolver = config.resolver ?? {};
65
+ const resolveNext = resolver.resolveRequest;
66
+
67
+ return {
68
+ ...config,
69
+ resolver: {
70
+ ...resolver,
71
+ resolveRequest: (context, moduleName, platform) => {
72
+ if (isSdkImport(moduleName) && !NOOP_ENTRIES.has(moduleName)) {
73
+ const filePath = NOOP_FILES[moduleName];
74
+ if (!filePath) {
75
+ throw unsupportedImportError({
76
+ moduleName,
77
+ originModulePath: context.originModulePath,
78
+ });
79
+ }
80
+ return { type: "sourceFile", filePath };
81
+ }
82
+
83
+ return resolveNext
84
+ ? resolveNext(context, moduleName, platform)
85
+ : context.resolveRequest(context, moduleName, platform);
86
+ },
87
+ },
88
+ };
89
+ }
90
+
91
+ module.exports = { withHeimdall };
@@ -0,0 +1 @@
1
+ export * from "../dist/noop";
package/noop/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "../dist/noop/index.js";
@@ -0,0 +1 @@
1
+ export * from "../dist/noop/zustand";
@@ -0,0 +1 @@
1
+ export * from "../dist/noop/zustand.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rnzeus/heimdall-sdk",
3
- "version": "0.2.4",
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",
@@ -29,7 +29,9 @@
29
29
  "sideEffects": false,
30
30
  "files": [
31
31
  "dist",
32
- "zustand"
32
+ "zustand",
33
+ "noop",
34
+ "metro"
33
35
  ],
34
36
  "main": "dist/index.js",
35
37
  "types": "dist/index.d.ts",
@@ -48,15 +50,34 @@
48
50
  "import": "./zustand/index.js",
49
51
  "require": "./zustand/index.js",
50
52
  "default": "./zustand/index.js"
53
+ },
54
+ "./noop": {
55
+ "types": "./noop/index.d.ts",
56
+ "react-native": "./noop/index.js",
57
+ "import": "./noop/index.js",
58
+ "require": "./noop/index.js",
59
+ "default": "./noop/index.js"
60
+ },
61
+ "./noop/zustand": {
62
+ "types": "./noop/zustand.d.ts",
63
+ "react-native": "./noop/zustand.js",
64
+ "import": "./noop/zustand.js",
65
+ "require": "./noop/zustand.js",
66
+ "default": "./noop/zustand.js"
67
+ },
68
+ "./metro": {
69
+ "require": "./metro/index.cjs",
70
+ "default": "./metro/index.cjs"
51
71
  }
52
72
  },
53
73
  "scripts": {
54
74
  "clean": "rimraf dist",
55
- "build": "node scripts/write-version.mjs && yarn clean && tsc -p tsconfig.build.json && node scripts/fix-esm-extensions.mjs dist",
75
+ "build": "node scripts/write-version.mjs && yarn clean && tsc -p tsconfig.build.json && node scripts/fix-esm-extensions.mjs dist && node scripts/check-noop.mjs",
56
76
  "dev": "tsc -p tsconfig.build.json -w",
57
77
  "typecheck": "node scripts/write-version.mjs && tsc -p tsconfig.json --noEmit",
58
78
  "knip": "knip",
59
- "dupes": "jscpd"
79
+ "dupes": "jscpd",
80
+ "test": "vitest run"
60
81
  },
61
82
  "peerDependencies": {
62
83
  "react": ">=18.0.0",
@@ -71,7 +92,7 @@
71
92
  }
72
93
  },
73
94
  "dependencies": {
74
- "@rnzeus/heimdall-protocol": "^0.2.0"
95
+ "@rnzeus/heimdall-protocol": "^0.3.0"
75
96
  },
76
97
  "devDependencies": {
77
98
  "@types/node": "^25.0.3",
@@ -84,6 +105,8 @@
84
105
  "react-native-tcp-socket": "^6.3.0",
85
106
  "rimraf": "^6.0.0",
86
107
  "typescript": "^5.7.2",
108
+ "vite": "7.3.7",
109
+ "vitest": "^5.0.3",
87
110
  "zustand": "^4.0.0"
88
111
  },
89
112
  "packageManager": "yarn@4.6.0",