Skip to content

Send files directly between devices over the internet - no cloud storage, no size limits.

Fix mobile worklet missing native crypto addons and protomux race (#3)

Denis Lupookov31628ff9a948
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 3629a2e..e9d6232 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -16,8 +16,8 @@
"android": "expo run:android",
"preios": "npm run bundle:ios",
"ios": "expo run:ios",
- "bundle:android": "bare-pack --host android --linked --out bundles/app-android.bundle.js ../../packages/core/dist/worklet/index.js",
- "bundle:ios": "bare-pack --host ios --linked --out bundles/app-ios.bundle.js ../../packages/core/dist/worklet/index.js",
+ "bundle:android": "bare-pack --host android-arm64 --host android-arm --host android-ia32 --host android-x64 --linked --out bundles/app-android.bundle.js ../../packages/core/dist/worklet/index.js",
+ "bundle:ios": "bare-pack --host ios-arm64 --host ios-arm64-simulator --host ios-x64-simulator --linked --out bundles/app-ios.bundle.js ../../packages/core/dist/worklet/index.js",
"bundle-bare": "npm run bundle:android && npm run bundle:ios",
"typecheck": "tsc --noEmit",
"build:apk": "eas build --platform android --profile preview",
diff --git a/package-lock.json b/package-lock.json
index d4a97cf..57110ae 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -7,6 +7,7 @@
"": {
"name": "altersend",
"version": "1.0.0",
+ "license": "Apache-2.0",
"workspaces": [
"packages/*",
"apps/*"
@@ -102,6 +103,7 @@
},
"apps/mobile": {
"name": "@altersend/mobile",
+ "version": "1.0.0",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
@@ -11326,9 +11328,7 @@
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/bare-buffer/-/bare-buffer-3.6.0.tgz",
"integrity": "sha512-/maRWEQ2eBkVNMbNFVsq1pHXJYVj4Y3AixwruB24eKZDs5Gtu0fixzvjYmBIuTsBMtVH5Yb27pQO9BhFa+IlIQ==",
- "devOptional": true,
"license": "Apache-2.0",
- "peer": true,
"engines": {
"bare": ">=1.20.0"
}
@@ -11365,6 +11365,33 @@
"bare-bundle": "*"
}
},
+ "node_modules/bare-crypto": {
+ "version": "1.14.0",
+ "resolved": "https://registry.npmjs.org/bare-crypto/-/bare-crypto-1.14.0.tgz",
+ "integrity": "sha512-k9QAFx67b0IVM0sII8SUbFvjC7oXQhEwkfVC3CcU6C7eaikkJUh2a3PbvQNc4zBx5QvE/zKw7WK2Jlkc7znVRQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-assert": "^1.2.0",
+ "bare-stream": "^2.6.3"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-dns": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/bare-dns/-/bare-dns-2.1.4.tgz",
+ "integrity": "sha512-abwjHmpWqSRNB7V5615QxPH92L71AVzFm/kKTs8VYiNTAi2xVdonpv0BjJ0hwXLwomoW+xsSOPjW6PZPO14asg==",
+ "license": "Apache-2.0",
+ "engines": {
+ "bare": ">=1.7.0"
+ }
+ },
"node_modules/bare-env": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bare-env/-/bare-env-3.0.0.tgz",
@@ -11460,30 +11487,6 @@
"bare-link": "bin.js"
}
},
- "node_modules/bare-link/node_modules/bare-subprocess": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/bare-subprocess/-/bare-subprocess-6.0.0.tgz",
- "integrity": "sha512-0uIOyxnhX14liHAM54tajLedN5eUsXSmxZOzDkODmuxeU8s/6/jVx5UFHOeAeDSiHHXMFf0BcaszEVsURkWJeg==",
- "license": "Apache-2.0",
- "dependencies": {
- "bare-env": "^3.0.0",
- "bare-events": "^2.5.4",
- "bare-os": "^3.0.1",
- "bare-pipe": "^4.0.0",
- "bare-url": "^2.2.2"
- },
- "engines": {
- "bare": ">=1.7.0"
- },
- "peerDependencies": {
- "bare-buffer": "*"
- },
- "peerDependenciesMeta": {
- "bare-buffer": {
- "optional": true
- }
- }
- },
"node_modules/bare-module": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/bare-module/-/bare-module-6.2.0.tgz",
@@ -11566,6 +11569,18 @@
}
}
},
+ "node_modules/bare-net": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/bare-net/-/bare-net-2.3.1.tgz",
+ "integrity": "sha512-MypSqDKpDU2Xt7FIfazn5yGvRnV09gFcIPHGWstW0gxuzA4tucTcwJSZeos97C4F89vtU5oGwXDN/HrGN6Y4Jw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.2.2",
+ "bare-pipe": "^4.0.0",
+ "bare-stream": "^2.0.0",
+ "bare-tcp": "^2.0.0"
+ }
+ },
"node_modules/bare-os": {
"version": "3.9.1",
"resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.9.1.tgz",
@@ -11696,30 +11711,6 @@
"require-asset": "^1.1.0"
}
},
- "node_modules/bare-sidecar/node_modules/bare-subprocess": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/bare-subprocess/-/bare-subprocess-6.0.0.tgz",
- "integrity": "sha512-0uIOyxnhX14liHAM54tajLedN5eUsXSmxZOzDkODmuxeU8s/6/jVx5UFHOeAeDSiHHXMFf0BcaszEVsURkWJeg==",
- "license": "Apache-2.0",
- "dependencies": {
- "bare-env": "^3.0.0",
- "bare-events": "^2.5.4",
- "bare-os": "^3.0.1",
- "bare-pipe": "^4.0.0",
- "bare-url": "^2.2.2"
- },
- "engines": {
- "bare": ">=1.7.0"
- },
- "peerDependencies": {
- "bare-buffer": "*"
- },
- "peerDependenciesMeta": {
- "bare-buffer": {
- "optional": true
- }
- }
- },
"node_modules/bare-signals": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/bare-signals/-/bare-signals-4.2.0.tgz",
@@ -11770,6 +11761,57 @@
}
}
},
+ "node_modules/bare-subprocess": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/bare-subprocess/-/bare-subprocess-6.0.0.tgz",
+ "integrity": "sha512-0uIOyxnhX14liHAM54tajLedN5eUsXSmxZOzDkODmuxeU8s/6/jVx5UFHOeAeDSiHHXMFf0BcaszEVsURkWJeg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-env": "^3.0.0",
+ "bare-events": "^2.5.4",
+ "bare-os": "^3.0.1",
+ "bare-pipe": "^4.0.0",
+ "bare-url": "^2.2.2"
+ },
+ "engines": {
+ "bare": ">=1.7.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-tcp": {
+ "version": "2.2.13",
+ "resolved": "https://registry.npmjs.org/bare-tcp/-/bare-tcp-2.2.13.tgz",
+ "integrity": "sha512-4KQPgqYugvK6QxcSnVGbl87XslBebxmXlv7Glf4M9iwwoSCDKtYmC1t6zsMctTNhzKXbWCId7mB4R9qLWj3JMw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-dns": "^2.0.4",
+ "bare-events": "^2.5.4",
+ "bare-stream": "^2.6.4"
+ },
+ "engines": {
+ "bare": ">=1.16.0"
+ }
+ },
+ "node_modules/bare-tls": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/bare-tls/-/bare-tls-3.1.5.tgz",
+ "integrity": "sha512-yoOtW3MyJF1mMwavLeuqOE7+qTKZ9cl1GRPxCUOXMUvYCfGltvXyRH48R4EKrRIfgUG6vil6n4Ea1i81fwmgZA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-net": "^2.0.1",
+ "bare-stream": "^2.6.4"
+ },
+ "engines": {
+ "bare": ">=1.7.0"
+ }
+ },
"node_modules/bare-tty": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/bare-tty/-/bare-tty-5.1.0.tgz",
@@ -11802,6 +11844,15 @@
"bare-path": "^3.0.0"
}
},
+ "node_modules/bare-zlib": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/bare-zlib/-/bare-zlib-1.3.4.tgz",
+ "integrity": "sha512-Ahr9pfa32rrrrs1ez5mioHS9u+DJUqp98MO88yEJlI9X5SxIuVOli8tbffG8FXwxJbD7imxfDRvwMLsnEteEUA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-stream": "^2.0.0"
+ }
+ },
"node_modules/base32-encode": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/base32-encode/-/base32-encode-1.2.0.tgz",
@@ -27315,9 +27366,15 @@
"license": "Apache-2.0",
"dependencies": {
"b4a": "^1.8.0",
+ "bare-buffer": "^3.6.0",
+ "bare-crypto": "^1.14.0",
+ "bare-dns": "^2.1.4",
"bare-fs": "^4.7.0",
"bare-process": "^4.4.1",
"bare-rpc": "^1.2.0",
+ "bare-tcp": "^2.2.13",
+ "bare-tls": "^3.1.5",
+ "bare-zlib": "^1.3.4",
"compact-encoding": "^2.19.0",
"corestore": "^7.9.1",
"hypercore-crypto": "^3.6.1",
diff --git a/packages/core/package.json b/packages/core/package.json
index cbae9ce..2429417 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -30,9 +30,15 @@
},
"dependencies": {
"b4a": "^1.8.0",
+ "bare-buffer": "^3.6.0",
+ "bare-crypto": "^1.14.0",
+ "bare-dns": "^2.1.4",
"bare-fs": "^4.7.0",
"bare-process": "^4.4.1",
"bare-rpc": "^1.2.0",
+ "bare-tcp": "^2.2.13",
+ "bare-tls": "^3.1.5",
+ "bare-zlib": "^1.3.4",
"compact-encoding": "^2.19.0",
"corestore": "^7.9.1",
"hypercore-crypto": "^3.6.1",
diff --git a/packages/core/src/types.d.ts b/packages/core/src/types.d.ts
index 7f120ba..e38a131 100644
--- a/packages/core/src/types.d.ts
+++ b/packages/core/src/types.d.ts
@@ -107,6 +107,7 @@ declare module 'hyperswarm' {
leave(discoveryKey: Uint8Array): unknown
destroy(): Promise<void>
on(event: 'connection', cb: (socket: PeerSocket, info: PeerInfo) => void): this
+ on(event: 'update', cb: () => void): this
}
}
@@ -123,7 +124,11 @@ declare module 'protomux' {
}
export default class Protomux {
static from(socket: unknown): Protomux
- createChannel(opts: { protocol: string }): ProtomuxChannel | null
+ createChannel(opts: {
+ protocol: string
+ onopen?: () => void
+ onclose?: () => void
+ }): ProtomuxChannel | null
}
}
diff --git a/packages/core/src/worklet/index.ts b/packages/core/src/worklet/index.ts
index 29d37ab..217706f 100644
--- a/packages/core/src/worklet/index.ts
+++ b/packages/core/src/worklet/index.ts
@@ -1,4 +1,11 @@
import './abort-polyfill'
+import './process-handlers'
+import 'bare-buffer'
+import 'bare-crypto'
+import 'bare-dns'
+import 'bare-tcp'
+import 'bare-tls'
+import 'bare-zlib'
import bareProcess from 'bare-process'
import fs from 'bare-fs'
import { TransferOrchestrator } from './transfer/orchestrator'
diff --git a/packages/core/src/worklet/process-handlers.ts b/packages/core/src/worklet/process-handlers.ts
new file mode 100644
index 0000000..66a4fee
--- /dev/null
+++ b/packages/core/src/worklet/process-handlers.ts
@@ -0,0 +1,26 @@
+interface BareGlobal {
+ on: (event: string, listener: (...args: unknown[]) => void) => unknown
+}
+
+function isBareGlobal(value: unknown): value is BareGlobal {
+ return (
+ typeof value === 'object' && value !== null && typeof Reflect.get(value, 'on') === 'function'
+ )
+}
+
+function formatReason(reason: unknown): string {
+ if (reason instanceof Error) {
+ return `${reason.message}${reason.stack ? `\n${reason.stack}` : ''}`
+ }
+ return String(reason)
+}
+
+const bare = Reflect.get(globalThis, 'Bare')
+if (isBareGlobal(bare)) {
+ bare.on('unhandledRejection', (reason: unknown) => {
+ console.error('Worklet unhandledRejection:', formatReason(reason))
+ })
+ bare.on('uncaughtException', (error: unknown) => {
+ console.error('Worklet uncaughtException:', formatReason(error))
+ })
+}
diff --git a/packages/core/src/worklet/transfer/control-channel.ts b/packages/core/src/worklet/transfer/control-channel.ts
index c4a3639..996e540 100644
--- a/packages/core/src/worklet/transfer/control-channel.ts
+++ b/packages/core/src/worklet/transfer/control-channel.ts
@@ -74,6 +74,8 @@ type PeerControlHandler = (message: PeerControlMessage) => void
export class PeerControlChannel {
private readonly message: ProtomuxMessage
+ private opened = false
+ private readonly pending: PeerControlMessage[] = []
constructor(message: ProtomuxMessage) {
this.message = message
@@ -81,8 +83,12 @@ export class PeerControlChannel {
static create(socket: PeerSocket, onmessage: PeerControlHandler): PeerControlChannel | null {
const mux = Protomux.from(socket)
+ let instance: PeerControlChannel | null = null
const channel = mux.createChannel({
- protocol: 'altersend/control'
+ protocol: 'altersend/control',
+ onopen: () => {
+ if (instance) instance.flush()
+ }
})
if (!channel) return null
@@ -106,10 +112,23 @@ export class PeerControlChannel {
})
channel.open()
- return new PeerControlChannel(message)
+ instance = new PeerControlChannel(message)
+ return instance
}
send(message: PeerControlMessage): void {
+ if (!this.opened) {
+ this.pending.push(message)
+ return
+ }
this.message.send({ ...message, protocolVersion: PROTOCOL_VERSION })
}
+
+ private flush(): void {
+ this.opened = true
+ const queue = this.pending.splice(0)
+ for (const msg of queue) {
+ this.message.send({ ...msg, protocolVersion: PROTOCOL_VERSION })
+ }
+ }
}
diff --git a/packages/core/src/worklet/transfer/orchestrator.ts b/packages/core/src/worklet/transfer/orchestrator.ts
index 0699a1b..deacb2d 100644
--- a/packages/core/src/worklet/transfer/orchestrator.ts
+++ b/packages/core/src/worklet/transfer/orchestrator.ts
@@ -256,7 +256,7 @@ export class TransferOrchestrator implements TransferRPC {
async host(): Promise<HostReply> {
await this.readyPromise
- const topic = await this.swarm.generateKey()
+ const topic = this.swarm.generateKey()
this.currentTopic = topic
return { topic }
}
diff --git a/packages/core/src/worklet/transfer/swarm.ts b/packages/core/src/worklet/transfer/swarm.ts
index f0d7164..06b5e70 100644
--- a/packages/core/src/worklet/transfer/swarm.ts
+++ b/packages/core/src/worklet/transfer/swarm.ts
@@ -34,27 +34,31 @@ export interface TransferSwarmOptions {
*
*/
export class TransferSwarm {
- private swarm: Hyperswarm
+ private swarm: Hyperswarm | null
private readonly peerSessions: Map<PeerSocket, PeerSession>
private readonly callbacks: TransferSwarmCallbacks
private readonly identityStore: PeerIdentityStore | null
- private readonly joinedDiscoveries: Set<string>
- private readonly pendingPeerKeys: Set<string>
private hostedTopicHex: string | null
+ private joinedAny: boolean
constructor(callbacks: TransferSwarmCallbacks, options: TransferSwarmOptions = {}) {
this.identityStore = options.identityStore ?? null
- this.swarm = this.createSwarm()
- this.peerSessions = new Map()
this.callbacks = callbacks
- this.joinedDiscoveries = new Set()
- this.pendingPeerKeys = new Set()
+ this.peerSessions = new Map()
this.hostedTopicHex = null
+ this.joinedAny = false
+ this.swarm = null
+ }
+
+ private ensureSwarm(): Hyperswarm {
+ if (!this.swarm) {
+ this.swarm = this.createSwarm()
+ }
+ return this.swarm
}
private createSwarm(keyPair?: NoiseKeyPair): Hyperswarm {
- const opts = { firewall: () => false }
- const swarm = keyPair ? new Hyperswarm({ ...opts, keyPair }) : new Hyperswarm(opts)
+ const swarm = keyPair ? new Hyperswarm({ keyPair }) : new Hyperswarm()
swarm.on('connection', (socket, info) => {
void this.handleConnection(socket, info).catch((err) => {
console.error(
@@ -66,62 +70,35 @@ export class TransferSwarm {
} catch {}
})
})
+ swarm.on('update', () => {})
return swarm
}
private async handleConnection(socket: PeerSocket, info: PeerInfo): Promise<void> {
- if (this.joinedDiscoveries.size === 0) {
- try {
- socket.destroy()
- } catch {}
- return
- }
-
const peerKey = b4a.toString(info.publicKey, 'hex')
- const isDuplicate =
- this.pendingPeerKeys.has(peerKey) ||
- Array.from(this.peerSessions.values()).some((s) => s.peerKey === peerKey)
- if (isDuplicate) {
+
+ await this.callbacks.onReady()
+
+ this.callbacks.onReplicate(socket)
+
+ let session: PeerSession | null = null
+ const controlChannel = PeerControlChannel.create(socket, (message) => {
+ if (!session) return
+ this.callbacks.onControlMessage(message, session)
+ })
+ if (!controlChannel) {
try {
socket.destroy()
} catch {}
return
}
- this.pendingPeerKeys.add(peerKey)
- try {
- await this.callbacks.onReady()
-
- if (this.joinedDiscoveries.size === 0) {
- try {
- socket.destroy()
- } catch {}
- return
- }
+ session = { socket, peerKey, controlChannel }
+ this.peerSessions.set(socket, session)
+ this.callbacks.onPeerConnected(session)
- this.callbacks.onReplicate(socket)
-
- let session: PeerSession | null = null
- const controlChannel = PeerControlChannel.create(socket, (message) => {
- if (!session) return
- this.callbacks.onControlMessage(message, session)
- })
- if (!controlChannel) {
- try {
- socket.destroy()
- } catch {}
- return
- }
-
- session = { socket, peerKey, controlChannel }
- this.peerSessions.set(socket, session)
- this.callbacks.onPeerConnected(session)
-
- socket.on('close', () => this.cleanupPeer(socket))
- socket.on('error', () => this.cleanupPeer(socket))
- } finally {
- this.pendingPeerKeys.delete(peerKey)
- }
+ socket.on('close', () => this.cleanupPeer(socket))
+ socket.on('error', () => this.cleanupPeer(socket))
}
private cleanupPeer(socket: PeerSocket): void {
@@ -131,62 +108,62 @@ export class TransferSwarm {
this.callbacks.onPeerDisconnected(session.peerKey, this.peerSessions.size)
}
- private async joinTopic(topic: Uint8Array): Promise<void> {
+ private joinTopic(topic: Uint8Array): void {
const discovery = crypto.discoveryKey(topic)
- const discoveryHex = b4a.toString(discovery, 'hex')
- this.joinedDiscoveries.add(discoveryHex)
- const session = this.swarm.join(discovery, { server: true, client: true })
- await session.flushed()
+ this.joinedAny = true
+ this.ensureSwarm().join(discovery, { server: true, client: true })
}
async endSession(): Promise<void> {
- this.joinedDiscoveries.clear()
this.hostedTopicHex = null
- this.pendingPeerKeys.clear()
+ this.joinedAny = false
- const sessionsToClose = Array.from(this.peerSessions.values())
- this.peerSessions.clear()
- for (const session of sessionsToClose) {
+ for (const conn of this.peerSessions.keys()) {
try {
- session.socket.destroy()
+ conn.destroy()
} catch {}
}
+ this.peerSessions.clear()
const oldSwarm = this.swarm
- this.swarm = this.createSwarm()
+ this.swarm = null
- try {
- await oldSwarm.destroy()
- } catch (err) {
- console.warn('TransferSwarm: old swarm destroy failed', err)
+ if (oldSwarm) {
+ try {
+ await oldSwarm.destroy()
+ } catch (err) {
+ console.warn('TransferSwarm: old swarm destroy failed', err)
+ }
}
}
async join(topicHex: string): Promise<void> {
- if (this.identityStore && this.joinedDiscoveries.size === 0) {
+ if (this.identityStore && !this.joinedAny) {
await this.swapKeyPair(await this.identityStore.getOrCreate(topicHex))
}
const topic = b4a.from(topicHex, 'hex')
- await this.joinTopic(topic)
+ this.joinTopic(topic)
}
private async swapKeyPair(keyPair: NoiseKeyPair): Promise<void> {
const oldSwarm = this.swarm
this.swarm = this.createSwarm(keyPair)
- try {
- await oldSwarm.destroy()
- } catch (err) {
- console.warn('TransferSwarm: keypair swap — old swarm destroy failed', err)
+ if (oldSwarm) {
+ try {
+ await oldSwarm.destroy()
+ } catch (err) {
+ console.warn('TransferSwarm: keypair swap — old swarm destroy failed', err)
+ }
}
}
- async generateKey(): Promise<string> {
+ generateKey(): string {
if (this.hostedTopicHex) {
return this.hostedTopicHex
}
const topic = crypto.randomBytes(32)
const topicHex = b4a.toString(topic, 'hex')
- await this.joinTopic(topic)
+ this.joinTopic(topic)
this.hostedTopicHex = topicHex
return topicHex
}
@@ -206,6 +183,13 @@ export class TransferSwarm {
}
async destroy(): Promise<void> {
- await this.swarm.destroy()
+ for (const conn of this.peerSessions.keys()) {
+ try {
+ conn.destroy()
+ } catch {}
+ }
+ if (this.swarm) {
+ await this.swarm.destroy()
+ }
}
}