nova-personal-agent-server 0.4.0 → 1.0.2
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/LICENSE +674 -201
- package/README.md +12 -2
- package/bin/nova-space-host.mjs +4 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
- package/node_modules/@nova-personal-agent/relay/package.json +1 -0
- package/package.json +13 -6
- package/runtime/dist/src/cascaded-text-provider.js +8 -3
- package/runtime/dist/src/composition/assembly.js +133 -35
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
- package/runtime/dist/src/composition/production-composition.js +57 -21
- package/runtime/dist/src/composition/realtime-assembly.js +160 -52
- package/runtime/dist/src/composition/soul-context.js +22 -0
- package/runtime/dist/src/config/capability-registry.js +48 -3
- package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
- package/runtime/dist/src/config/config.js +541 -128
- package/runtime/dist/src/config/credential-rotation.js +26 -0
- package/runtime/dist/src/config/data-root.js +764 -0
- package/runtime/dist/src/config/diagnostics.js +3 -1
- package/runtime/dist/src/config/environment-contract.js +190 -188
- package/runtime/dist/src/config/model-routes.js +140 -0
- package/runtime/dist/src/config/voice-credentials.js +55 -0
- package/runtime/dist/src/connectors/composio/index.js +9 -0
- package/runtime/dist/src/connectors/feishu/index.js +258 -44
- package/runtime/dist/src/connectors/macos/mail.js +7 -3
- package/runtime/dist/src/connectors/macos/reader.js +3 -1
- package/runtime/dist/src/conversation-voice-provider.js +5 -2
- package/runtime/dist/src/core/causal-runtime.js +38 -3
- package/runtime/dist/src/core/context-view.js +7 -0
- package/runtime/dist/src/core/guards.js +32 -0
- package/runtime/dist/src/core/runtime.js +3 -0
- package/runtime/dist/src/core/schedule-tools.js +2 -2
- package/runtime/dist/src/core/source-processing-instructions.js +2 -2
- package/runtime/dist/src/core/source-processing-tools.js +3 -1
- package/runtime/dist/src/core/tool-schema.js +42 -7
- package/runtime/dist/src/desktop/desktop-camera.js +3 -5
- package/runtime/dist/src/desktop/desktop-control.js +41 -8
- package/runtime/dist/src/desktop/desktop-session.js +90 -19
- package/runtime/dist/src/desktop/desktop-wire.js +5 -7
- package/runtime/dist/src/desktop/startup-error.js +18 -16
- package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
- package/runtime/dist/src/desktop-entry.js +6 -2
- package/runtime/dist/src/desktop.js +5 -1
- package/runtime/dist/src/device/attempt.js +65 -0
- package/runtime/dist/src/device/authority.js +159 -0
- package/runtime/dist/src/device/gateway.js +87 -0
- package/runtime/dist/src/device/ledger.js +91 -0
- package/runtime/dist/src/device/ownership.js +92 -0
- package/runtime/dist/src/device/port.js +2 -0
- package/runtime/dist/src/device/schedule-ownership.js +103 -0
- package/runtime/dist/src/executors/acp/transport.js +2 -0
- package/runtime/dist/src/executors/browser.js +4 -3
- package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
- package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
- package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
- package/runtime/dist/src/executors/codex/common.js +1 -1
- package/runtime/dist/src/executors/codex/contract.js +12 -16
- package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
- package/runtime/dist/src/executors/codex/factory.js +54 -32
- package/runtime/dist/src/executors/codex/host-config.js +69 -20
- package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
- package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
- package/runtime/dist/src/executors/codex/process-owner.js +4 -6
- package/runtime/dist/src/executors/codex/production-host.js +33 -34
- package/runtime/dist/src/executors/codex/protocol.js +9 -14
- package/runtime/dist/src/executors/codex/session-title.js +6 -8
- package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
- package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
- package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
- package/runtime/dist/src/executors/coding/intake.js +12 -7
- package/runtime/dist/src/executors/computer-backend.js +18 -10
- package/runtime/dist/src/executors/computer-config.js +32 -0
- package/runtime/dist/src/executors/computer-device.js +68 -16
- package/runtime/dist/src/executors/computer-worker.js +18 -6
- package/runtime/dist/src/executors/computer.js +29 -56
- package/runtime/dist/src/executors/device-lock.js +14 -5
- package/runtime/dist/src/executors/gui-execution.js +2 -0
- package/runtime/dist/src/executors/index.js +0 -1
- package/runtime/dist/src/executors/mobile.js +9 -8
- package/runtime/dist/src/executors/native-process.js +4 -0
- package/runtime/dist/src/executors/search.js +3 -5
- package/runtime/dist/src/executors/task-resources.js +21 -0
- package/runtime/dist/src/executors/watcher.js +2 -4
- package/runtime/dist/src/experience/host.js +179 -0
- package/runtime/dist/src/index.js +2 -0
- package/runtime/dist/src/knowledge/assembly.js +3 -4
- package/runtime/dist/src/knowledge/embeddings.js +50 -34
- package/runtime/dist/src/knowledge/service.js +1 -0
- package/runtime/dist/src/knowledge/store-client.js +1 -6
- package/runtime/dist/src/knowledge/store-worker.js +1 -3
- package/runtime/dist/src/mem0/resource.js +25 -0
- package/runtime/dist/src/mem0/store-worker.js +234 -21
- package/runtime/dist/src/memory/consumer.js +31 -0
- package/runtime/dist/src/memory/engine-worker.js +210 -0
- package/runtime/dist/src/memory/entry.js +8 -1
- package/runtime/dist/src/memory/explicit-memory.js +20 -0
- package/runtime/dist/src/memory/factory.js +30 -15
- package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
- package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
- package/runtime/dist/src/memory/prerecall-port.js +27 -0
- package/runtime/dist/src/memory/prerecall.js +1 -1
- package/runtime/dist/src/memory/production-engine.js +151 -0
- package/runtime/dist/src/memory/provenance.js +1 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
- package/runtime/dist/src/memory/retrieval.js +107 -22
- package/runtime/dist/src/memory/sensitivity.js +6 -2
- package/runtime/dist/src/memory/source-retrieval.js +11 -0
- package/runtime/dist/src/memory/tool-capabilities.js +46 -0
- package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
- package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
- package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
- package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
- package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
- package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
- package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
- package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
- package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
- package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
- package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
- package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
- package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
- package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
- package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
- package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
- package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
- package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
- package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
- package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
- package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
- package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
- package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
- package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
- package/runtime/dist/src/memory-ledger/store-client.js +235 -37
- package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
- package/runtime/dist/src/memory-ledger/store.js +91 -1
- package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
- package/runtime/dist/src/memory-substrate/diary.js +27 -0
- package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
- package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
- package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
- package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
- package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
- package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
- package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
- package/runtime/dist/src/memory-substrate/migration.js +2 -0
- package/runtime/dist/src/memory-substrate/purge.js +12 -2
- package/runtime/dist/src/memory-substrate/resource.js +514 -129
- package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
- package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
- package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
- package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
- package/runtime/dist/src/memory-substrate/source-state.js +8 -0
- package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
- package/runtime/dist/src/memory-substrate/store.js +125 -23
- package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
- package/runtime/dist/src/model/goal-writer.js +80 -0
- package/runtime/dist/src/model/jev-client.js +24 -13
- package/runtime/dist/src/model/model-adapters.js +2 -3
- package/runtime/dist/src/model/model-catalog.js +80 -0
- package/runtime/dist/src/model/model-gateway.js +47 -18
- package/runtime/dist/src/model/model-purpose.js +3 -4
- package/runtime/dist/src/model/personal-writer.js +536 -44
- package/runtime/dist/src/model/proactivity.js +50 -6
- package/runtime/dist/src/model/responses-model-gateway.js +59 -0
- package/runtime/dist/src/model/task-verifier.js +3 -3
- package/runtime/dist/src/model/timeline-anchors.js +77 -0
- package/runtime/dist/src/model/timeline-perspective.js +13 -0
- package/runtime/dist/src/model/timeline-selection.js +182 -0
- package/runtime/dist/src/model/understanding-writer.js +27 -0
- package/runtime/dist/src/model/vision-capability.js +3 -1
- package/runtime/dist/src/model/workbench-writer.js +96 -0
- package/runtime/dist/src/news/feeds.js +6 -10
- package/runtime/dist/src/news/interests.js +23 -0
- package/runtime/dist/src/news/service.js +87 -31
- package/runtime/dist/src/news/sources.json +116 -0
- package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
- package/runtime/dist/src/notifications/content.js +41 -0
- package/runtime/dist/src/notifications/contracts.js +4 -2
- package/runtime/dist/src/notifications/feed.js +6 -2
- package/runtime/dist/src/notifications/service.js +27 -14
- package/runtime/dist/src/notifications/store.js +3 -1
- package/runtime/dist/src/personal-agent/app-context.js +39 -4
- package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
- package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
- package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
- package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
- package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
- package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
- package/runtime/dist/src/personal-agent/contracts.js +24 -4
- package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
- package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
- package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
- package/runtime/dist/src/personal-agent/conversations.js +71 -15
- package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
- package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
- package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
- package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2379 -223
- package/runtime/dist/src/personal-agent/identity-context.js +33 -0
- package/runtime/dist/src/personal-agent/life.js +129 -11
- package/runtime/dist/src/personal-agent/local-shell.js +181 -0
- package/runtime/dist/src/personal-agent/local-tools.js +234 -0
- package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
- package/runtime/dist/src/personal-agent/project-digests.js +7 -3
- package/runtime/dist/src/personal-agent/project-history.js +36 -0
- package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
- package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
- package/runtime/dist/src/personal-agent/sources.js +9 -1
- package/runtime/dist/src/personal-agent/store.js +124 -14
- package/runtime/dist/src/personal-agent/task-loop.js +3 -0
- package/runtime/dist/src/personal-agent/tasks.js +16 -4
- package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
- package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
- package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
- package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
- package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
- package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
- package/runtime/dist/src/personal-agent/understanding.js +7 -22
- package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
- package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
- package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
- package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
- package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
- package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
- package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
- package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
- package/runtime/dist/src/projects/project-native-resource.js +10 -8
- package/runtime/dist/src/projects/project-store.js +36 -4
- package/runtime/dist/src/realtime/bridge.js +77 -8
- package/runtime/dist/src/realtime/capabilities.js +19 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
- package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
- package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
- package/runtime/dist/src/realtime/evidence.js +1 -1
- package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
- package/runtime/dist/src/realtime/gemini.js +14 -3
- package/runtime/dist/src/realtime/host-delivery.js +37 -4
- package/runtime/dist/src/realtime/protocol.js +18 -3
- package/runtime/dist/src/realtime/provider-projection.js +4 -1
- package/runtime/dist/src/realtime/provider-session.js +73 -16
- package/runtime/dist/src/realtime/qwen-transport.js +35 -4
- package/runtime/dist/src/realtime/qwen.js +144 -9
- package/runtime/dist/src/realtime/service-state.js +0 -1
- package/runtime/dist/src/realtime/service.js +93 -7
- package/runtime/dist/src/realtime/session.js +39 -32
- package/runtime/dist/src/realtime/sglang-native.js +214 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
- package/runtime/dist/src/realtime/telemetry.js +6 -3
- package/runtime/dist/src/realtime/tool-continuations.js +84 -7
- package/runtime/dist/src/realtime/transport.js +17 -0
- package/runtime/dist/src/realtime/usage.js +33 -17
- package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
- package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
- package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
- package/runtime/dist/src/server/aoq-chat-server.js +1 -1
- package/runtime/dist/src/server/client-server.js +21 -0
- package/runtime/dist/src/server-entry.js +3 -0
- package/runtime/dist/src/space-host/admin-socket.js +115 -0
- package/runtime/dist/src/space-host/audio-owner.js +44 -0
- package/runtime/dist/src/space-host/cli.js +195 -0
- package/runtime/dist/src/space-host/config.js +247 -0
- package/runtime/dist/src/space-host/context-input.js +12 -0
- package/runtime/dist/src/space-host/contracts.js +10 -0
- package/runtime/dist/src/space-host/host-admin.js +114 -0
- package/runtime/dist/src/space-host/key-delivery.js +28 -0
- package/runtime/dist/src/space-host/mobile-tools.js +9 -0
- package/runtime/dist/src/space-host/model-settings.js +213 -0
- package/runtime/dist/src/space-host/projection.js +37 -0
- package/runtime/dist/src/space-host/push.js +137 -0
- package/runtime/dist/src/space-host/relay-transport.js +55 -0
- package/runtime/dist/src/space-host/service.js +841 -0
- package/runtime/dist/src/space-host/voice-crypto.js +240 -0
- package/runtime/dist/src/space-host/voice.js +600 -0
- package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
- package/runtime/dist/src/storage/private-database.js +7 -10
- package/runtime/dist/src/text/unicode-normalize.js +5 -1
- package/runtime/dist/src/understanding/candidates.js +8 -10
- package/runtime/dist/src/understanding/fixture.js +1 -1
- package/runtime/dist/src/understanding/pipeline.js +4 -4
- package/runtime/dist/src/usage/context.js +23 -0
- package/runtime/dist/src/usage/index.js +4 -0
- package/runtime/dist/src/usage/ledger-worker.js +90 -0
- package/runtime/dist/src/usage/ledger.js +74 -0
- package/runtime/dist/src/usage/model-call.js +63 -0
- package/runtime/dist/src/usage/pricing.js +68 -0
- package/runtime/dist/src/usage/summary.js +69 -0
- package/runtime/dist/src/voicemem/store-client.js +104 -21
- package/runtime/dist/src/voicemem/store-worker.js +5 -8
- package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
- package/src/command.mjs +8 -1
- package/runtime/dist/src/executors/autoglm.js +0 -376
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { createServer as createSecureServer } from 'node:https';
|
|
3
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
4
|
+
import { MailboxStore } from './mailbox.js';
|
|
5
|
+
import { LiveRelay } from './live.js';
|
|
6
|
+
import { MediaRelay } from './media.js';
|
|
7
|
+
import { RelayError } from './protocol.js';
|
|
8
|
+
import { SecurityStore } from './security.js';
|
|
9
|
+
import { canonicalAddress, sourceAddress, trustedAddresses } from './source-address.js';
|
|
10
|
+
const loopback = (host) => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host);
|
|
11
|
+
/** Inbound infrastructure only: endpoints still initiate all connections. No model or plaintext API. */
|
|
12
|
+
export class RelayServer {
|
|
13
|
+
security;
|
|
14
|
+
mailbox;
|
|
15
|
+
live;
|
|
16
|
+
media;
|
|
17
|
+
http;
|
|
18
|
+
sockets = new WebSocketServer({ noServer: true, maxPayload: 1024, perMessageDeflate: false });
|
|
19
|
+
mediaSockets;
|
|
20
|
+
rates = new Map();
|
|
21
|
+
trustedProxies;
|
|
22
|
+
forwardedConnections = new Map();
|
|
23
|
+
requestSources = new WeakMap();
|
|
24
|
+
ipConnections = new Map();
|
|
25
|
+
options;
|
|
26
|
+
maintenance;
|
|
27
|
+
constructor(options) {
|
|
28
|
+
this.options = { bind: '127.0.0.1', port: 0, maxBodyBytes: 768 * 1024, maxResponseBytes: 1536 * 1024, maxConnections: 1024,
|
|
29
|
+
maxConnectionsPerIp: 32, requestsPerMinute: 600, bootstrapPerMinute: 20, maxRateSources: 10000, globalRequestsPerMinute: 30000, globalBootstrapPerMinute: 200, ...options };
|
|
30
|
+
for (const key of ['maxBodyBytes', 'maxResponseBytes', 'maxConnections', 'maxConnectionsPerIp', 'requestsPerMinute', 'bootstrapPerMinute', 'maxRateSources', 'globalRequestsPerMinute', 'globalBootstrapPerMinute']) {
|
|
31
|
+
if (!Number.isSafeInteger(this.options[key]) || this.options[key] < 1)
|
|
32
|
+
throw new RelayError('invalid_options');
|
|
33
|
+
}
|
|
34
|
+
if (!Number.isSafeInteger(this.options.port) || this.options.port < 0 || this.options.port > 65535)
|
|
35
|
+
throw new RelayError('invalid_port');
|
|
36
|
+
if (!loopback(this.options.bind) && !options.tls &&
|
|
37
|
+
!(options.externalTls && options.publicUrl && new URL(options.publicUrl).protocol === 'https:'))
|
|
38
|
+
throw new RelayError('tls_required');
|
|
39
|
+
if (this.options.maxResponseBytes < (options.mailbox?.maxMessageBytes ?? 512 * 1024) + 256)
|
|
40
|
+
throw new RelayError('invalid_response_budget');
|
|
41
|
+
this.trustedProxies = trustedAddresses(options.trustedProxyAddresses);
|
|
42
|
+
this.security = new SecurityStore(options.securityPath, { bootstrapToken: options.bootstrapToken, ...(options.clock === undefined ? {} : { now: options.clock }), ...(options.maxControlOperationsPerSpace === undefined ? {} : { maxControlOperations: options.maxControlOperationsPerSpace }) });
|
|
43
|
+
this.mailbox = new MailboxStore(options.mailboxPath, this.security, { maxMessageBytes: 512 * 1024, ...options.mailbox });
|
|
44
|
+
this.live = new LiveRelay(this.security, { ...options.live, maxConnections: this.options.maxConnections });
|
|
45
|
+
this.media = new MediaRelay(this.security, { ...options.media, ...(options.clock === undefined ? {} : { clock: options.clock }) });
|
|
46
|
+
// ws enforces maxPayload while assembling a message, before it is buffered whole.
|
|
47
|
+
this.mediaSockets = new WebSocketServer({ noServer: true, maxPayload: this.media.maxFrameBytes, perMessageDeflate: false });
|
|
48
|
+
const listener = (req, res) => { void this.route(req, res); };
|
|
49
|
+
this.http = options.tls ? createSecureServer(options.tls, listener) : createServer(listener);
|
|
50
|
+
this.http.maxConnections = this.options.maxConnections;
|
|
51
|
+
this.http.requestTimeout = 10000;
|
|
52
|
+
this.http.headersTimeout = 10000;
|
|
53
|
+
this.http.keepAliveTimeout = 5000;
|
|
54
|
+
this.http.maxHeadersCount = 32;
|
|
55
|
+
this.http.on('connection', socket => {
|
|
56
|
+
let ip;
|
|
57
|
+
try {
|
|
58
|
+
ip = canonicalAddress(socket.remoteAddress ?? '0.0.0.0');
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
socket.destroy();
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
// Before HTTP headers exist, a trusted proxy is bounded by the global TCP cap.
|
|
65
|
+
// Its clients are counted separately for each HTTP request and WS lifetime below.
|
|
66
|
+
if (this.trustedProxies.has(ip))
|
|
67
|
+
return;
|
|
68
|
+
const count = this.ipConnections.get(ip) ?? 0;
|
|
69
|
+
if (count >= this.options.maxConnectionsPerIp) {
|
|
70
|
+
socket.destroy();
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
this.ipConnections.set(ip, count + 1);
|
|
74
|
+
socket.on('close', () => {
|
|
75
|
+
const left = (this.ipConnections.get(ip) ?? 1) - 1;
|
|
76
|
+
if (left)
|
|
77
|
+
this.ipConnections.set(ip, left);
|
|
78
|
+
else
|
|
79
|
+
this.ipConnections.delete(ip);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
this.http.on('upgrade', (req, socket, head) => {
|
|
83
|
+
let release;
|
|
84
|
+
try {
|
|
85
|
+
release = this.reserveForwardedConnection(req);
|
|
86
|
+
socket.once('close', release);
|
|
87
|
+
this.rate(req, false);
|
|
88
|
+
const url = new URL(req.url ?? '/', 'http://relay.invalid');
|
|
89
|
+
if (url.search || (url.pathname !== '/v1/live' && !(url.pathname === '/v1/media' && this.media.enabled)))
|
|
90
|
+
throw new RelayError('invalid_route');
|
|
91
|
+
const p = this.security.authenticate(req.headers.authorization);
|
|
92
|
+
if (url.pathname === '/v1/media') {
|
|
93
|
+
const session = req.headers['x-nova-media-session'];
|
|
94
|
+
if (typeof session !== 'string')
|
|
95
|
+
throw new RelayError('invalid_media_session');
|
|
96
|
+
this.mediaSockets.handleUpgrade(req, socket, head, ws => { if (release)
|
|
97
|
+
ws.once('close', release); this.mediaConnected(p, session, ws, req); });
|
|
98
|
+
}
|
|
99
|
+
else
|
|
100
|
+
this.sockets.handleUpgrade(req, socket, head, ws => { if (release)
|
|
101
|
+
ws.once('close', release); this.connected(p, ws, req); });
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
release?.();
|
|
105
|
+
const code = this.errorCode(error);
|
|
106
|
+
socket.end(`HTTP/1.1 ${this.errorStatus(code)} Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
this.maintenance = setInterval(() => {
|
|
110
|
+
this.live.sweep();
|
|
111
|
+
try {
|
|
112
|
+
this.media.sweep();
|
|
113
|
+
}
|
|
114
|
+
catch { /* A clock fault must not stop rate-bucket maintenance. */ }
|
|
115
|
+
const before = Date.now() - 60000;
|
|
116
|
+
for (const [key, value] of this.rates)
|
|
117
|
+
if (value.start <= before)
|
|
118
|
+
this.rates.delete(key);
|
|
119
|
+
}, 1000);
|
|
120
|
+
this.maintenance.unref();
|
|
121
|
+
}
|
|
122
|
+
async listen() {
|
|
123
|
+
await new Promise((resolve, reject) => {
|
|
124
|
+
const failed = (error) => { reject(error); };
|
|
125
|
+
this.http.once('error', failed);
|
|
126
|
+
this.http.listen(this.options.port, this.options.bind, () => { this.http.off('error', failed); resolve(); });
|
|
127
|
+
});
|
|
128
|
+
const address = this.http.address();
|
|
129
|
+
return `${this.options.tls ? 'https' : 'http'}://${address.address.includes(':') ? `[${address.address}]` : address.address}:${address.port}`;
|
|
130
|
+
}
|
|
131
|
+
async close() {
|
|
132
|
+
clearInterval(this.maintenance);
|
|
133
|
+
for (const ws of this.sockets.clients)
|
|
134
|
+
ws.terminate();
|
|
135
|
+
for (const ws of this.mediaSockets.clients)
|
|
136
|
+
ws.terminate();
|
|
137
|
+
await new Promise(resolve => this.sockets.close(() => resolve()));
|
|
138
|
+
await new Promise(resolve => this.mediaSockets.close(() => resolve()));
|
|
139
|
+
try {
|
|
140
|
+
await new Promise((resolve, reject) => this.http.close(error => {
|
|
141
|
+
if (error && error.code !== 'ERR_SERVER_NOT_RUNNING')
|
|
142
|
+
reject(error);
|
|
143
|
+
else
|
|
144
|
+
resolve();
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
this.security.close();
|
|
149
|
+
this.mailbox.close();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
source(req) {
|
|
153
|
+
let value = this.requestSources.get(req);
|
|
154
|
+
if (value === undefined) {
|
|
155
|
+
value = sourceAddress(req, this.trustedProxies);
|
|
156
|
+
this.requestSources.set(req, value);
|
|
157
|
+
}
|
|
158
|
+
return value;
|
|
159
|
+
}
|
|
160
|
+
reserveForwardedConnection(req) {
|
|
161
|
+
if (!this.trustedProxies.has(canonicalAddress(req.socket.remoteAddress ?? '0.0.0.0')))
|
|
162
|
+
return () => { };
|
|
163
|
+
const ip = this.source(req), count = this.forwardedConnections.get(ip) ?? 0;
|
|
164
|
+
if (count >= this.options.maxConnectionsPerIp)
|
|
165
|
+
throw new RelayError('rate_limited');
|
|
166
|
+
this.forwardedConnections.set(ip, count + 1);
|
|
167
|
+
let released = false;
|
|
168
|
+
return () => { if (released)
|
|
169
|
+
return; released = true; const remaining = (this.forwardedConnections.get(ip) ?? 1) - 1; if (remaining > 0)
|
|
170
|
+
this.forwardedConnections.set(ip, remaining);
|
|
171
|
+
else
|
|
172
|
+
this.forwardedConnections.delete(ip); };
|
|
173
|
+
}
|
|
174
|
+
rate(req, bootstrap) {
|
|
175
|
+
const now = Date.now();
|
|
176
|
+
const prefix = bootstrap ? 'bootstrap' : 'all';
|
|
177
|
+
for (const [key, limit] of [[`${prefix}:source:${this.source(req)}`, bootstrap ? this.options.bootstrapPerMinute : this.options.requestsPerMinute],
|
|
178
|
+
[`${prefix}:global`, bootstrap ? this.options.globalBootstrapPerMinute : this.options.globalRequestsPerMinute]]) {
|
|
179
|
+
let bucket = this.rates.get(key);
|
|
180
|
+
if (!bucket || now - bucket.start >= 60000) {
|
|
181
|
+
if (!bucket && this.rates.size >= this.options.maxRateSources)
|
|
182
|
+
throw new RelayError('rate_limited');
|
|
183
|
+
bucket = { start: now, count: 0 };
|
|
184
|
+
this.rates.set(key, bucket);
|
|
185
|
+
}
|
|
186
|
+
if (++bucket.count > limit)
|
|
187
|
+
throw new RelayError('rate_limited');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async body(req) {
|
|
191
|
+
if (req.headers['content-type']?.split(';')[0]?.trim() !== 'application/json')
|
|
192
|
+
throw new RelayError('json_required');
|
|
193
|
+
const declared = req.headers['content-length'];
|
|
194
|
+
if (declared && (!/^\d+$/.test(declared) || Number(declared) > this.options.maxBodyBytes))
|
|
195
|
+
throw new RelayError('body_too_large');
|
|
196
|
+
const chunks = [];
|
|
197
|
+
let bytes = 0;
|
|
198
|
+
for await (const chunk of req) {
|
|
199
|
+
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
200
|
+
bytes += value.length;
|
|
201
|
+
if (bytes > this.options.maxBodyBytes)
|
|
202
|
+
throw new RelayError('body_too_large');
|
|
203
|
+
chunks.push(value);
|
|
204
|
+
}
|
|
205
|
+
let body;
|
|
206
|
+
try {
|
|
207
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
throw new RelayError('invalid_json');
|
|
211
|
+
}
|
|
212
|
+
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
213
|
+
throw new RelayError('invalid_json');
|
|
214
|
+
return body;
|
|
215
|
+
}
|
|
216
|
+
integer(value) {
|
|
217
|
+
if (value === null)
|
|
218
|
+
return undefined;
|
|
219
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)))
|
|
220
|
+
throw new RelayError('invalid_cursor');
|
|
221
|
+
return Number(value);
|
|
222
|
+
}
|
|
223
|
+
async route(req, res) {
|
|
224
|
+
try {
|
|
225
|
+
const release = this.reserveForwardedConnection(req);
|
|
226
|
+
res.once('finish', release);
|
|
227
|
+
res.once('close', release);
|
|
228
|
+
this.rate(req, false);
|
|
229
|
+
const url = new URL(req.url ?? '/', 'http://relay.invalid');
|
|
230
|
+
const route = `${req.method} ${url.pathname}`;
|
|
231
|
+
let result;
|
|
232
|
+
// Source-limited bootstrap endpoints require proof of key possession; no caller-supplied principal.
|
|
233
|
+
if (['POST /v1/spaces', 'POST /v1/auth/challenge', 'POST /v1/auth/session', 'POST /v1/pairing/requests'].includes(route)) {
|
|
234
|
+
this.rate(req, true);
|
|
235
|
+
const body = await this.body(req);
|
|
236
|
+
if (route === 'POST /v1/spaces')
|
|
237
|
+
result = this.security.createSpace(body, String(req.headers['x-relay-bootstrap-token'] ?? ''));
|
|
238
|
+
else if (route === 'POST /v1/auth/challenge')
|
|
239
|
+
result = this.security.beginLogin(String(body.space ?? ''), String(body.device ?? ''));
|
|
240
|
+
else if (route === 'POST /v1/auth/session')
|
|
241
|
+
result = this.security.completeLogin(body);
|
|
242
|
+
else
|
|
243
|
+
result = this.security.requestPairing(body);
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
const p = this.security.authenticate(req.headers.authorization);
|
|
247
|
+
switch (route) {
|
|
248
|
+
case 'GET /v1/mailbox': {
|
|
249
|
+
const after = this.integer(url.searchParams.get('after'));
|
|
250
|
+
const limit = this.integer(url.searchParams.get('limit'));
|
|
251
|
+
result = this.mailbox.read(p, { maxBytes: this.options.maxResponseBytes - 256, ...(after === undefined ? {} : { after }), ...(limit === undefined ? {} : { limit }) });
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
case 'GET /v1/mailbox/status':
|
|
255
|
+
result = this.mailbox.status(p);
|
|
256
|
+
break;
|
|
257
|
+
case 'POST /v1/mailbox': {
|
|
258
|
+
const envelope = await this.body(req);
|
|
259
|
+
const accepted = this.mailbox.send(p, envelope);
|
|
260
|
+
result = accepted;
|
|
261
|
+
if (!accepted.duplicate && this.options.onMailbox) {
|
|
262
|
+
// A failed external wake never rolls back durable mail or changes its HTTP outcome.
|
|
263
|
+
try {
|
|
264
|
+
void Promise.resolve(this.options.onMailbox(p, envelope, accepted.seq)).catch(() => { });
|
|
265
|
+
}
|
|
266
|
+
catch { /* Wake is best effort. */ }
|
|
267
|
+
}
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
case 'POST /v1/mailbox/ack':
|
|
271
|
+
result = { ackCursor: this.mailbox.acknowledge(p, (await this.body(req)).cursor) };
|
|
272
|
+
break;
|
|
273
|
+
case 'GET /v1/presence':
|
|
274
|
+
result = { online: this.live.presence(p, url.searchParams.get('device') ?? '') };
|
|
275
|
+
break;
|
|
276
|
+
case 'POST /v1/stream':
|
|
277
|
+
this.live.send(p, await this.body(req));
|
|
278
|
+
result = { accepted: true };
|
|
279
|
+
break;
|
|
280
|
+
case 'POST /v1/pairing/invitations':
|
|
281
|
+
result = this.security.createInvitation(p, await this.body(req));
|
|
282
|
+
break;
|
|
283
|
+
case 'GET /v1/pairing/requests':
|
|
284
|
+
result = this.security.pendingPairings(p);
|
|
285
|
+
break;
|
|
286
|
+
case 'POST /v1/pairing/confirm': {
|
|
287
|
+
const body = await this.body(req);
|
|
288
|
+
result = this.security.confirmPairing(p, String(body.requestId ?? ''), String(body.opId ?? ''));
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
case 'GET /v1/devices':
|
|
292
|
+
result = this.security.listDevices(p);
|
|
293
|
+
break;
|
|
294
|
+
case 'POST /v1/devices/revoke': {
|
|
295
|
+
const body = await this.body(req);
|
|
296
|
+
result = this.security.revokeDevice(p, String(body.device ?? ''), String(body.opId ?? ''));
|
|
297
|
+
this.live.sweep();
|
|
298
|
+
this.media.sweep();
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
case 'POST /v1/media/sessions': {
|
|
302
|
+
if (!this.media.enabled)
|
|
303
|
+
throw new RelayError('invalid_route');
|
|
304
|
+
const body = await this.body(req);
|
|
305
|
+
result = this.media.reserve(p, { session: body.session, client: body.client, ttlMs: body.ttlMs });
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
case 'GET /v1/capabilities':
|
|
309
|
+
if (!this.media.enabled)
|
|
310
|
+
throw new RelayError('invalid_route');
|
|
311
|
+
result = { media: { v: 1, codecs: ['pcm16'], maxKbpsPerDirection: this.media.maxKbpsPerDirection, maxFrameBytes: this.media.maxFrameBytes } };
|
|
312
|
+
break;
|
|
313
|
+
default: throw new RelayError('invalid_route');
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
this.json(res, 200, result);
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
const code = this.errorCode(error);
|
|
320
|
+
this.json(res, this.errorStatus(code), { error: code });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
json(res, status, value) {
|
|
324
|
+
if (res.destroyed || res.headersSent)
|
|
325
|
+
return;
|
|
326
|
+
const body = JSON.stringify(value);
|
|
327
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store',
|
|
328
|
+
'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(body) });
|
|
329
|
+
res.end(body);
|
|
330
|
+
}
|
|
331
|
+
errorCode(error) { return error instanceof RelayError ? error.code : 'invalid_request'; }
|
|
332
|
+
errorStatus(code) {
|
|
333
|
+
if (code === 'rate_limited')
|
|
334
|
+
return 429;
|
|
335
|
+
if (['body_too_large', 'message_too_large'].includes(code))
|
|
336
|
+
return 413;
|
|
337
|
+
if (code === 'invalid_route')
|
|
338
|
+
return 404;
|
|
339
|
+
if (['media_capacity', 'media_session_exists', 'media_role_claimed', 'media_session_limit'].includes(code))
|
|
340
|
+
return 409;
|
|
341
|
+
if (['offline', 'id_conflict', 'cursor_expired', 'capacity_exceeded', 'history_capacity_exceeded', 'backpressure', 'page_too_small'].includes(code))
|
|
342
|
+
return 409;
|
|
343
|
+
if (/auth|session|token|signature|proof|revoked|epoch|forbidden|host_required|inactive|unknown_device/.test(code))
|
|
344
|
+
return 401;
|
|
345
|
+
return 400;
|
|
346
|
+
}
|
|
347
|
+
connected(p, ws, req) {
|
|
348
|
+
let connection;
|
|
349
|
+
try {
|
|
350
|
+
connection = this.live.connect(p, {
|
|
351
|
+
send: envelope => new Promise((resolve, reject) => {
|
|
352
|
+
try {
|
|
353
|
+
this.security.authenticate(req.headers.authorization);
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
reject(error);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 1024 * 1024) {
|
|
360
|
+
reject(new RelayError('backpressure'));
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
ws.send(JSON.stringify({ type: 'stream', envelope }), error => error ? reject(error) : resolve());
|
|
364
|
+
}),
|
|
365
|
+
close: () => ws.terminate(),
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
ws.terminate();
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const heartbeat = () => { try {
|
|
373
|
+
this.security.authenticate(req.headers.authorization);
|
|
374
|
+
connection.heartbeat();
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
ws.terminate();
|
|
378
|
+
} };
|
|
379
|
+
const timer = setInterval(() => { if (ws.readyState === WebSocket.OPEN)
|
|
380
|
+
ws.ping(); }, 10000);
|
|
381
|
+
timer.unref();
|
|
382
|
+
const controlFrame = () => { try {
|
|
383
|
+
this.rate(req, false);
|
|
384
|
+
heartbeat();
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
ws.terminate();
|
|
388
|
+
} };
|
|
389
|
+
ws.on('pong', controlFrame);
|
|
390
|
+
ws.on('ping', controlFrame);
|
|
391
|
+
ws.on('message', (data, isBinary) => {
|
|
392
|
+
try {
|
|
393
|
+
this.rate(req, false);
|
|
394
|
+
if (isBinary)
|
|
395
|
+
throw new RelayError('invalid_frame');
|
|
396
|
+
if (JSON.parse(data.toString()).type !== 'heartbeat')
|
|
397
|
+
throw new RelayError('invalid_frame');
|
|
398
|
+
heartbeat();
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
ws.close(1008, 'invalid_frame');
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
ws.on('error', () => ws.terminate());
|
|
405
|
+
ws.on('close', () => { clearInterval(timer); try {
|
|
406
|
+
connection.close();
|
|
407
|
+
}
|
|
408
|
+
catch { /* Revoked connections already dropped. */ } });
|
|
409
|
+
ws.send(JSON.stringify({ type: 'ready', principal: p }));
|
|
410
|
+
}
|
|
411
|
+
/** One media leg. Frames are opaque; only renewal text frames are parsed (docs/design/space-voice.md §1). */
|
|
412
|
+
mediaConnected(p, session, ws, req) {
|
|
413
|
+
let header = String(req.headers.authorization ?? '');
|
|
414
|
+
let leg;
|
|
415
|
+
const same = (a, b) => a.space === b.space && a.device === b.device && a.epoch === b.epoch;
|
|
416
|
+
// `join` may drain the peer's early control frames synchronously: binary writes are held
|
|
417
|
+
// until the `ready` text frame is on the socket, so clients always see `ready` first.
|
|
418
|
+
let readySent = false;
|
|
419
|
+
const held = [];
|
|
420
|
+
try {
|
|
421
|
+
leg = this.media.join(p, session, {
|
|
422
|
+
write: frame => new Promise((resolve, reject) => {
|
|
423
|
+
const write = () => {
|
|
424
|
+
if (ws.readyState !== WebSocket.OPEN) {
|
|
425
|
+
reject(new RelayError('offline'));
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
ws.send(frame, { binary: true }, error => error ? reject(error) : resolve());
|
|
429
|
+
};
|
|
430
|
+
if (readySent)
|
|
431
|
+
write();
|
|
432
|
+
else
|
|
433
|
+
held.push(write);
|
|
434
|
+
}),
|
|
435
|
+
close: reason => { try {
|
|
436
|
+
ws.close(1000, reason);
|
|
437
|
+
}
|
|
438
|
+
catch {
|
|
439
|
+
ws.terminate();
|
|
440
|
+
} setTimeout(() => ws.terminate(), 1000).unref(); },
|
|
441
|
+
authorized: () => same(this.security.authenticate(header), p),
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
ws.close(1008, this.errorCode(error));
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
const timer = setInterval(() => { if (ws.readyState === WebSocket.OPEN)
|
|
449
|
+
ws.ping(); }, 10000);
|
|
450
|
+
timer.unref();
|
|
451
|
+
ws.on('message', (data, isBinary) => {
|
|
452
|
+
try {
|
|
453
|
+
const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
454
|
+
if (isBinary) {
|
|
455
|
+
leg.receive(bytes);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
this.rate(req, false);
|
|
459
|
+
const frame = JSON.parse(bytes.toString('utf8'));
|
|
460
|
+
if (frame.type !== 'renew' || typeof frame.token !== 'string')
|
|
461
|
+
throw new RelayError('invalid_frame');
|
|
462
|
+
const next = `Bearer ${frame.token}`;
|
|
463
|
+
leg.renew(this.security.authenticate(next));
|
|
464
|
+
header = next;
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
ws.close(1008, 'invalid_frame');
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
ws.on('error', () => ws.terminate());
|
|
471
|
+
ws.on('close', () => { clearInterval(timer); leg.close(); });
|
|
472
|
+
ws.send(JSON.stringify({ type: 'ready', role: leg.role }));
|
|
473
|
+
readySent = true;
|
|
474
|
+
for (const write of held.splice(0))
|
|
475
|
+
write();
|
|
476
|
+
}
|
|
477
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
import { RelayError } from './protocol.js';
|
|
3
|
+
/** Exact IP trust, never hostnames, arbitrary forwarding headers or implicit hop counts. */
|
|
4
|
+
export function canonicalAddress(value) {
|
|
5
|
+
const version = isIP(value);
|
|
6
|
+
if (version === 4)
|
|
7
|
+
return value;
|
|
8
|
+
if (version !== 6)
|
|
9
|
+
throw new RelayError('invalid_source_address');
|
|
10
|
+
let canonical;
|
|
11
|
+
try {
|
|
12
|
+
canonical = new URL(`http://[${value}]/`).hostname.slice(1, -1);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
throw new RelayError('invalid_source_address');
|
|
16
|
+
}
|
|
17
|
+
const mapped = /^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/.exec(canonical);
|
|
18
|
+
if (mapped) {
|
|
19
|
+
const high = parseInt(mapped[1], 16), low = parseInt(mapped[2], 16);
|
|
20
|
+
return [high >>> 8, high & 255, low >>> 8, low & 255].join('.');
|
|
21
|
+
}
|
|
22
|
+
return canonical;
|
|
23
|
+
}
|
|
24
|
+
export function trustedAddresses(values = []) {
|
|
25
|
+
if (!Array.isArray(values) || values.length > 64 || values.some(value => typeof value !== 'string'))
|
|
26
|
+
throw new RelayError('invalid_trusted_proxies');
|
|
27
|
+
try {
|
|
28
|
+
return new Set(values.map(canonicalAddress));
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new RelayError('invalid_trusted_proxies');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function sourceAddress(req, trusted) {
|
|
35
|
+
let current = canonicalAddress(req.socket.remoteAddress ?? '0.0.0.0');
|
|
36
|
+
// A direct client can forge forwarding headers; they are deliberately ignored.
|
|
37
|
+
if (!trusted.has(current))
|
|
38
|
+
return current;
|
|
39
|
+
const raw = req.headers['x-forwarded-for'];
|
|
40
|
+
if (raw === undefined)
|
|
41
|
+
return current;
|
|
42
|
+
if (typeof raw !== 'string' || raw.length > 2048)
|
|
43
|
+
throw new RelayError('invalid_forwarded_address');
|
|
44
|
+
const chain = raw.split(',');
|
|
45
|
+
if (chain.length > 16)
|
|
46
|
+
throw new RelayError('invalid_forwarded_address');
|
|
47
|
+
let addresses;
|
|
48
|
+
try {
|
|
49
|
+
addresses = chain.map(value => canonicalAddress(value.trim()));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new RelayError('invalid_forwarded_address');
|
|
53
|
+
}
|
|
54
|
+
// Stop at the first untrusted hop from the socket. Attacker-controlled prefixes never win.
|
|
55
|
+
while (trusted.has(current) && addresses.length)
|
|
56
|
+
current = addresses.pop();
|
|
57
|
+
return current;
|
|
58
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"@nova-personal-agent/relay","version":"1.0.2","type":"module","exports":{".":"./dist/src/client.js","./client":"./dist/src/client.js","./crypto":"./dist/src/crypto.js","./security":"./dist/src/security.js","./pairing":"./dist/src/pairing.js","./protocol":"./dist/src/protocol.js","./server":"./dist/src/server.js"},"engines":{"node":">=22.13.0"},"license":"GPL-3.0-or-later"}
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nova-personal-agent-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "Headless Nova Personal Agent service and terminal device pairing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"novapersonal-server": "bin/novapersonal-server.mjs",
|
|
8
|
-
"novaaudio-server": "bin/novapersonal-server.mjs"
|
|
8
|
+
"novaaudio-server": "bin/novapersonal-server.mjs",
|
|
9
|
+
"nova-space-host": "bin/nova-space-host.mjs"
|
|
9
10
|
},
|
|
10
11
|
"engines": {
|
|
11
12
|
"node": ">=22.14.0"
|
|
@@ -45,17 +46,23 @@
|
|
|
45
46
|
"playwright": "1.63.0",
|
|
46
47
|
"qrcode": "1.5.4",
|
|
47
48
|
"saxes": "^6.0.0",
|
|
49
|
+
"smol-toml": "1.9.1",
|
|
48
50
|
"undici": "7.29.0",
|
|
49
51
|
"voicemem": "0.0.1",
|
|
50
52
|
"ws": "8.21.3",
|
|
51
|
-
"zod": "4.4.3"
|
|
53
|
+
"zod": "4.4.3",
|
|
54
|
+
"@nova-personal-agent/relay": "1.0.2",
|
|
55
|
+
"jose": "6.2.10"
|
|
52
56
|
},
|
|
53
|
-
"
|
|
57
|
+
"bundleDependencies": [
|
|
58
|
+
"@nova-personal-agent/relay"
|
|
59
|
+
],
|
|
60
|
+
"license": "GPL-3.0-or-later",
|
|
54
61
|
"repository": {
|
|
55
62
|
"type": "git",
|
|
56
|
-
"url": "git+https://github.com/deepnovacore/
|
|
63
|
+
"url": "git+https://github.com/deepnovacore/NovaPersonalAgent.git"
|
|
57
64
|
},
|
|
58
|
-
"homepage": "https://deepnovacore.github.io/
|
|
65
|
+
"homepage": "https://deepnovacore.github.io/NovaPersonalAgent/",
|
|
59
66
|
"publishConfig": {
|
|
60
67
|
"access": "public",
|
|
61
68
|
"registry": "https://registry.npmjs.org/"
|
|
@@ -5,15 +5,20 @@ import { capabilitiesFromSettings } from './config/config.js';
|
|
|
5
5
|
import { CascadedRealtimeAdapter } from './realtime/cascaded/adapter.js';
|
|
6
6
|
import { frontendInstructions } from './realtime/frontend-instructions.js';
|
|
7
7
|
import { usageReporterForEndpoint } from './realtime/usage.js';
|
|
8
|
+
/** Same selected text model, transports and usage routing for chat, planning and local builds. */
|
|
9
|
+
export function configuredTextLlm(options, registry = cascadedProviderRegistries) {
|
|
10
|
+
const selected = requireSelectedCascadedLlmConfig(options.settings);
|
|
11
|
+
return registry.llm[selected.provider === 'ark' ? 'ark' : 'qwen']({ config: selected.config, clock: options.clock, ids: { next: options.idFactory }, instructions: options.instructions, ...(options.transport ? { transport: options.transport } : {}), ...(options.onUsage ? { onUsage: usageReporterForEndpoint(options.onUsage, selected.config.baseUrl) } : {}) });
|
|
12
|
+
}
|
|
8
13
|
/** One independent text conversation. Construct no endpointing, recognition, or synthesis nodes. */
|
|
9
14
|
export function buildCascadedTextProvider(options, registry = cascadedProviderRegistries) {
|
|
10
15
|
const selected = requireSelectedCascadedLlmConfig(options.settings);
|
|
11
16
|
const capabilities = capabilitiesFromSettings(options.settings);
|
|
12
17
|
const input = { config: selected.config, clock: options.clock, ids: { next: options.idFactory }, instructions: options.sourceProcessingTask ? SOURCE_PROCESSING_INSTRUCTIONS : options.scheduledTask ? scheduledTaskInstructions(options.settings.language) : frontendInstructions({
|
|
13
|
-
schedules: options.schedules === true, search: capabilities.modules.search.enabled, camera: options.captureFrame !== undefined, coding: capabilities.modules.coding.enabled, gui: options.settings.executors.some(name => ['browser', 'computer', 'mobile'].includes(name)), knowledge: capabilities.modules.knowledge.enabled,
|
|
18
|
+
...(options.memoryTools ? { memoryTools: options.memoryTools } : {}), schedules: options.schedules === true, search: capabilities.modules.search.enabled, camera: options.captureFrame !== undefined, coding: capabilities.modules.coding.enabled, gui: options.settings.executors.some(name => ['browser', 'computer', 'mobile'].includes(name)), knowledge: capabilities.modules.knowledge.enabled, chatToolPolicy: options.chatToolPolicy === true,
|
|
14
19
|
}, options.executorApproval === true), ...(options.onUsage === undefined ? {} : { onUsage: usageReporterForEndpoint(options.onUsage, selected.config.baseUrl) }) };
|
|
15
|
-
const factory =
|
|
16
|
-
return new CascadedRealtimeAdapter({ language: options.settings.language, textOnly: true, scheduledTask: options.scheduledTask === true, llm: factory.open(), llmFactory: factory, idFactory: options.idFactory, ...(options.prerecall === undefined ? {} : { prerecall: options.prerecall }), ...(options.captureFrame === undefined ? {} : { captureFrame: options.captureFrame }), ...(options.telemetry === undefined ? {} : { telemetry: options.telemetry }), ...(options.history === undefined ? {} : { history: options.history }) });
|
|
20
|
+
const factory = configuredTextLlm({ ...options, instructions: input.instructions }, registry);
|
|
21
|
+
return new CascadedRealtimeAdapter({ language: options.settings.language, textOnly: true, scheduledTask: options.scheduledTask === true, llm: factory.open(), llmFactory: factory, idFactory: options.idFactory, ...(options.prerecall === undefined ? {} : { prerecall: options.prerecall }), ...(options.prerecallPolicy === undefined ? {} : { prerecallPolicy: options.prerecallPolicy }), ...(options.prerecallMeta === undefined ? {} : { prerecallMeta: options.prerecallMeta }), ...(options.captureFrame === undefined ? {} : { captureFrame: options.captureFrame }), ...(options.telemetry === undefined ? {} : { telemetry: options.telemetry }), ...(options.history === undefined ? {} : { history: options.history }) });
|
|
17
22
|
}
|
|
18
23
|
function scheduledTaskInstructions(language) {
|
|
19
24
|
return language === 'en' ? [
|