@namzu/sdk 65.3.0 → 67.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +153 -0
- package/dist/account/lock.d.ts +4 -12
- package/dist/account/lock.d.ts.map +1 -1
- package/dist/account/lock.js +5 -140
- package/dist/account/lock.js.map +1 -1
- package/dist/account/registry.d.ts.map +1 -1
- package/dist/account/registry.js +50 -6
- package/dist/account/registry.js.map +1 -1
- package/dist/account/types.d.ts +7 -5
- package/dist/account/types.d.ts.map +1 -1
- package/dist/account/types.js +6 -7
- package/dist/account/types.js.map +1 -1
- package/dist/authorization/dangerous-commands.d.ts +64 -0
- package/dist/authorization/dangerous-commands.d.ts.map +1 -0
- package/dist/authorization/dangerous-commands.js +479 -0
- package/dist/authorization/dangerous-commands.js.map +1 -0
- package/dist/authorization/gate.d.ts.map +1 -1
- package/dist/authorization/gate.js +19 -5
- package/dist/authorization/gate.js.map +1 -1
- package/dist/authorization/protected-paths.d.ts +11 -6
- package/dist/authorization/protected-paths.d.ts.map +1 -1
- package/dist/authorization/protected-paths.js +13 -8
- package/dist/authorization/protected-paths.js.map +1 -1
- package/dist/authorization/readonly-commands.d.ts +6 -1
- package/dist/authorization/readonly-commands.d.ts.map +1 -1
- package/dist/authorization/readonly-commands.js +35 -1
- package/dist/authorization/readonly-commands.js.map +1 -1
- package/dist/authorization/removal.d.ts +10 -0
- package/dist/authorization/removal.d.ts.map +1 -1
- package/dist/authorization/removal.js +7 -7
- package/dist/authorization/removal.js.map +1 -1
- package/dist/authorization/rules.d.ts +10 -0
- package/dist/authorization/rules.d.ts.map +1 -1
- package/dist/authorization/rules.js +60 -14
- package/dist/authorization/rules.js.map +1 -1
- package/dist/authorization/shell-lexer.d.ts +10 -0
- package/dist/authorization/shell-lexer.d.ts.map +1 -1
- package/dist/authorization/shell-lexer.js +15 -0
- package/dist/authorization/shell-lexer.js.map +1 -1
- package/dist/bridge/acp/permission.d.ts +5 -0
- package/dist/bridge/acp/permission.d.ts.map +1 -1
- package/dist/bridge/acp/permission.js.map +1 -1
- package/dist/bridge/acp/server.d.ts +8 -1
- package/dist/bridge/acp/server.d.ts.map +1 -1
- package/dist/bridge/acp/server.js +48 -6
- package/dist/bridge/acp/server.js.map +1 -1
- package/dist/compaction/context-breakdown.d.ts +25 -6
- package/dist/compaction/context-breakdown.d.ts.map +1 -1
- package/dist/compaction/context-breakdown.js +27 -7
- package/dist/compaction/context-breakdown.js.map +1 -1
- package/dist/compaction/dangling.d.ts.map +1 -1
- package/dist/compaction/dangling.js +2 -0
- package/dist/compaction/dangling.js.map +1 -1
- package/dist/compaction/extractor.d.ts +7 -1
- package/dist/compaction/extractor.d.ts.map +1 -1
- package/dist/compaction/extractor.js +8 -1
- package/dist/compaction/extractor.js.map +1 -1
- package/dist/compaction/index.d.ts +1 -1
- package/dist/compaction/index.d.ts.map +1 -1
- package/dist/compaction/index.js +1 -1
- package/dist/compaction/index.js.map +1 -1
- package/dist/compaction/managers/structured.js +2 -2
- package/dist/compaction/managers/structured.js.map +1 -1
- package/dist/compaction/manual.d.ts.map +1 -1
- package/dist/compaction/manual.js +11 -6
- package/dist/compaction/manual.js.map +1 -1
- package/dist/compaction/model-summary.d.ts.map +1 -1
- package/dist/compaction/model-summary.js +7 -1
- package/dist/compaction/model-summary.js.map +1 -1
- package/dist/compaction/summary.d.ts +13 -2
- package/dist/compaction/summary.d.ts.map +1 -1
- package/dist/compaction/summary.js +46 -3
- package/dist/compaction/summary.js.map +1 -1
- package/dist/constants/tools/index.d.ts +18 -1
- package/dist/constants/tools/index.d.ts.map +1 -1
- package/dist/constants/tools/index.js +28 -16
- package/dist/constants/tools/index.js.map +1 -1
- package/dist/manager/session/turn-recorder.d.ts +6 -0
- package/dist/manager/session/turn-recorder.d.ts.map +1 -1
- package/dist/manager/session/turn-recorder.js +29 -1
- package/dist/manager/session/turn-recorder.js.map +1 -1
- package/dist/network/audit.d.ts +49 -0
- package/dist/network/audit.d.ts.map +1 -0
- package/dist/network/audit.js +84 -0
- package/dist/network/audit.js.map +1 -0
- package/dist/network/clock.d.ts +21 -0
- package/dist/network/clock.d.ts.map +1 -0
- package/dist/network/clock.js +51 -0
- package/dist/network/clock.js.map +1 -0
- package/dist/network/discovery-mdns.d.ts +120 -0
- package/dist/network/discovery-mdns.d.ts.map +1 -0
- package/dist/network/discovery-mdns.js +442 -0
- package/dist/network/discovery-mdns.js.map +1 -0
- package/dist/network/discovery.d.ts +63 -0
- package/dist/network/discovery.d.ts.map +1 -0
- package/dist/network/discovery.js +163 -0
- package/dist/network/discovery.js.map +1 -0
- package/dist/network/fingerprint.d.ts +73 -0
- package/dist/network/fingerprint.d.ts.map +1 -0
- package/dist/network/fingerprint.js +208 -0
- package/dist/network/fingerprint.js.map +1 -0
- package/dist/network/identity.d.ts +38 -0
- package/dist/network/identity.d.ts.map +1 -0
- package/dist/network/identity.js +71 -0
- package/dist/network/identity.js.map +1 -0
- package/dist/network/index.d.ts +39 -0
- package/dist/network/index.d.ts.map +1 -0
- package/dist/network/index.js +25 -0
- package/dist/network/index.js.map +1 -0
- package/dist/network/join.d.ts +69 -0
- package/dist/network/join.d.ts.map +1 -0
- package/dist/network/join.js +136 -0
- package/dist/network/join.js.map +1 -0
- package/dist/network/mail-policy.d.ts +97 -0
- package/dist/network/mail-policy.d.ts.map +1 -0
- package/dist/network/mail-policy.js +147 -0
- package/dist/network/mail-policy.js.map +1 -0
- package/dist/network/membership.d.ts +76 -0
- package/dist/network/membership.d.ts.map +1 -0
- package/dist/network/membership.js +225 -0
- package/dist/network/membership.js.map +1 -0
- package/dist/network/roster.d.ts +59 -0
- package/dist/network/roster.d.ts.map +1 -0
- package/dist/network/roster.js +120 -0
- package/dist/network/roster.js.map +1 -0
- package/dist/network/service.d.ts +303 -0
- package/dist/network/service.d.ts.map +1 -0
- package/dist/network/service.js +1891 -0
- package/dist/network/service.js.map +1 -0
- package/dist/network/store.d.ts +141 -0
- package/dist/network/store.d.ts.map +1 -0
- package/dist/network/store.js +198 -0
- package/dist/network/store.js.map +1 -0
- package/dist/network/transport.d.ts +96 -0
- package/dist/network/transport.d.ts.map +1 -0
- package/dist/network/transport.js +342 -0
- package/dist/network/transport.js.map +1 -0
- package/dist/network/wire.d.ts +345 -0
- package/dist/network/wire.d.ts.map +1 -0
- package/dist/network/wire.js +212 -0
- package/dist/network/wire.js.map +1 -0
- package/dist/network/x509.d.ts +28 -0
- package/dist/network/x509.d.ts.map +1 -0
- package/dist/network/x509.js +84 -0
- package/dist/network/x509.js.map +1 -0
- package/dist/pals/activity/causality.d.ts.map +1 -1
- package/dist/pals/activity/causality.js +14 -2
- package/dist/pals/activity/causality.js.map +1 -1
- package/dist/peers/endpoint.d.ts.map +1 -1
- package/dist/peers/endpoint.js +6 -0
- package/dist/peers/endpoint.js.map +1 -1
- package/dist/peers/envelope.d.ts +18 -0
- package/dist/peers/envelope.d.ts.map +1 -1
- package/dist/peers/envelope.js +68 -5
- package/dist/peers/envelope.js.map +1 -1
- package/dist/peers/index.d.ts +5 -4
- package/dist/peers/index.d.ts.map +1 -1
- package/dist/peers/index.js +3 -2
- package/dist/peers/index.js.map +1 -1
- package/dist/peers/mode-word.d.ts +10 -0
- package/dist/peers/mode-word.d.ts.map +1 -0
- package/dist/peers/mode-word.js +19 -0
- package/dist/peers/mode-word.js.map +1 -0
- package/dist/peers/protocol.d.ts +42 -0
- package/dist/peers/protocol.d.ts.map +1 -1
- package/dist/peers/protocol.js +22 -1
- package/dist/peers/protocol.js.map +1 -1
- package/dist/peers/record.d.ts +8 -0
- package/dist/peers/record.d.ts.map +1 -1
- package/dist/peers/record.js +5 -0
- package/dist/peers/record.js.map +1 -1
- package/dist/plugin/session-hook-env.d.ts.map +1 -1
- package/dist/plugin/session-hook-env.js +22 -2
- package/dist/plugin/session-hook-env.js.map +1 -1
- package/dist/plugin/shell-hook.d.ts +16 -2
- package/dist/plugin/shell-hook.d.ts.map +1 -1
- package/dist/plugin/shell-hook.js +183 -14
- package/dist/plugin/shell-hook.js.map +1 -1
- package/dist/prompt/coding-agent-doctrine.d.ts +4 -2
- package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
- package/dist/prompt/coding-agent-doctrine.js +33 -38
- package/dist/prompt/coding-agent-doctrine.js.map +1 -1
- package/dist/public-runtime.d.ts +14 -6
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +22 -5
- package/dist/public-runtime.js.map +1 -1
- package/dist/public-tools.d.ts +3 -2
- package/dist/public-tools.d.ts.map +1 -1
- package/dist/public-tools.js +2 -2
- package/dist/public-tools.js.map +1 -1
- package/dist/public-types.d.ts +7 -2
- package/dist/public-types.d.ts.map +1 -1
- package/dist/runtime/jobs/registry.d.ts +29 -1
- package/dist/runtime/jobs/registry.d.ts.map +1 -1
- package/dist/runtime/jobs/registry.js +64 -0
- package/dist/runtime/jobs/registry.js.map +1 -1
- package/dist/runtime/query/auto-review/classifier.d.ts +30 -6
- package/dist/runtime/query/auto-review/classifier.d.ts.map +1 -1
- package/dist/runtime/query/auto-review/classifier.js +40 -12
- package/dist/runtime/query/auto-review/classifier.js.map +1 -1
- package/dist/runtime/query/auto-review/feedback.d.ts +37 -0
- package/dist/runtime/query/auto-review/feedback.d.ts.map +1 -0
- package/dist/runtime/query/auto-review/feedback.js +45 -0
- package/dist/runtime/query/auto-review/feedback.js.map +1 -0
- package/dist/runtime/query/auto-review/git-status.d.ts +59 -0
- package/dist/runtime/query/auto-review/git-status.d.ts.map +1 -0
- package/dist/runtime/query/auto-review/git-status.js +379 -0
- package/dist/runtime/query/auto-review/git-status.js.map +1 -0
- package/dist/runtime/query/auto-review/index.d.ts +3 -3
- package/dist/runtime/query/auto-review/index.d.ts.map +1 -1
- package/dist/runtime/query/auto-review/index.js +2 -2
- package/dist/runtime/query/auto-review/index.js.map +1 -1
- package/dist/runtime/query/auto-review/prompt.d.ts.map +1 -1
- package/dist/runtime/query/auto-review/prompt.js +6 -1
- package/dist/runtime/query/auto-review/prompt.js.map +1 -1
- package/dist/runtime/query/auto-review/transcript.d.ts +14 -1
- package/dist/runtime/query/auto-review/transcript.d.ts.map +1 -1
- package/dist/runtime/query/auto-review/transcript.js +48 -2
- package/dist/runtime/query/auto-review/transcript.js.map +1 -1
- package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
- package/dist/runtime/query/executor/tool-call-admission.js +40 -3
- package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
- package/dist/runtime/query/executor.d.ts +32 -10
- package/dist/runtime/query/executor.d.ts.map +1 -1
- package/dist/runtime/query/executor.js +78 -17
- package/dist/runtime/query/executor.js.map +1 -1
- package/dist/runtime/query/index.d.ts +9 -0
- package/dist/runtime/query/index.d.ts.map +1 -1
- package/dist/runtime/query/index.js +54 -17
- package/dist/runtime/query/index.js.map +1 -1
- package/dist/runtime/query/iteration/index.d.ts.map +1 -1
- package/dist/runtime/query/iteration/index.js +17 -3
- package/dist/runtime/query/iteration/index.js.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.js +5 -2
- package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
- package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/context.js +5 -0
- package/dist/runtime/query/iteration/phases/context.js.map +1 -1
- package/dist/runtime/query/iteration/phases/per-call-review.d.ts +1 -2
- package/dist/runtime/query/iteration/phases/per-call-review.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/per-call-review.js +2 -5
- package/dist/runtime/query/iteration/phases/per-call-review.js.map +1 -1
- package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/tool-review.js +6 -1
- package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
- package/dist/runtime/query/pasted-frames.d.ts +34 -0
- package/dist/runtime/query/pasted-frames.d.ts.map +1 -0
- package/dist/runtime/query/pasted-frames.js +108 -0
- package/dist/runtime/query/pasted-frames.js.map +1 -0
- package/dist/runtime/query/path-escalation.d.ts +6 -0
- package/dist/runtime/query/path-escalation.d.ts.map +1 -1
- package/dist/runtime/query/path-escalation.js +15 -3
- package/dist/runtime/query/path-escalation.js.map +1 -1
- package/dist/runtime/query/request-interrupted-turns.d.ts +20 -0
- package/dist/runtime/query/request-interrupted-turns.d.ts.map +1 -0
- package/dist/runtime/query/request-interrupted-turns.js +43 -0
- package/dist/runtime/query/request-interrupted-turns.js.map +1 -0
- package/dist/runtime/query/review-policy.d.ts +16 -6
- package/dist/runtime/query/review-policy.d.ts.map +1 -1
- package/dist/runtime/query/review-policy.js +111 -15
- package/dist/runtime/query/review-policy.js.map +1 -1
- package/dist/runtime/query/turn/outcome-ledger.d.ts +9 -0
- package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -1
- package/dist/runtime/query/turn/outcome-ledger.js +94 -6
- package/dist/runtime/query/turn/outcome-ledger.js.map +1 -1
- package/dist/runtime/query/unanswered.d.ts +19 -0
- package/dist/runtime/query/unanswered.d.ts.map +1 -0
- package/dist/runtime/query/unanswered.js +25 -0
- package/dist/runtime/query/unanswered.js.map +1 -0
- package/dist/runtime/system-events.d.ts +4 -4
- package/dist/runtime/system-events.d.ts.map +1 -1
- package/dist/runtime/system-events.js +2 -0
- package/dist/runtime/system-events.js.map +1 -1
- package/dist/session/workspace/git-worktree.d.ts +8 -0
- package/dist/session/workspace/git-worktree.d.ts.map +1 -1
- package/dist/session/workspace/git-worktree.js +21 -3
- package/dist/session/workspace/git-worktree.js.map +1 -1
- package/dist/store/evidence/source-kind.d.ts +1 -1
- package/dist/store/evidence/source-kind.d.ts.map +1 -1
- package/dist/store/evidence/source-kind.js +1 -1
- package/dist/store/evidence/source-kind.js.map +1 -1
- package/dist/store/session-index/sqlite.d.ts.map +1 -1
- package/dist/store/session-index/sqlite.js +42 -3
- package/dist/store/session-index/sqlite.js.map +1 -1
- package/dist/store/session-log/disk.js +1 -1
- package/dist/store/session-log/disk.js.map +1 -1
- package/dist/store/session-log/lease.d.ts.map +1 -1
- package/dist/store/session-log/lease.js +3 -2
- package/dist/store/session-log/lease.js.map +1 -1
- package/dist/tools/admit-facts.d.ts.map +1 -1
- package/dist/tools/admit-facts.js +2 -0
- package/dist/tools/admit-facts.js.map +1 -1
- package/dist/tools/builtins/bash.d.ts +10 -2
- package/dist/tools/builtins/bash.d.ts.map +1 -1
- package/dist/tools/builtins/bash.js +56 -17
- package/dist/tools/builtins/bash.js.map +1 -1
- package/dist/tools/builtins/browser-local.d.ts +117 -0
- package/dist/tools/builtins/browser-local.d.ts.map +1 -0
- package/dist/tools/builtins/browser-local.js +437 -0
- package/dist/tools/builtins/browser-local.js.map +1 -0
- package/dist/tools/builtins/browser.d.ts +18 -1
- package/dist/tools/builtins/browser.d.ts.map +1 -1
- package/dist/tools/builtins/browser.js +84 -6
- package/dist/tools/builtins/browser.js.map +1 -1
- package/dist/tools/builtins/computer-use-window-id.d.ts +16 -0
- package/dist/tools/builtins/computer-use-window-id.d.ts.map +1 -0
- package/dist/tools/builtins/computer-use-window-id.js +52 -0
- package/dist/tools/builtins/computer-use-window-id.js.map +1 -0
- package/dist/tools/builtins/computer-use.d.ts +65 -7
- package/dist/tools/builtins/computer-use.d.ts.map +1 -1
- package/dist/tools/builtins/computer-use.js +384 -71
- package/dist/tools/builtins/computer-use.js.map +1 -1
- package/dist/tools/builtins/content-fingerprint.d.ts +6 -0
- package/dist/tools/builtins/content-fingerprint.d.ts.map +1 -1
- package/dist/tools/builtins/content-fingerprint.js +7 -1
- package/dist/tools/builtins/content-fingerprint.js.map +1 -1
- package/dist/tools/builtins/edit.d.ts.map +1 -1
- package/dist/tools/builtins/edit.js +89 -7
- package/dist/tools/builtins/edit.js.map +1 -1
- package/dist/tools/builtins/file-write-result.d.ts.map +1 -1
- package/dist/tools/builtins/file-write-result.js +2 -1
- package/dist/tools/builtins/file-write-result.js.map +1 -1
- package/dist/tools/builtins/grep.js +1 -1
- package/dist/tools/builtins/grep.js.map +1 -1
- package/dist/tools/builtins/job.d.ts.map +1 -1
- package/dist/tools/builtins/job.js +4 -2
- package/dist/tools/builtins/job.js.map +1 -1
- package/dist/tools/builtins/monitor.d.ts.map +1 -1
- package/dist/tools/builtins/monitor.js +6 -1
- package/dist/tools/builtins/monitor.js.map +1 -1
- package/dist/tools/builtins/search-tools.d.ts +12 -1
- package/dist/tools/builtins/search-tools.d.ts.map +1 -1
- package/dist/tools/builtins/search-tools.js +166 -20
- package/dist/tools/builtins/search-tools.js.map +1 -1
- package/dist/tools/builtins/shell-read-credit.d.ts +18 -6
- package/dist/tools/builtins/shell-read-credit.d.ts.map +1 -1
- package/dist/tools/builtins/shell-read-credit.js +95 -27
- package/dist/tools/builtins/shell-read-credit.js.map +1 -1
- package/dist/tools/builtins/wait-for-job.d.ts.map +1 -1
- package/dist/tools/builtins/wait-for-job.js +14 -3
- package/dist/tools/builtins/wait-for-job.js.map +1 -1
- package/dist/tools/builtins/web-guidance.d.ts +6 -0
- package/dist/tools/builtins/web-guidance.d.ts.map +1 -1
- package/dist/tools/builtins/web-guidance.js +6 -0
- package/dist/tools/builtins/web-guidance.js.map +1 -1
- package/dist/tools/builtins/web.d.ts.map +1 -1
- package/dist/tools/builtins/web.js +2 -1
- package/dist/tools/builtins/web.js.map +1 -1
- package/dist/tools/builtins/write-file.d.ts.map +1 -1
- package/dist/tools/builtins/write-file.js +32 -2
- package/dist/tools/builtins/write-file.js.map +1 -1
- package/dist/tools/command-shell.d.ts +1 -1
- package/dist/tools/command-shell.d.ts.map +1 -1
- package/dist/tools/command-shell.js +6 -8
- package/dist/tools/command-shell.js.map +1 -1
- package/dist/tools/defineTool.d.ts +2 -0
- package/dist/tools/defineTool.d.ts.map +1 -1
- package/dist/tools/defineTool.js +17 -1
- package/dist/tools/defineTool.js.map +1 -1
- package/dist/tools/schedules/index.d.ts +1 -0
- package/dist/tools/schedules/index.d.ts.map +1 -1
- package/dist/tools/schedules/index.js +1 -0
- package/dist/tools/schedules/index.js.map +1 -1
- package/dist/tools/schedules/loop-tool.d.ts.map +1 -1
- package/dist/tools/schedules/loop-tool.js +8 -6
- package/dist/tools/schedules/loop-tool.js.map +1 -1
- package/dist/tools/schedules/present.js +1 -1
- package/dist/tools/schedules/present.js.map +1 -1
- package/dist/tools/schedules/timer-tools.d.ts +36 -0
- package/dist/tools/schedules/timer-tools.d.ts.map +1 -0
- package/dist/tools/schedules/timer-tools.js +234 -0
- package/dist/tools/schedules/timer-tools.js.map +1 -0
- package/dist/tools/schedules/types.d.ts +68 -3
- package/dist/tools/schedules/types.d.ts.map +1 -1
- package/dist/tools/task/create.d.ts.map +1 -1
- package/dist/tools/task/create.js +2 -0
- package/dist/tools/task/create.js.map +1 -1
- package/dist/toolsets/manager.d.ts +49 -7
- package/dist/toolsets/manager.d.ts.map +1 -1
- package/dist/toolsets/manager.js +239 -40
- package/dist/toolsets/manager.js.map +1 -1
- package/dist/turn/evidence-query.d.ts +18 -1
- package/dist/turn/evidence-query.d.ts.map +1 -1
- package/dist/turn/evidence-query.js +177 -35
- package/dist/turn/evidence-query.js.map +1 -1
- package/dist/turn/evidence-recall.d.ts +8 -1
- package/dist/turn/evidence-recall.d.ts.map +1 -1
- package/dist/turn/evidence-recall.js +82 -22
- package/dist/turn/evidence-recall.js.map +1 -1
- package/dist/turn/history-shed.d.ts +15 -0
- package/dist/turn/history-shed.d.ts.map +1 -0
- package/dist/turn/history-shed.js +23 -0
- package/dist/turn/history-shed.js.map +1 -0
- package/dist/types/acp/index.d.ts +26 -0
- package/dist/types/acp/index.d.ts.map +1 -1
- package/dist/types/authorization/index.d.ts +9 -1
- package/dist/types/authorization/index.d.ts.map +1 -1
- package/dist/types/authorization/index.js +11 -2
- package/dist/types/authorization/index.js.map +1 -1
- package/dist/types/hitl/index.d.ts +10 -0
- package/dist/types/hitl/index.d.ts.map +1 -1
- package/dist/types/hitl/index.js.map +1 -1
- package/dist/types/message/index.d.ts +56 -1
- package/dist/types/message/index.d.ts.map +1 -1
- package/dist/types/message/index.js +2 -1
- package/dist/types/message/index.js.map +1 -1
- package/dist/types/permission/index.d.ts +14 -0
- package/dist/types/permission/index.d.ts.map +1 -1
- package/dist/types/permission/index.js +14 -0
- package/dist/types/permission/index.js.map +1 -1
- package/dist/types/plugin/index.d.ts +148 -1
- package/dist/types/plugin/index.d.ts.map +1 -1
- package/dist/types/plugin/index.js +9 -0
- package/dist/types/plugin/index.js.map +1 -1
- package/dist/types/provider/index.d.ts +1 -0
- package/dist/types/provider/index.d.ts.map +1 -1
- package/dist/types/provider/interface.d.ts +12 -0
- package/dist/types/provider/interface.d.ts.map +1 -1
- package/dist/types/provider/limits.d.ts +33 -0
- package/dist/types/provider/limits.d.ts.map +1 -0
- package/dist/types/provider/limits.js +7 -0
- package/dist/types/provider/limits.js.map +1 -0
- package/dist/types/tool/index.d.ts +30 -0
- package/dist/types/tool/index.d.ts.map +1 -1
- package/dist/types/tool/index.js.map +1 -1
- package/dist/types/tool/presentation.d.ts +4 -0
- package/dist/types/tool/presentation.d.ts.map +1 -1
- package/dist/utils/file-lock.d.ts +88 -0
- package/dist/utils/file-lock.d.ts.map +1 -0
- package/dist/utils/file-lock.js +281 -0
- package/dist/utils/file-lock.js.map +1 -0
- package/dist/utils/state-backup.d.ts +87 -0
- package/dist/utils/state-backup.d.ts.map +1 -0
- package/dist/utils/state-backup.js +272 -0
- package/dist/utils/state-backup.js.map +1 -0
- package/dist/utils/temp-sweep.d.ts +66 -0
- package/dist/utils/temp-sweep.d.ts.map +1 -0
- package/dist/utils/temp-sweep.js +311 -0
- package/dist/utils/temp-sweep.js.map +1 -0
- package/dist/utils/temp.d.ts +14 -0
- package/dist/utils/temp.d.ts.map +1 -1
- package/dist/utils/temp.js +70 -2
- package/dist/utils/temp.js.map +1 -1
- package/package.json +1 -1
- package/src/account/lock.ts +13 -133
- package/src/account/registry.ts +75 -21
- package/src/account/types.ts +8 -9
- package/src/authorization/dangerous-commands.ts +542 -0
- package/src/authorization/gate.ts +19 -5
- package/src/authorization/protected-paths.ts +13 -8
- package/src/authorization/readonly-commands.ts +35 -1
- package/src/authorization/removal.ts +7 -7
- package/src/authorization/rules.ts +75 -15
- package/src/authorization/shell-lexer.ts +19 -0
- package/src/bridge/acp/permission.ts +2 -0
- package/src/bridge/acp/server.ts +66 -6
- package/src/compaction/context-breakdown.ts +53 -11
- package/src/compaction/dangling.ts +2 -0
- package/src/compaction/extractor.ts +9 -1
- package/src/compaction/index.ts +1 -0
- package/src/compaction/managers/structured.ts +2 -2
- package/src/compaction/manual.ts +11 -3
- package/src/compaction/model-summary.ts +8 -1
- package/src/compaction/summary.ts +54 -7
- package/src/constants/tools/index.ts +30 -16
- package/src/manager/session/turn-recorder.ts +37 -1
- package/src/network/audit.ts +113 -0
- package/src/network/clock.ts +62 -0
- package/src/network/discovery-mdns.ts +485 -0
- package/src/network/discovery.ts +210 -0
- package/src/network/fingerprint.ts +241 -0
- package/src/network/identity.ts +98 -0
- package/src/network/index.ts +134 -0
- package/src/network/join.ts +177 -0
- package/src/network/mail-policy.ts +199 -0
- package/src/network/membership.ts +290 -0
- package/src/network/roster.ts +165 -0
- package/src/network/service.ts +2304 -0
- package/src/network/store.ts +261 -0
- package/src/network/transport.ts +445 -0
- package/src/network/wire.ts +250 -0
- package/src/network/x509.ts +114 -0
- package/src/pals/activity/causality.ts +16 -2
- package/src/peers/endpoint.ts +6 -0
- package/src/peers/envelope.ts +82 -5
- package/src/peers/index.ts +10 -2
- package/src/peers/mode-word.ts +18 -0
- package/src/peers/protocol.ts +24 -1
- package/src/peers/record.ts +5 -0
- package/src/plugin/session-hook-env.ts +25 -2
- package/src/plugin/shell-hook.ts +208 -14
- package/src/prompt/coding-agent-doctrine.ts +33 -38
- package/src/public-runtime.ts +107 -1
- package/src/public-tools.ts +11 -0
- package/src/public-types.ts +67 -1
- package/src/runtime/jobs/registry.ts +93 -3
- package/src/runtime/query/auto-review/classifier.ts +76 -14
- package/src/runtime/query/auto-review/feedback.ts +50 -0
- package/src/runtime/query/auto-review/git-status.ts +437 -0
- package/src/runtime/query/auto-review/index.ts +7 -2
- package/src/runtime/query/auto-review/prompt.ts +6 -1
- package/src/runtime/query/auto-review/transcript.ts +67 -4
- package/src/runtime/query/executor/tool-call-admission.ts +49 -3
- package/src/runtime/query/executor.ts +104 -21
- package/src/runtime/query/index.ts +66 -17
- package/src/runtime/query/iteration/index.ts +24 -3
- package/src/runtime/query/iteration/phases/compaction.ts +4 -0
- package/src/runtime/query/iteration/phases/context.ts +5 -0
- package/src/runtime/query/iteration/phases/per-call-review.ts +8 -13
- package/src/runtime/query/iteration/phases/tool-review.ts +7 -1
- package/src/runtime/query/pasted-frames.ts +119 -0
- package/src/runtime/query/path-escalation.ts +27 -3
- package/src/runtime/query/request-interrupted-turns.ts +47 -0
- package/src/runtime/query/review-policy.ts +125 -22
- package/src/runtime/query/turn/outcome-ledger.ts +99 -6
- package/src/runtime/query/unanswered.ts +35 -0
- package/src/runtime/system-events.ts +2 -0
- package/src/session/workspace/git-worktree.ts +34 -3
- package/src/store/evidence/source-kind.ts +1 -1
- package/src/store/session-index/sqlite.ts +40 -3
- package/src/store/session-log/disk.ts +1 -1
- package/src/store/session-log/lease.ts +3 -2
- package/src/tools/admit-facts.ts +2 -0
- package/src/tools/builtins/bash.ts +62 -19
- package/src/tools/builtins/browser-local.ts +504 -0
- package/src/tools/builtins/browser.ts +108 -6
- package/src/tools/builtins/computer-use-window-id.ts +50 -0
- package/src/tools/builtins/computer-use.ts +460 -68
- package/src/tools/builtins/content-fingerprint.ts +8 -1
- package/src/tools/builtins/edit.ts +93 -7
- package/src/tools/builtins/file-write-result.ts +2 -1
- package/src/tools/builtins/grep.ts +1 -1
- package/src/tools/builtins/job.ts +4 -2
- package/src/tools/builtins/monitor.ts +6 -1
- package/src/tools/builtins/search-tools.ts +196 -21
- package/src/tools/builtins/shell-read-credit.ts +97 -33
- package/src/tools/builtins/wait-for-job.ts +13 -3
- package/src/tools/builtins/web-guidance.ts +6 -0
- package/src/tools/builtins/web.ts +2 -1
- package/src/tools/builtins/write-file.ts +31 -3
- package/src/tools/command-shell.ts +6 -8
- package/src/tools/defineTool.ts +20 -1
- package/src/tools/schedules/index.ts +11 -0
- package/src/tools/schedules/loop-tool.ts +10 -6
- package/src/tools/schedules/present.ts +1 -1
- package/src/tools/schedules/timer-tools.ts +258 -0
- package/src/tools/schedules/types.ts +72 -3
- package/src/tools/task/create.ts +2 -0
- package/src/toolsets/manager.ts +262 -46
- package/src/turn/evidence-query.ts +183 -42
- package/src/turn/evidence-recall.ts +96 -19
- package/src/turn/history-shed.ts +30 -0
- package/src/types/acp/index.ts +24 -0
- package/src/types/authorization/index.ts +20 -3
- package/src/types/hitl/index.ts +10 -0
- package/src/types/message/index.ts +65 -0
- package/src/types/permission/index.ts +18 -0
- package/src/types/plugin/index.ts +205 -26
- package/src/types/provider/index.ts +1 -0
- package/src/types/provider/interface.ts +13 -0
- package/src/types/provider/limits.ts +35 -0
- package/src/types/tool/index.ts +30 -2
- package/src/types/tool/presentation.ts +4 -0
- package/src/utils/file-lock.ts +328 -0
- package/src/utils/state-backup.ts +318 -0
- package/src/utils/temp-sweep.ts +327 -0
- package/src/utils/temp.ts +73 -2
|
@@ -0,0 +1,2304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Namzu network service: one object per machine that owns its identity,
|
|
3
|
+
* membership, listener, discovery, roster, roles and cross-machine mail.
|
|
4
|
+
*
|
|
5
|
+
* Host-neutral. A host (the terminal today, the desktop later) supplies a
|
|
6
|
+
* `NetworkHost` for what only it knows: its live sessions, how to hand a
|
|
7
|
+
* message to one of them, how to set a role. The service never prints, never
|
|
8
|
+
* reads a process-wide setting and never touches a clock or timer except
|
|
9
|
+
* through the injected `NetworkClock`.
|
|
10
|
+
*
|
|
11
|
+
* Safety properties kept here (tests name each):
|
|
12
|
+
* - a machine joins only after one Allow by an existing member;
|
|
13
|
+
* - a non-member can do nothing but ask to join;
|
|
14
|
+
* - a role is descriptive: no code path in this file changes a permission mode;
|
|
15
|
+
* - mail from another machine is held, not accepted, when its mode differs,
|
|
16
|
+
* when the receiver is in bypass, or when the sender's mode cannot be
|
|
17
|
+
* confirmed; held mail expires and the sender is told.
|
|
18
|
+
*
|
|
19
|
+
* @experimental
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { execFile } from 'node:child_process'
|
|
23
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
24
|
+
import { readFile } from 'node:fs/promises'
|
|
25
|
+
import { networkInterfaces, hostname as osHostname, platform as osPlatform } from 'node:os'
|
|
26
|
+
import { z } from 'zod'
|
|
27
|
+
import { type AuditEntry, type AuditSink, createFileAuditSink, textHash } from './audit.js'
|
|
28
|
+
import { type NetworkClock, systemClock } from './clock.js'
|
|
29
|
+
import {
|
|
30
|
+
type DiscoveredEndpoint,
|
|
31
|
+
type ListenAddress,
|
|
32
|
+
type NetworkDiscovery,
|
|
33
|
+
isPrivateNetworkAddress,
|
|
34
|
+
privateInterfaces,
|
|
35
|
+
} from './discovery.js'
|
|
36
|
+
import { createNetworkIdentity, createSystemGatewayReader } from './fingerprint.js'
|
|
37
|
+
import { type MachineKey, generateMachineKey, machineIdOf, shortMachineId } from './identity.js'
|
|
38
|
+
import { JoinTable, type PendingJoin, formatJoinCode, joinCode } from './join.js'
|
|
39
|
+
import {
|
|
40
|
+
HoldQueue,
|
|
41
|
+
type MailSetting,
|
|
42
|
+
SlidingCounter,
|
|
43
|
+
TokenBuckets,
|
|
44
|
+
decideMail,
|
|
45
|
+
} from './mail-policy.js'
|
|
46
|
+
import {
|
|
47
|
+
type Admission,
|
|
48
|
+
AdmissionSchema,
|
|
49
|
+
type MembershipView,
|
|
50
|
+
RevocationSchema,
|
|
51
|
+
admittedBy,
|
|
52
|
+
createFounding,
|
|
53
|
+
evaluateMembership,
|
|
54
|
+
mergeMembership,
|
|
55
|
+
signAdmission,
|
|
56
|
+
signRevocation,
|
|
57
|
+
} from './membership.js'
|
|
58
|
+
import {
|
|
59
|
+
type LocalSession,
|
|
60
|
+
type RosterMachineView,
|
|
61
|
+
type RosterView,
|
|
62
|
+
offlineSessions,
|
|
63
|
+
resolveSessionTarget,
|
|
64
|
+
} from './roster.js'
|
|
65
|
+
import { type MachineFile, type NetworkStore, type PeersFile, createNetworkStore } from './store.js'
|
|
66
|
+
import {
|
|
67
|
+
type NetClient,
|
|
68
|
+
type NetListener,
|
|
69
|
+
NetworkError,
|
|
70
|
+
type PeerInfo,
|
|
71
|
+
type ServerContext,
|
|
72
|
+
type TlsIdentity,
|
|
73
|
+
createNetListener,
|
|
74
|
+
dialNet,
|
|
75
|
+
} from './transport.js'
|
|
76
|
+
import {
|
|
77
|
+
type HostPort,
|
|
78
|
+
MAX_HOPS,
|
|
79
|
+
MAX_MEMBERS,
|
|
80
|
+
MAX_NAME_LENGTH,
|
|
81
|
+
MAX_NET_TEXT_BYTES,
|
|
82
|
+
NET_PROTOCOL,
|
|
83
|
+
type NetDeliverRequest,
|
|
84
|
+
type NetNoticeRequest,
|
|
85
|
+
type NetOutcome,
|
|
86
|
+
type NetRequest,
|
|
87
|
+
type RoleSetRequest,
|
|
88
|
+
type Roster,
|
|
89
|
+
RosterSchema,
|
|
90
|
+
type RosterSession,
|
|
91
|
+
sanitizeName,
|
|
92
|
+
sanitizeRole,
|
|
93
|
+
} from './wire.js'
|
|
94
|
+
import { buildMachineCertificate } from './x509.js'
|
|
95
|
+
|
|
96
|
+
export const DEFAULT_LISTEN_PORT = 47_310
|
|
97
|
+
export const BROWSE_WINDOW_MS = 5_000
|
|
98
|
+
/**
|
|
99
|
+
* A network with one machine in it that was founded less than this long ago is "fresh": if a second fresh
|
|
100
|
+
* one is heard nearby (two machines started together and each founded one), the younger asks to join the older.
|
|
101
|
+
*/
|
|
102
|
+
export const FRESH_NETWORK_MS = 60_000
|
|
103
|
+
export const INTERFACE_RECHECK_MS = 30_000
|
|
104
|
+
export const ROSTER_FRESH_MS = 15_000
|
|
105
|
+
const MAX_NEARBY_NETWORKS = 8
|
|
106
|
+
|
|
107
|
+
/** A message from a session on another machine, as the host receives it. */
|
|
108
|
+
export interface RemoteMail {
|
|
109
|
+
readonly id: string
|
|
110
|
+
readonly from: {
|
|
111
|
+
readonly machineId: string
|
|
112
|
+
readonly machineName: string
|
|
113
|
+
readonly sessionRef: string
|
|
114
|
+
readonly sessionName: string
|
|
115
|
+
readonly mode: string
|
|
116
|
+
}
|
|
117
|
+
readonly text: string
|
|
118
|
+
readonly inReplyTo?: string
|
|
119
|
+
readonly hops: number
|
|
120
|
+
/** True when the person allowed this held message once: the host re-checks nothing but a later mode change. */
|
|
121
|
+
readonly allowedOnce: boolean
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface NetworkHost {
|
|
125
|
+
listLocalSessions(): readonly LocalSession[]
|
|
126
|
+
/** Hand a message to a local session. `refused` when the session is gone or declines. */
|
|
127
|
+
deliverLocal(
|
|
128
|
+
sessionRef: string,
|
|
129
|
+
mail: RemoteMail,
|
|
130
|
+
): Promise<{ readonly status: 'queued' | 'refused'; readonly reason?: string }>
|
|
131
|
+
/** Record a role on a local session; false when there is no such session. Never touches permissions. */
|
|
132
|
+
setLocalRole?(
|
|
133
|
+
sessionRef: string,
|
|
134
|
+
role: string | null,
|
|
135
|
+
info: { readonly by: string; readonly at: number },
|
|
136
|
+
): boolean
|
|
137
|
+
report?(text: string): void
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export type NetworkState = 'off' | 'starting' | 'searching' | 'ready' | 'ambiguous' | 'removed'
|
|
141
|
+
|
|
142
|
+
export interface HeldMail {
|
|
143
|
+
readonly id: string
|
|
144
|
+
readonly machineId: string
|
|
145
|
+
readonly machineName: string
|
|
146
|
+
readonly fromSessionRef: string
|
|
147
|
+
readonly fromSessionName: string
|
|
148
|
+
readonly fromMode: string
|
|
149
|
+
readonly toSessionRef: string
|
|
150
|
+
readonly text: string
|
|
151
|
+
readonly inReplyTo?: string
|
|
152
|
+
readonly hops: number
|
|
153
|
+
readonly reason: string
|
|
154
|
+
readonly heldAt: number
|
|
155
|
+
readonly expiresAt: number
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export type NetworkEvent =
|
|
159
|
+
| { readonly type: 'state'; readonly state: NetworkState; readonly reason?: string }
|
|
160
|
+
| { readonly type: 'founded'; readonly netId: string }
|
|
161
|
+
| {
|
|
162
|
+
readonly type: 'join-waiting'
|
|
163
|
+
readonly code: string
|
|
164
|
+
readonly shownCode: string
|
|
165
|
+
readonly endpoint: HostPort
|
|
166
|
+
}
|
|
167
|
+
| { readonly type: 'joined'; readonly netId: string; readonly members: number }
|
|
168
|
+
| {
|
|
169
|
+
readonly type: 'join-ended'
|
|
170
|
+
readonly result: 'denied' | 'expired' | 'refused' | 'cancelled'
|
|
171
|
+
readonly reason?: string
|
|
172
|
+
}
|
|
173
|
+
| { readonly type: 'join-request'; readonly request: PendingJoin }
|
|
174
|
+
| {
|
|
175
|
+
/** A join was admitted without asking, on a trusted network or because `network.autoAdmit` is `always`. */
|
|
176
|
+
readonly type: 'join-auto'
|
|
177
|
+
readonly requestId: string
|
|
178
|
+
readonly name: string
|
|
179
|
+
readonly machineId: string
|
|
180
|
+
readonly mode: 'trusted-network' | 'always'
|
|
181
|
+
/** The name of the trusted network, when that is why. */
|
|
182
|
+
readonly network?: string
|
|
183
|
+
readonly at: number
|
|
184
|
+
}
|
|
185
|
+
| {
|
|
186
|
+
readonly type: 'join-settled'
|
|
187
|
+
readonly requestId: string
|
|
188
|
+
readonly result: 'allow' | 'deny' | 'expired'
|
|
189
|
+
}
|
|
190
|
+
| { readonly type: 'member-added'; readonly machineId: string; readonly name?: string }
|
|
191
|
+
| { readonly type: 'member-removed'; readonly machineId: string; readonly name?: string }
|
|
192
|
+
| { readonly type: 'removed-self' }
|
|
193
|
+
| { readonly type: 'nearby'; readonly networks: readonly string[] }
|
|
194
|
+
| { readonly type: 'held'; readonly mail: HeldMail }
|
|
195
|
+
| {
|
|
196
|
+
readonly type: 'held-resolved'
|
|
197
|
+
readonly id: string
|
|
198
|
+
readonly result: 'allowed' | 'denied' | 'expired'
|
|
199
|
+
}
|
|
200
|
+
| {
|
|
201
|
+
readonly type: 'mail-outcome'
|
|
202
|
+
readonly id: string
|
|
203
|
+
readonly outcome: NetOutcome
|
|
204
|
+
readonly machineId: string
|
|
205
|
+
readonly detail?: string
|
|
206
|
+
}
|
|
207
|
+
| {
|
|
208
|
+
readonly type: 'role'
|
|
209
|
+
readonly target: 'machine' | string
|
|
210
|
+
readonly role: string | null
|
|
211
|
+
readonly byMachine: string
|
|
212
|
+
readonly at: number
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface NetworkStatus {
|
|
216
|
+
readonly state: NetworkState
|
|
217
|
+
readonly reason?: string
|
|
218
|
+
readonly machine:
|
|
219
|
+
| { readonly id: string; readonly name: string; readonly role?: string }
|
|
220
|
+
| undefined
|
|
221
|
+
readonly netId: string | undefined
|
|
222
|
+
readonly members: number
|
|
223
|
+
readonly port: number | undefined
|
|
224
|
+
readonly pendingJoins: number
|
|
225
|
+
readonly held: number
|
|
226
|
+
readonly nearbyNetworks: number
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export interface NetworkServiceOptions {
|
|
230
|
+
/** The Namzu home (`~/.namzu`); the service keeps its files in `<home>/network`. */
|
|
231
|
+
readonly home: string
|
|
232
|
+
readonly host: NetworkHost
|
|
233
|
+
/** True only in a terminal with a person at it. A service constructed with false refuses to start unless `allowUnattended`. */
|
|
234
|
+
readonly interactive: boolean
|
|
235
|
+
readonly allowUnattended?: boolean
|
|
236
|
+
readonly discovery: NetworkDiscovery
|
|
237
|
+
readonly clock?: NetworkClock
|
|
238
|
+
readonly interfaces?: () => NodeJS.Dict<import('node:os').NetworkInterfaceInfo[]>
|
|
239
|
+
/** Tests only: 127.0.0.1 counts as a private interface. */
|
|
240
|
+
readonly allowLoopback?: boolean
|
|
241
|
+
/** The person said `network.enabled: true`: listen on non-private addresses too. */
|
|
242
|
+
readonly anyNetwork?: boolean
|
|
243
|
+
/** The port to listen on; 0 = ephemeral and not remembered. Defaults to the remembered one, then 47310, then ephemeral. */
|
|
244
|
+
readonly listenPort?: number
|
|
245
|
+
readonly hostname?: string
|
|
246
|
+
readonly machineName?: string
|
|
247
|
+
readonly acceptMail?: () => MailSetting
|
|
248
|
+
/**
|
|
249
|
+
* Whether a join request is admitted without an Allow: on a trusted network (default), on any private
|
|
250
|
+
* network, or never. Read at each request.
|
|
251
|
+
*/
|
|
252
|
+
readonly autoAdmit?: () => AutoAdmitSetting
|
|
253
|
+
/** Which local network an address is on (see `fingerprint.ts`); undefined when unknown. Tests inject one. */
|
|
254
|
+
readonly networkIdentity?: (address: string) => Promise<string | undefined>
|
|
255
|
+
readonly audit?: AuditSink
|
|
256
|
+
readonly store?: NetworkStore
|
|
257
|
+
readonly browseMs?: number
|
|
258
|
+
readonly platform?: string
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export type AutoAdmitSetting = 'trusted-networks' | 'always' | 'never'
|
|
262
|
+
|
|
263
|
+
/** A local network as the person sees it. */
|
|
264
|
+
export interface NetworkRef {
|
|
265
|
+
readonly id: string
|
|
266
|
+
/** The name it is trusted under, when it is trusted. */
|
|
267
|
+
readonly trusted?: string
|
|
268
|
+
/** A short default name to offer when the person trusts it. */
|
|
269
|
+
readonly suggestedName: string
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export interface TrustedNetwork {
|
|
273
|
+
readonly id: string
|
|
274
|
+
readonly name: string
|
|
275
|
+
readonly trustedAt: number
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Strip the IPv4-in-IPv6 prefix a socket may report. */
|
|
279
|
+
const plainAddress = (address: string) => address.replace(/^::ffff:/i, '')
|
|
280
|
+
|
|
281
|
+
interface PeerState {
|
|
282
|
+
name: string
|
|
283
|
+
addresses: HostPort[]
|
|
284
|
+
role?: string
|
|
285
|
+
sessions?: readonly RosterSession[]
|
|
286
|
+
rosterAt?: number
|
|
287
|
+
seenAt?: number
|
|
288
|
+
online: boolean
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const PeerEntrySchema = z
|
|
292
|
+
.object({
|
|
293
|
+
machineId: z.string().length(64),
|
|
294
|
+
name: z.string(),
|
|
295
|
+
addresses: z.array(z.object({ host: z.string(), port: z.number().int() }).strict()).max(8),
|
|
296
|
+
})
|
|
297
|
+
.strict()
|
|
298
|
+
const AdmittedFrameSchema = z
|
|
299
|
+
.object({
|
|
300
|
+
status: z.literal('admitted'),
|
|
301
|
+
netId: z.string().length(16).optional(),
|
|
302
|
+
admissions: z.array(AdmissionSchema).max(MAX_MEMBERS * 2),
|
|
303
|
+
revocations: z.array(RevocationSchema).max(MAX_MEMBERS * 2),
|
|
304
|
+
peers: z.array(PeerEntrySchema).max(MAX_MEMBERS),
|
|
305
|
+
})
|
|
306
|
+
.strict()
|
|
307
|
+
const PendingFrameSchema = z
|
|
308
|
+
.object({ status: z.literal('pending'), nonce: z.string(), netId: z.string().length(16) })
|
|
309
|
+
.strict()
|
|
310
|
+
const EndFrameSchema = z
|
|
311
|
+
.object({ status: z.enum(['denied', 'expired', 'refused']), reason: z.string().optional() })
|
|
312
|
+
.strict()
|
|
313
|
+
const HelloReplySchema = z
|
|
314
|
+
.object({
|
|
315
|
+
machineName: z.string(),
|
|
316
|
+
addresses: z.array(z.object({ host: z.string(), port: z.number().int() }).strict()).max(8),
|
|
317
|
+
})
|
|
318
|
+
.strict()
|
|
319
|
+
const SyncReplySchema = z
|
|
320
|
+
.object({ admissions: z.array(AdmissionSchema), revocations: z.array(RevocationSchema) })
|
|
321
|
+
.strict()
|
|
322
|
+
/** Words from another machine that reach a screen or a model: no control characters, one line, short. */
|
|
323
|
+
function cleanReason(value: string | undefined): string | undefined {
|
|
324
|
+
return value === undefined ? undefined : sanitizeName(value, 200)
|
|
325
|
+
}
|
|
326
|
+
const DeliverReplyParse = z
|
|
327
|
+
.object({
|
|
328
|
+
status: z.enum(['queued', 'held', 'refused']),
|
|
329
|
+
reason: z.string().optional().transform(cleanReason),
|
|
330
|
+
})
|
|
331
|
+
.strict()
|
|
332
|
+
const StatusReplySchema = z
|
|
333
|
+
.object({
|
|
334
|
+
status: z.enum(['applied', 'refused']),
|
|
335
|
+
reason: z.string().optional().transform(cleanReason),
|
|
336
|
+
})
|
|
337
|
+
.strict()
|
|
338
|
+
|
|
339
|
+
export interface NetworkService {
|
|
340
|
+
start(): Promise<void>
|
|
341
|
+
status(): NetworkStatus
|
|
342
|
+
identity(): { readonly machineId: string; readonly name: string } | undefined
|
|
343
|
+
on(listener: (event: NetworkEvent) => void): () => void
|
|
344
|
+
/** The roster: this machine first, then every member. Pulls fresh rosters unless `refresh` is false. */
|
|
345
|
+
roster(options?: { readonly refresh?: boolean }): Promise<RosterView>
|
|
346
|
+
members(): readonly {
|
|
347
|
+
readonly machineId: string
|
|
348
|
+
readonly name: string
|
|
349
|
+
readonly self: boolean
|
|
350
|
+
}[]
|
|
351
|
+
pendingJoins(): readonly PendingJoin[]
|
|
352
|
+
/**
|
|
353
|
+
* Admit a joiner. `trust` also marks the local network the request came from as trusted (a string names it);
|
|
354
|
+
* it throws, before admitting anything, when that network cannot be recognised.
|
|
355
|
+
*/
|
|
356
|
+
allow(query: string, options?: { readonly trust?: boolean | string }): Promise<PendingJoin>
|
|
357
|
+
/** Which local network `address` is on, and whether it is trusted; undefined when it cannot be recognised. */
|
|
358
|
+
networkOf(address: string): Promise<NetworkRef | undefined>
|
|
359
|
+
trustedNetworks(): Promise<readonly TrustedNetwork[]>
|
|
360
|
+
/** Mark the network `address` is on as trusted, or rename it when it already is. Returns the name. */
|
|
361
|
+
trustNetwork(address: string, name?: string): Promise<TrustedNetwork>
|
|
362
|
+
/** Stop trusting a network by name or id prefix. */
|
|
363
|
+
untrustNetwork(query: string): Promise<TrustedNetwork>
|
|
364
|
+
/** Give a trusted network another name. */
|
|
365
|
+
renameNetwork(query: string, name: string): Promise<TrustedNetwork>
|
|
366
|
+
deny(query: string): Promise<PendingJoin>
|
|
367
|
+
remove(
|
|
368
|
+
machineId: string,
|
|
369
|
+
options?: { readonly cascade?: boolean },
|
|
370
|
+
): Promise<{ readonly removed: readonly string[] }>
|
|
371
|
+
/** Who `machineId` admitted that is still a member: what a cascade would also remove. */
|
|
372
|
+
admittedBy(machineId: string): readonly string[]
|
|
373
|
+
rename(name: string): Promise<void>
|
|
374
|
+
setRole(
|
|
375
|
+
target: { readonly machineId: string; readonly sessionRef?: string },
|
|
376
|
+
role: string | null,
|
|
377
|
+
): Promise<{ readonly status: 'applied' | 'refused'; readonly reason?: string }>
|
|
378
|
+
send(
|
|
379
|
+
target: { readonly machineId: string; readonly sessionRef: string },
|
|
380
|
+
text: string,
|
|
381
|
+
from: { readonly sessionRef: string; readonly sessionName: string; readonly mode: string },
|
|
382
|
+
options?: { readonly inReplyTo?: string; readonly hops?: number },
|
|
383
|
+
): Promise<{
|
|
384
|
+
readonly id: string
|
|
385
|
+
readonly status: 'queued' | 'held' | 'refused'
|
|
386
|
+
readonly reason?: string
|
|
387
|
+
}>
|
|
388
|
+
/** Resolve what a person typed (`name`, `machine/name`, `[ref]`) against the last roster. */
|
|
389
|
+
resolve(text: string): ReturnType<typeof resolveSessionTarget>
|
|
390
|
+
/** Add an address by hand (`namzu peers add`): joins when this machine has no network, remembers the address otherwise. */
|
|
391
|
+
add(hostPort: string): Promise<'join-requested' | 'added'>
|
|
392
|
+
/** Ask a nearby network to let this machine in. Resolves when the request is decided. */
|
|
393
|
+
join(endpoint: HostPort): Promise<'joined' | 'denied' | 'expired' | 'refused' | 'cancelled'>
|
|
394
|
+
/** Withdraw the join request this machine is waiting on. False when none is waiting. */
|
|
395
|
+
cancelJoin(): boolean
|
|
396
|
+
/** The networks heard nearby while this machine has none of its own (or only a fresh one): one address each. */
|
|
397
|
+
nearbyNetworks(): readonly {
|
|
398
|
+
readonly netId: string
|
|
399
|
+
readonly host: string
|
|
400
|
+
readonly port: number
|
|
401
|
+
}[]
|
|
402
|
+
held(): readonly HeldMail[]
|
|
403
|
+
allowHeld(id: string): Promise<void>
|
|
404
|
+
denyHeld(id: string): Promise<void>
|
|
405
|
+
/** The host took held-then-allowed or accepted mail into a turn: tell the sender. */
|
|
406
|
+
reportDelivered(machineId: string, mailId: string, fromSessionRef: string): Promise<void>
|
|
407
|
+
close(): Promise<void>
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export function parseHostPort(text: string, defaultPort = DEFAULT_LISTEN_PORT): HostPort {
|
|
411
|
+
const trimmed = text.trim()
|
|
412
|
+
const v6 = /^\[([^\]]+)\](?::(\d+))?$/.exec(trimmed)
|
|
413
|
+
let host: string
|
|
414
|
+
let portText: string | undefined
|
|
415
|
+
if (v6) {
|
|
416
|
+
host = v6[1] as string
|
|
417
|
+
portText = v6[2]
|
|
418
|
+
} else {
|
|
419
|
+
const idx = trimmed.lastIndexOf(':')
|
|
420
|
+
if (idx > 0 && trimmed.indexOf(':') === idx) {
|
|
421
|
+
host = trimmed.slice(0, idx)
|
|
422
|
+
portText = trimmed.slice(idx + 1)
|
|
423
|
+
} else {
|
|
424
|
+
host = trimmed
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const port = portText === undefined ? defaultPort : Number(portText)
|
|
428
|
+
if (
|
|
429
|
+
!host ||
|
|
430
|
+
!/^[A-Za-z0-9.:_%-]+$/.test(host) ||
|
|
431
|
+
!Number.isInteger(port) ||
|
|
432
|
+
port < 1 ||
|
|
433
|
+
port > 65535
|
|
434
|
+
) {
|
|
435
|
+
throw new NetworkError('invalid', 'That is not a valid address. Use host or host:port.')
|
|
436
|
+
}
|
|
437
|
+
return { host, port }
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const same = (a: HostPort, b: HostPort) => a.host === b.host && a.port === b.port
|
|
441
|
+
|
|
442
|
+
export function createNamzuNetwork(options: NetworkServiceOptions): NetworkService {
|
|
443
|
+
if (!options.interactive && !options.allowUnattended) {
|
|
444
|
+
throw new NetworkError(
|
|
445
|
+
'unattended',
|
|
446
|
+
'The Namzu network runs only in a terminal with a person at it.',
|
|
447
|
+
)
|
|
448
|
+
}
|
|
449
|
+
const clock = options.clock ?? systemClock
|
|
450
|
+
const store = options.store ?? createNetworkStore({ home: options.home })
|
|
451
|
+
const audit: AuditSink =
|
|
452
|
+
options.audit ??
|
|
453
|
+
createFileAuditSink({ dir: store.dir, report: (m) => options.host.report?.(m) })
|
|
454
|
+
const discovery = options.discovery
|
|
455
|
+
const host = options.host
|
|
456
|
+
const platform = options.platform ?? osPlatform()
|
|
457
|
+
const listeners = new Set<(event: NetworkEvent) => void>()
|
|
458
|
+
|
|
459
|
+
let state: NetworkState = 'off'
|
|
460
|
+
let stateReason: string | undefined
|
|
461
|
+
let key: MachineKey | undefined
|
|
462
|
+
let tls: TlsIdentity | undefined
|
|
463
|
+
let machine: MachineFile | undefined
|
|
464
|
+
let netId: string | undefined
|
|
465
|
+
let adm: Admission[] = []
|
|
466
|
+
let rev: import('./membership.js').Revocation[] = []
|
|
467
|
+
let view: MembershipView | undefined
|
|
468
|
+
let membersRev = 0
|
|
469
|
+
let port: number | undefined
|
|
470
|
+
let addresses: ListenAddress[] = []
|
|
471
|
+
let started = false
|
|
472
|
+
let closed = false
|
|
473
|
+
const netListeners: NetListener[] = []
|
|
474
|
+
const peerState = new Map<string, PeerState>()
|
|
475
|
+
const nearby = new Map<string, DiscoveredEndpoint[]>()
|
|
476
|
+
const pendingConns = new Map<string, ServerContext>()
|
|
477
|
+
const sent = new Map<
|
|
478
|
+
string,
|
|
479
|
+
{ machineId: string; at: number; session: string; bytes: number; textHash: string }
|
|
480
|
+
>()
|
|
481
|
+
const seenMail: string[] = []
|
|
482
|
+
const inFlight = new Set<string>()
|
|
483
|
+
const offDiscovery: Array<() => void> = []
|
|
484
|
+
let cancelBrowse: (() => void) | undefined
|
|
485
|
+
let cancelRecheck: (() => void) | undefined
|
|
486
|
+
let joining = false
|
|
487
|
+
let joinClient: NetClient | undefined
|
|
488
|
+
let joinCancelled = false
|
|
489
|
+
let foundedAt: number | undefined
|
|
490
|
+
const declinedNets = new Set<string>()
|
|
491
|
+
const probing = new Set<string>()
|
|
492
|
+
|
|
493
|
+
const emit = (event: NetworkEvent) => {
|
|
494
|
+
for (const l of [...listeners]) {
|
|
495
|
+
try {
|
|
496
|
+
l(event)
|
|
497
|
+
} catch {
|
|
498
|
+
// a listener must not break the service
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
const setState = (next: NetworkState, reason?: string) => {
|
|
503
|
+
if (state === next && stateReason === reason) return
|
|
504
|
+
state = next
|
|
505
|
+
stateReason = reason
|
|
506
|
+
emit({ type: 'state', state, reason })
|
|
507
|
+
}
|
|
508
|
+
const logAudit = (entry: Omit<AuditEntry, 'at'>) => {
|
|
509
|
+
void audit.append({ at: clock.now(), ...entry })
|
|
510
|
+
}
|
|
511
|
+
const who = (machineId: string) => ({
|
|
512
|
+
id12: shortMachineId(machineId),
|
|
513
|
+
name: peerState.get(machineId)?.name,
|
|
514
|
+
})
|
|
515
|
+
|
|
516
|
+
const identify =
|
|
517
|
+
options.networkIdentity ??
|
|
518
|
+
createNetworkIdentity({
|
|
519
|
+
interfaces: options.interfaces ?? networkInterfaces,
|
|
520
|
+
clock,
|
|
521
|
+
gateway: createSystemGatewayReader({
|
|
522
|
+
platform: osPlatform(),
|
|
523
|
+
readText: (path) => readFile(path, 'utf8').catch(() => undefined),
|
|
524
|
+
run: (command, args) =>
|
|
525
|
+
new Promise((resolve) => {
|
|
526
|
+
execFile(
|
|
527
|
+
command,
|
|
528
|
+
[...args],
|
|
529
|
+
{ timeout: 4000, windowsHide: true, maxBuffer: 64 * 1024 },
|
|
530
|
+
(error, stdout) => resolve(error ? undefined : String(stdout)),
|
|
531
|
+
)
|
|
532
|
+
}),
|
|
533
|
+
}),
|
|
534
|
+
})
|
|
535
|
+
|
|
536
|
+
async function trustedList(): Promise<readonly TrustedNetwork[]> {
|
|
537
|
+
const read = await store.readTrustedNetworks()
|
|
538
|
+
return read.status === 'ok' ? read.value.networks : []
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
async function networkOf(address: string): Promise<NetworkRef | undefined> {
|
|
542
|
+
const id = await identify(plainAddress(address)).catch(() => undefined)
|
|
543
|
+
if (!id) return undefined
|
|
544
|
+
const list = await trustedList()
|
|
545
|
+
const known = list.find((n) => n.id === id)
|
|
546
|
+
const names = new Set(list.map((n) => n.name.toLowerCase()))
|
|
547
|
+
let n = list.length + 1
|
|
548
|
+
while (names.has(`network ${n}`)) n++
|
|
549
|
+
return { id, ...(known ? { trusted: known.name } : {}), suggestedName: `Network ${n}` }
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
async function trustNetwork(address: string, name?: string): Promise<TrustedNetwork> {
|
|
553
|
+
const ref = await networkOf(address)
|
|
554
|
+
if (!ref)
|
|
555
|
+
throw new NetworkError(
|
|
556
|
+
'invalid',
|
|
557
|
+
'This network cannot be recognised (its gateway cannot be read), so it cannot be trusted.',
|
|
558
|
+
)
|
|
559
|
+
const list = await trustedList()
|
|
560
|
+
const existing = list.find((n) => n.id === ref.id)
|
|
561
|
+
const wanted =
|
|
562
|
+
name === undefined ? (existing?.name ?? ref.suggestedName) : sanitizeName(name, 40)
|
|
563
|
+
if (wanted.length === 0) throw new NetworkError('invalid', 'A network needs a name.')
|
|
564
|
+
if (list.some((n) => n.id !== ref.id && n.name.toLowerCase() === wanted.toLowerCase()))
|
|
565
|
+
throw new NetworkError('invalid', `Another trusted network is already called "${wanted}".`)
|
|
566
|
+
const entry: TrustedNetwork = {
|
|
567
|
+
id: ref.id,
|
|
568
|
+
name: wanted,
|
|
569
|
+
trustedAt: existing?.trustedAt ?? clock.now(),
|
|
570
|
+
}
|
|
571
|
+
await store.writeTrustedNetworks({
|
|
572
|
+
v: 1,
|
|
573
|
+
networks: [...list.filter((n) => n.id !== ref.id), entry],
|
|
574
|
+
})
|
|
575
|
+
logAudit({
|
|
576
|
+
event: 'network_trusted',
|
|
577
|
+
decision: existing ? 'renamed' : 'trusted',
|
|
578
|
+
reason: wanted,
|
|
579
|
+
})
|
|
580
|
+
return entry
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function findTrusted(list: readonly TrustedNetwork[], query: string): TrustedNetwork {
|
|
584
|
+
const q = query.trim().toLowerCase()
|
|
585
|
+
const hits = list.filter((n) => n.name.toLowerCase() === q)
|
|
586
|
+
const matches = hits.length > 0 ? hits : list.filter((n) => q.length >= 4 && n.id.startsWith(q))
|
|
587
|
+
if (matches.length !== 1)
|
|
588
|
+
throw new NetworkError(
|
|
589
|
+
'unknown_target',
|
|
590
|
+
matches.length === 0
|
|
591
|
+
? `No trusted network is called "${query}". \`namzu peers networks\` lists them.`
|
|
592
|
+
: 'More than one trusted network matches that.',
|
|
593
|
+
)
|
|
594
|
+
return matches[0] as TrustedNetwork
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
async function renameNetwork(query: string, name: string): Promise<TrustedNetwork> {
|
|
598
|
+
const list = await trustedList()
|
|
599
|
+
const found = findTrusted(list, query)
|
|
600
|
+
const wanted = sanitizeName(name, 40)
|
|
601
|
+
if (wanted.length === 0) throw new NetworkError('invalid', 'A network needs a name.')
|
|
602
|
+
if (list.some((n) => n.id !== found.id && n.name.toLowerCase() === wanted.toLowerCase()))
|
|
603
|
+
throw new NetworkError('invalid', `Another trusted network is already called "${wanted}".`)
|
|
604
|
+
const entry = { ...found, name: wanted }
|
|
605
|
+
await store.writeTrustedNetworks({
|
|
606
|
+
v: 1,
|
|
607
|
+
networks: list.map((n) => (n.id === found.id ? entry : n)),
|
|
608
|
+
})
|
|
609
|
+
logAudit({ event: 'network_trusted', decision: 'renamed', reason: wanted })
|
|
610
|
+
return entry
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
async function untrustNetwork(query: string): Promise<TrustedNetwork> {
|
|
614
|
+
const list = await trustedList()
|
|
615
|
+
const gone = findTrusted(list, query)
|
|
616
|
+
await store.writeTrustedNetworks({ v: 1, networks: list.filter((n) => n.id !== gone.id) })
|
|
617
|
+
logAudit({ event: 'network_untrusted', reason: gone.name })
|
|
618
|
+
return gone
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Why a request from `address` is admitted without asking, or undefined when it must ask. */
|
|
622
|
+
async function autoAdmitMode(
|
|
623
|
+
address: string,
|
|
624
|
+
): Promise<{ mode: 'trusted-network' | 'always'; network?: string } | undefined> {
|
|
625
|
+
const setting = options.autoAdmit?.() ?? 'trusted-networks'
|
|
626
|
+
if (setting === 'never') return undefined
|
|
627
|
+
const plain = plainAddress(address)
|
|
628
|
+
if (setting === 'always')
|
|
629
|
+
return options.allowLoopback || isPrivateNetworkAddress(plain)
|
|
630
|
+
? { mode: 'always' }
|
|
631
|
+
: undefined
|
|
632
|
+
const ref = await networkOf(plain)
|
|
633
|
+
return ref?.trusted ? { mode: 'trusted-network', network: ref.trusted } : undefined
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const joiners = new JoinTable({
|
|
637
|
+
clock,
|
|
638
|
+
onExpire: (entry) => {
|
|
639
|
+
pendingConns.get(entry.requestId)?.write({ status: 'expired' })
|
|
640
|
+
pendingConns.get(entry.requestId)?.close()
|
|
641
|
+
pendingConns.delete(entry.requestId)
|
|
642
|
+
logAudit({
|
|
643
|
+
event: 'join_expired',
|
|
644
|
+
machine: { id12: entry.viaMachineId.slice(0, 12), name: entry.name },
|
|
645
|
+
})
|
|
646
|
+
emit({ type: 'join-settled', requestId: entry.requestId, result: 'expired' })
|
|
647
|
+
},
|
|
648
|
+
})
|
|
649
|
+
const heldQueue = new HoldQueue<HeldMail>({
|
|
650
|
+
clock,
|
|
651
|
+
capacity: 32,
|
|
652
|
+
onExpire: (id, mail) => {
|
|
653
|
+
logAudit({
|
|
654
|
+
event: 'mail_expired',
|
|
655
|
+
direction: 'in',
|
|
656
|
+
machine: who(mail.machineId),
|
|
657
|
+
session: mail.toSessionRef,
|
|
658
|
+
})
|
|
659
|
+
emit({ type: 'held-resolved', id, result: 'expired' })
|
|
660
|
+
void notifySender(mail, 'expired', 'The message was not answered in time and has expired.')
|
|
661
|
+
},
|
|
662
|
+
})
|
|
663
|
+
const mailBuckets = new TokenBuckets({ capacity: 30, refillPerSecond: 0.5, clock })
|
|
664
|
+
const roleBuckets = new TokenBuckets({ capacity: 6, refillPerSecond: 0.1, clock })
|
|
665
|
+
const pairs = new SlidingCounter(clock, 60_000)
|
|
666
|
+
|
|
667
|
+
const selfName = () => machine?.name ?? 'this machine'
|
|
668
|
+
const isMember = (machineId: string) => view?.members.has(machineId) === true
|
|
669
|
+
const selfId = () => key?.machineId as string
|
|
670
|
+
|
|
671
|
+
// ─── identity and files ────────────────────────────────────────────────
|
|
672
|
+
|
|
673
|
+
async function loadIdentity(): Promise<void> {
|
|
674
|
+
const k = await store.readKey()
|
|
675
|
+
if (k.status === 'ok') key = k.value
|
|
676
|
+
else {
|
|
677
|
+
key = generateMachineKey()
|
|
678
|
+
if (k.status === 'corrupt')
|
|
679
|
+
host.report?.('The machine key was unreadable; this machine starts a new identity.')
|
|
680
|
+
await store.writeKey(key)
|
|
681
|
+
}
|
|
682
|
+
// A fresh certificate each start: its name is random, so it is no stable mark of this machine.
|
|
683
|
+
const certPem = buildMachineCertificate(key, { now: clock.now() }).pem
|
|
684
|
+
await store.writeCertificate(certPem)
|
|
685
|
+
tls = { key, certificatePem: certPem }
|
|
686
|
+
const m = await store.readMachine()
|
|
687
|
+
const name = sanitizeName(
|
|
688
|
+
options.machineName ?? (m.status === 'ok' ? m.value.name : undefined) ?? defaultName(),
|
|
689
|
+
)
|
|
690
|
+
if (m.status === 'ok' && m.value.machineId === key.machineId) {
|
|
691
|
+
machine = { ...m.value, name }
|
|
692
|
+
} else {
|
|
693
|
+
machine = { v: 1, machineId: key.machineId, name, createdAt: clock.now() }
|
|
694
|
+
}
|
|
695
|
+
await store.writeMachine(machine)
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function defaultName(): string {
|
|
699
|
+
const raw = (options.hostname ?? osHostname()).split('.')[0] ?? ''
|
|
700
|
+
return raw.trim().length > 0 ? raw : 'this-machine'
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
async function loadNetwork(): Promise<void> {
|
|
704
|
+
const n = await store.readNetwork()
|
|
705
|
+
const m = await store.readMembers()
|
|
706
|
+
if (n.status !== 'ok' || m.status !== 'ok') return
|
|
707
|
+
const v = evaluateMembership(
|
|
708
|
+
{ admissions: m.value.members, revocations: m.value.revoked },
|
|
709
|
+
n.value.netId,
|
|
710
|
+
)
|
|
711
|
+
if (!v.netId || !v.members.has(selfId())) return
|
|
712
|
+
netId = v.netId
|
|
713
|
+
adm = [...v.admissions]
|
|
714
|
+
rev = [...v.revocations]
|
|
715
|
+
view = v
|
|
716
|
+
membersRev = m.value.rev
|
|
717
|
+
foundedAt = n.value.createdAt
|
|
718
|
+
const peers = await store.readPeers()
|
|
719
|
+
if (peers.status === 'ok') {
|
|
720
|
+
for (const [id, p] of Object.entries(peers.value.machines)) {
|
|
721
|
+
peerState.set(id, {
|
|
722
|
+
name: p.name,
|
|
723
|
+
addresses: p.addresses.map((a) => ({ host: a.host, port: a.port })),
|
|
724
|
+
online: false,
|
|
725
|
+
})
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async function persistMembership(): Promise<void> {
|
|
731
|
+
if (!view || !netId) return
|
|
732
|
+
membersRev++
|
|
733
|
+
const founding = view.admissions.find((a) => a.admittedBy === a.machineId)
|
|
734
|
+
const before = await store.readNetwork()
|
|
735
|
+
await store.writeNetwork({
|
|
736
|
+
v: 1,
|
|
737
|
+
netId,
|
|
738
|
+
founderPublicKey: founding?.publicKey ?? '',
|
|
739
|
+
createdAt:
|
|
740
|
+
before.status === 'ok' && before.value.netId === netId
|
|
741
|
+
? before.value.createdAt
|
|
742
|
+
: clock.now(),
|
|
743
|
+
})
|
|
744
|
+
await store.writeMembers({
|
|
745
|
+
v: 1,
|
|
746
|
+
rev: membersRev,
|
|
747
|
+
members: [...view.admissions],
|
|
748
|
+
revoked: [...view.revocations],
|
|
749
|
+
})
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
async function persistPeers(): Promise<void> {
|
|
753
|
+
const machines: PeersFile['machines'] = {}
|
|
754
|
+
for (const [id, p] of peerState) {
|
|
755
|
+
if (!isMember(id) || id === selfId()) continue
|
|
756
|
+
machines[id] = {
|
|
757
|
+
name: p.name.slice(0, 80),
|
|
758
|
+
addresses: p.addresses
|
|
759
|
+
.slice(0, 4)
|
|
760
|
+
.map((a) => ({ host: a.host, port: a.port, at: clock.now() })),
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
await store.writePeers({ v: 1, machines }).catch(() => undefined)
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// ─── membership changes ────────────────────────────────────────────────
|
|
767
|
+
|
|
768
|
+
function adopt(next: MembershipView): { added: string[]; removed: string[] } {
|
|
769
|
+
const before = new Set(view?.members.keys() ?? [])
|
|
770
|
+
const added = [...next.members.keys()].filter((id) => !before.has(id))
|
|
771
|
+
const removed = [...before].filter((id) => !next.members.has(id))
|
|
772
|
+
view = next
|
|
773
|
+
adm = [...next.admissions]
|
|
774
|
+
rev = [...next.revocations]
|
|
775
|
+
return { added, removed }
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function mergeIn(
|
|
779
|
+
admissions: readonly Admission[],
|
|
780
|
+
revocations: readonly import('./membership.js').Revocation[],
|
|
781
|
+
): Promise<boolean> {
|
|
782
|
+
if (!netId) return false
|
|
783
|
+
const merged = mergeMembership(
|
|
784
|
+
{ admissions: adm, revocations: rev },
|
|
785
|
+
{ admissions, revocations },
|
|
786
|
+
netId,
|
|
787
|
+
)
|
|
788
|
+
if (!merged.netId) return false
|
|
789
|
+
const sizeBefore = adm.length + rev.length
|
|
790
|
+
const { added, removed } = adopt(merged)
|
|
791
|
+
if (
|
|
792
|
+
added.length === 0 &&
|
|
793
|
+
removed.length === 0 &&
|
|
794
|
+
merged.admissions.length + merged.revocations.length === sizeBefore
|
|
795
|
+
)
|
|
796
|
+
return false
|
|
797
|
+
await persistMembership()
|
|
798
|
+
for (const id of added) {
|
|
799
|
+
if (id !== selfId())
|
|
800
|
+
emit({ type: 'member-added', machineId: id, name: peerState.get(id)?.name })
|
|
801
|
+
}
|
|
802
|
+
for (const id of removed) {
|
|
803
|
+
if (id === selfId()) continue
|
|
804
|
+
for (const l of netListeners) l.closeMachine(id)
|
|
805
|
+
logAudit({ event: 'removed', machine: who(id) })
|
|
806
|
+
emit({ type: 'member-removed', machineId: id, name: peerState.get(id)?.name })
|
|
807
|
+
}
|
|
808
|
+
if (!merged.members.has(selfId())) await handleSelfRemoved()
|
|
809
|
+
return added.length > 0 || removed.length > 0
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
async function handleSelfRemoved(): Promise<void> {
|
|
813
|
+
await stopNetworking()
|
|
814
|
+
await store.reset()
|
|
815
|
+
key = undefined
|
|
816
|
+
tls = undefined
|
|
817
|
+
machine = undefined
|
|
818
|
+
netId = undefined
|
|
819
|
+
view = undefined
|
|
820
|
+
adm = []
|
|
821
|
+
rev = []
|
|
822
|
+
foundedAt = undefined
|
|
823
|
+
peerState.clear()
|
|
824
|
+
started = false
|
|
825
|
+
setState('removed', 'This machine was removed from the network. Its identity was reset.')
|
|
826
|
+
emit({ type: 'removed-self' })
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
async function pushSync(except?: string): Promise<void> {
|
|
830
|
+
if (!view) return
|
|
831
|
+
const request = {
|
|
832
|
+
protocol: NET_PROTOCOL,
|
|
833
|
+
op: 'members_sync',
|
|
834
|
+
admissions: adm,
|
|
835
|
+
revocations: rev,
|
|
836
|
+
}
|
|
837
|
+
const targets = new Set([...view.members.keys(), ...view.admissions.map((a) => a.machineId)])
|
|
838
|
+
await Promise.all(
|
|
839
|
+
[...targets]
|
|
840
|
+
.filter((id) => id !== selfId() && id !== except)
|
|
841
|
+
.map(async (id) => {
|
|
842
|
+
try {
|
|
843
|
+
const reply = SyncReplySchema.safeParse(await callMachine(id, request))
|
|
844
|
+
if (reply.success) await mergeIn(reply.data.admissions, reply.data.revocations)
|
|
845
|
+
} catch {
|
|
846
|
+
// offline members catch up when they next connect
|
|
847
|
+
}
|
|
848
|
+
}),
|
|
849
|
+
)
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// ─── dialing ───────────────────────────────────────────────────────────
|
|
853
|
+
|
|
854
|
+
function ownAddress(h: HostPort): boolean {
|
|
855
|
+
return port === h.port && addresses.some((a) => a.address === h.host)
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function candidateAddresses(machineId: string): HostPort[] {
|
|
859
|
+
const out: HostPort[] = []
|
|
860
|
+
for (const a of peerState.get(machineId)?.addresses ?? [])
|
|
861
|
+
if (!out.some((o) => same(o, a))) out.push(a)
|
|
862
|
+
return out
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
async function connectTo(h: HostPort, expectMachineId?: string): Promise<NetClient> {
|
|
866
|
+
if (!tls) throw new NetworkError('off', 'The Namzu network is not running.')
|
|
867
|
+
return dialNet({
|
|
868
|
+
identity: tls,
|
|
869
|
+
host: h.host,
|
|
870
|
+
port: h.port,
|
|
871
|
+
clock,
|
|
872
|
+
expectMachineId,
|
|
873
|
+
accept: expectMachineId ? undefined : (peer: PeerInfo) => isMember(peer.machineId),
|
|
874
|
+
})
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
function remember(machineId: string, h: HostPort): void {
|
|
878
|
+
const p = peerState.get(machineId) ?? {
|
|
879
|
+
name: machineId.slice(0, 12),
|
|
880
|
+
addresses: [],
|
|
881
|
+
online: true,
|
|
882
|
+
}
|
|
883
|
+
p.addresses = [h, ...p.addresses.filter((a) => !same(a, h))].slice(0, 4)
|
|
884
|
+
peerState.set(machineId, p)
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
async function callMachine(machineId: string, request: object): Promise<unknown> {
|
|
888
|
+
let last: unknown
|
|
889
|
+
for (const address of candidateAddresses(machineId)) {
|
|
890
|
+
if (ownAddress(address)) continue
|
|
891
|
+
try {
|
|
892
|
+
const client = await connectTo(address, machineId)
|
|
893
|
+
try {
|
|
894
|
+
const reply = await client.request(request)
|
|
895
|
+
remember(machineId, address)
|
|
896
|
+
const p = peerState.get(machineId)
|
|
897
|
+
if (p) {
|
|
898
|
+
p.online = true
|
|
899
|
+
p.seenAt = clock.now()
|
|
900
|
+
}
|
|
901
|
+
return reply
|
|
902
|
+
} finally {
|
|
903
|
+
client.close()
|
|
904
|
+
}
|
|
905
|
+
} catch (error) {
|
|
906
|
+
last = error
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
const p = peerState.get(machineId)
|
|
910
|
+
if (p) p.online = false
|
|
911
|
+
throw last instanceof NetworkError
|
|
912
|
+
? last
|
|
913
|
+
: new NetworkError('dial', 'That machine could not be reached.')
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// ─── greeting: hello, members_sync, roster over one connection ───────────
|
|
917
|
+
|
|
918
|
+
function ourHostPorts(): HostPort[] {
|
|
919
|
+
return port === undefined
|
|
920
|
+
? []
|
|
921
|
+
: addresses.map((a) => ({ host: a.address, port: port as number }))
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
async function greet(client: NetClient, address: HostPort): Promise<void> {
|
|
925
|
+
const peerId = client.peer.machineId
|
|
926
|
+
remember(peerId, address)
|
|
927
|
+
const hello = HelloReplySchema.safeParse(
|
|
928
|
+
await client.request({
|
|
929
|
+
protocol: NET_PROTOCOL,
|
|
930
|
+
op: 'hello',
|
|
931
|
+
machineName: selfName(),
|
|
932
|
+
addresses: ourHostPorts().slice(0, 8),
|
|
933
|
+
protocolMax: 1,
|
|
934
|
+
}),
|
|
935
|
+
)
|
|
936
|
+
const p = peerState.get(peerId) as PeerState
|
|
937
|
+
if (hello.success) {
|
|
938
|
+
p.name = sanitizeName(hello.data.machineName)
|
|
939
|
+
for (const a of hello.data.addresses) remember(peerId, a)
|
|
940
|
+
remember(peerId, address)
|
|
941
|
+
}
|
|
942
|
+
p.online = true
|
|
943
|
+
p.seenAt = clock.now()
|
|
944
|
+
const sync = SyncReplySchema.safeParse(
|
|
945
|
+
await client.request({
|
|
946
|
+
protocol: NET_PROTOCOL,
|
|
947
|
+
op: 'members_sync',
|
|
948
|
+
admissions: adm,
|
|
949
|
+
revocations: rev,
|
|
950
|
+
}),
|
|
951
|
+
)
|
|
952
|
+
if (sync.success) await mergeIn(sync.data.admissions, sync.data.revocations)
|
|
953
|
+
const roster = RosterSchema.safeParse(
|
|
954
|
+
await client.request({ protocol: NET_PROTOCOL, op: 'roster' }),
|
|
955
|
+
)
|
|
956
|
+
if (roster.success) applyRoster(peerId, roster.data)
|
|
957
|
+
await persistPeers()
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function applyRoster(machineId: string, roster: Roster): void {
|
|
961
|
+
const p = peerState.get(machineId)
|
|
962
|
+
if (!p || roster.machine.id !== machineId) return
|
|
963
|
+
p.name = sanitizeName(roster.machine.name)
|
|
964
|
+
p.role = roster.machine.role === undefined ? undefined : sanitizeRole(roster.machine.role)
|
|
965
|
+
// Everything another machine says about its sessions is text for a screen and for a model.
|
|
966
|
+
p.sessions = roster.sessions.map(({ role, ...s }) => {
|
|
967
|
+
const cleanRole = role === undefined ? undefined : sanitizeRole(role)
|
|
968
|
+
return {
|
|
969
|
+
...s,
|
|
970
|
+
name: sanitizeName(s.name, 80) || 'session',
|
|
971
|
+
folder: sanitizeName(s.folder, 120),
|
|
972
|
+
mode: sanitizeName(s.mode, 40) || 'unknown',
|
|
973
|
+
...(cleanRole ? { role: cleanRole } : {}),
|
|
974
|
+
}
|
|
975
|
+
})
|
|
976
|
+
p.rosterAt = clock.now()
|
|
977
|
+
p.seenAt = clock.now()
|
|
978
|
+
p.online = true
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
async function discover(endpoint: DiscoveredEndpoint): Promise<void> {
|
|
982
|
+
const h = { host: endpoint.host, port: endpoint.port }
|
|
983
|
+
if (ownAddress(h)) return
|
|
984
|
+
const keyText = `${h.host}:${h.port}`
|
|
985
|
+
if (inFlight.has(keyText)) return
|
|
986
|
+
inFlight.add(keyText)
|
|
987
|
+
try {
|
|
988
|
+
const client = await connectTo(h)
|
|
989
|
+
try {
|
|
990
|
+
await greet(client, h)
|
|
991
|
+
} finally {
|
|
992
|
+
client.close()
|
|
993
|
+
}
|
|
994
|
+
} catch {
|
|
995
|
+
// not a member, or unreachable: nothing to do
|
|
996
|
+
} finally {
|
|
997
|
+
inFlight.delete(keyText)
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function onEndpoint(endpoint: DiscoveredEndpoint): void {
|
|
1002
|
+
if (closed) return
|
|
1003
|
+
if (netId && endpoint.netId === netId) {
|
|
1004
|
+
void discover(endpoint)
|
|
1005
|
+
return
|
|
1006
|
+
}
|
|
1007
|
+
if (netId && view && view.members.size <= 1) {
|
|
1008
|
+
void considerStepDown(endpoint)
|
|
1009
|
+
return
|
|
1010
|
+
}
|
|
1011
|
+
if (!view || view.members.size <= 1) {
|
|
1012
|
+
if (!nearby.has(endpoint.netId) && nearby.size >= MAX_NEARBY_NETWORKS) return
|
|
1013
|
+
const list = nearby.get(endpoint.netId) ?? []
|
|
1014
|
+
if (list.length >= 8) return
|
|
1015
|
+
if (!list.some((e) => e.host === endpoint.host && e.port === endpoint.port))
|
|
1016
|
+
list.push(endpoint)
|
|
1017
|
+
nearby.set(endpoint.netId, list)
|
|
1018
|
+
if (state === 'searching' || state === 'ambiguous')
|
|
1019
|
+
emit({ type: 'nearby', networks: [...nearby.keys()] })
|
|
1020
|
+
} else if (endpoint.netId !== netId) {
|
|
1021
|
+
emit({ type: 'nearby', networks: [endpoint.netId] })
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// ─── start / found / join ──────────────────────────────────────────────
|
|
1026
|
+
|
|
1027
|
+
function eligibleAddresses(): ListenAddress[] {
|
|
1028
|
+
return privateInterfaces((options.interfaces ?? networkInterfaces)(), {
|
|
1029
|
+
allowLoopback: options.allowLoopback,
|
|
1030
|
+
anyAddress: options.anyNetwork,
|
|
1031
|
+
})
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
async function startListeners(list: ListenAddress[]): Promise<void> {
|
|
1035
|
+
if (!tls) return
|
|
1036
|
+
const identity = tls
|
|
1037
|
+
const preferred = options.listenPort ?? machine?.listenPort ?? DEFAULT_LISTEN_PORT
|
|
1038
|
+
addresses = list
|
|
1039
|
+
port = undefined
|
|
1040
|
+
for (const a of list) {
|
|
1041
|
+
const l = createNetListener({
|
|
1042
|
+
identity,
|
|
1043
|
+
clock,
|
|
1044
|
+
isMember,
|
|
1045
|
+
handle: handle,
|
|
1046
|
+
onRefused: (info) =>
|
|
1047
|
+
logAudit({
|
|
1048
|
+
event: 'connection_refused',
|
|
1049
|
+
machine: info.machineId ? { id12: shortMachineId(info.machineId) } : undefined,
|
|
1050
|
+
reason: `${info.reason}${info.op ? `:${info.op}` : ''}`,
|
|
1051
|
+
}),
|
|
1052
|
+
})
|
|
1053
|
+
const want = port ?? preferred
|
|
1054
|
+
let bound: number
|
|
1055
|
+
try {
|
|
1056
|
+
bound = await l.listen(a.bindHost, want)
|
|
1057
|
+
} catch {
|
|
1058
|
+
if (port !== undefined || want === 0) continue
|
|
1059
|
+
bound = await l.listen(a.bindHost, 0)
|
|
1060
|
+
}
|
|
1061
|
+
port ??= bound
|
|
1062
|
+
netListeners.push(l)
|
|
1063
|
+
}
|
|
1064
|
+
if (
|
|
1065
|
+
port !== undefined &&
|
|
1066
|
+
options.listenPort === undefined &&
|
|
1067
|
+
machine &&
|
|
1068
|
+
machine.listenPort !== port
|
|
1069
|
+
) {
|
|
1070
|
+
machine = { ...machine, listenPort: port }
|
|
1071
|
+
await store.writeMachine(machine)
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
async function advertise(): Promise<void> {
|
|
1076
|
+
if (netId && port !== undefined) {
|
|
1077
|
+
discovery.start({ netId, port, addresses: addresses.map((a) => a.address) })
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
async function found(): Promise<void> {
|
|
1082
|
+
if (!key || netId) return
|
|
1083
|
+
const founding = createFounding(key, clock.now())
|
|
1084
|
+
const next = evaluateMembership({ admissions: [founding], revocations: [] })
|
|
1085
|
+
netId = next.netId
|
|
1086
|
+
foundedAt = clock.now()
|
|
1087
|
+
adopt(next)
|
|
1088
|
+
await persistMembership()
|
|
1089
|
+
setState('ready')
|
|
1090
|
+
emit({ type: 'founded', netId: netId as string })
|
|
1091
|
+
await advertise()
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
/**
|
|
1095
|
+
* Two machines that started together each browsed, heard nothing and founded a network. When a second
|
|
1096
|
+
* fresh network that is also alone turns up, the younger one (by the age each reports on its own clock,
|
|
1097
|
+
* ties by network id) asks the older to let it in; the person on the older one sees one line and one Allow.
|
|
1098
|
+
*/
|
|
1099
|
+
async function considerStepDown(endpoint: DiscoveredEndpoint): Promise<void> {
|
|
1100
|
+
if (!tls || !netId || foundedAt === undefined || closed) return
|
|
1101
|
+
if (joining || declinedNets.has(endpoint.netId)) return
|
|
1102
|
+
if (clock.now() - foundedAt > FRESH_NETWORK_MS) return
|
|
1103
|
+
const keyText = `${endpoint.host}:${endpoint.port}`
|
|
1104
|
+
if (probing.has(keyText)) return
|
|
1105
|
+
probing.add(keyText)
|
|
1106
|
+
let theirAge: number | undefined
|
|
1107
|
+
try {
|
|
1108
|
+
const client = await dialNet({
|
|
1109
|
+
identity: tls,
|
|
1110
|
+
host: endpoint.host,
|
|
1111
|
+
port: endpoint.port,
|
|
1112
|
+
clock,
|
|
1113
|
+
})
|
|
1114
|
+
try {
|
|
1115
|
+
const reply = (await client.request({ protocol: NET_PROTOCOL, op: 'ping_net' })) as {
|
|
1116
|
+
netId?: unknown
|
|
1117
|
+
ageMs?: unknown
|
|
1118
|
+
}
|
|
1119
|
+
if (reply.netId === endpoint.netId && typeof reply.ageMs === 'number')
|
|
1120
|
+
theirAge = reply.ageMs
|
|
1121
|
+
} finally {
|
|
1122
|
+
client.close()
|
|
1123
|
+
}
|
|
1124
|
+
} catch {
|
|
1125
|
+
return
|
|
1126
|
+
} finally {
|
|
1127
|
+
probing.delete(keyText)
|
|
1128
|
+
}
|
|
1129
|
+
if (theirAge === undefined || closed || joining || !netId || foundedAt === undefined) return
|
|
1130
|
+
if (!view || view.members.size > 1) return
|
|
1131
|
+
if (theirAge > FRESH_NETWORK_MS) return
|
|
1132
|
+
const mine = clock.now() - foundedAt
|
|
1133
|
+
const younger = mine < theirAge || (mine === theirAge && (netId as string) > endpoint.netId)
|
|
1134
|
+
if (!younger) return
|
|
1135
|
+
declinedNets.add(endpoint.netId)
|
|
1136
|
+
emit({ type: 'nearby', networks: [endpoint.netId] })
|
|
1137
|
+
await join({ host: endpoint.host, port: endpoint.port }).catch(() => undefined)
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
async function afterBrowse(): Promise<void> {
|
|
1141
|
+
cancelBrowse = undefined
|
|
1142
|
+
if (closed || netId) return
|
|
1143
|
+
const nets = [...nearby.keys()]
|
|
1144
|
+
if (nets.length === 0) return found()
|
|
1145
|
+
if (nets.length === 1) {
|
|
1146
|
+
const target = (
|
|
1147
|
+
nearby.get(nets[0] as string) as DiscoveredEndpoint[]
|
|
1148
|
+
)[0] as DiscoveredEndpoint
|
|
1149
|
+
setState('searching', 'Asking to join a Namzu network nearby.')
|
|
1150
|
+
void join({ host: target.host, port: target.port }).catch(() => undefined)
|
|
1151
|
+
return
|
|
1152
|
+
}
|
|
1153
|
+
setState('ambiguous', `Found ${nets.length} Namzu networks nearby.`)
|
|
1154
|
+
emit({ type: 'nearby', networks: nets })
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
async function start(): Promise<void> {
|
|
1158
|
+
if (started) return
|
|
1159
|
+
started = true
|
|
1160
|
+
closed = false
|
|
1161
|
+
setState('starting')
|
|
1162
|
+
const list = eligibleAddresses()
|
|
1163
|
+
if (list.length === 0) {
|
|
1164
|
+
started = false
|
|
1165
|
+
setState('off', 'This network is not known to be private.')
|
|
1166
|
+
return
|
|
1167
|
+
}
|
|
1168
|
+
await loadIdentity()
|
|
1169
|
+
await loadNetwork()
|
|
1170
|
+
await startListeners(list)
|
|
1171
|
+
logAudit({ event: 'network_on' })
|
|
1172
|
+
offDiscovery.push(discovery.onFound(onEndpoint))
|
|
1173
|
+
if (netId) {
|
|
1174
|
+
setState('ready')
|
|
1175
|
+
discovery.start({ netId, port: port as number, addresses: list.map((a) => a.address) })
|
|
1176
|
+
for (const id of view?.members.keys() ?? []) {
|
|
1177
|
+
if (id === selfId()) continue
|
|
1178
|
+
void reconnect(id)
|
|
1179
|
+
}
|
|
1180
|
+
} else {
|
|
1181
|
+
setState('searching')
|
|
1182
|
+
discovery.start(undefined)
|
|
1183
|
+
cancelBrowse = clock.setTimer(() => void afterBrowse(), options.browseMs ?? BROWSE_WINDOW_MS)
|
|
1184
|
+
}
|
|
1185
|
+
watchInterfaces(list)
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
async function reconnect(machineId: string): Promise<void> {
|
|
1189
|
+
for (const address of candidateAddresses(machineId)) {
|
|
1190
|
+
if (ownAddress(address)) continue
|
|
1191
|
+
try {
|
|
1192
|
+
const client = await connectTo(address, machineId)
|
|
1193
|
+
try {
|
|
1194
|
+
await greet(client, address)
|
|
1195
|
+
} finally {
|
|
1196
|
+
client.close()
|
|
1197
|
+
}
|
|
1198
|
+
return
|
|
1199
|
+
} catch {
|
|
1200
|
+
// try the next address
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
function watchInterfaces(initial: ListenAddress[]): void {
|
|
1206
|
+
let current = initial
|
|
1207
|
+
.map((a) => a.address)
|
|
1208
|
+
.sort()
|
|
1209
|
+
.join(',')
|
|
1210
|
+
const tick = () => {
|
|
1211
|
+
if (closed) return
|
|
1212
|
+
const list = eligibleAddresses()
|
|
1213
|
+
const joined = list
|
|
1214
|
+
.map((a) => a.address)
|
|
1215
|
+
.sort()
|
|
1216
|
+
.join(',')
|
|
1217
|
+
if (joined !== current && list.length === 0) {
|
|
1218
|
+
// Left the private network: nothing listens or is announced until one is back.
|
|
1219
|
+
current = joined
|
|
1220
|
+
void (async () => {
|
|
1221
|
+
await Promise.all(netListeners.splice(0).map((l) => l.close()))
|
|
1222
|
+
port = undefined
|
|
1223
|
+
addresses = []
|
|
1224
|
+
discovery.start(undefined)
|
|
1225
|
+
setState('off', 'This network is not known to be private.')
|
|
1226
|
+
})()
|
|
1227
|
+
} else if (joined !== current) {
|
|
1228
|
+
current = joined
|
|
1229
|
+
void (async () => {
|
|
1230
|
+
await Promise.all(netListeners.splice(0).map((l) => l.close()))
|
|
1231
|
+
await startListeners(list)
|
|
1232
|
+
await advertise()
|
|
1233
|
+
if (netId) setState('ready')
|
|
1234
|
+
else if (state === 'off') setState('searching')
|
|
1235
|
+
})()
|
|
1236
|
+
}
|
|
1237
|
+
cancelRecheck = clock.setTimer(tick, INTERFACE_RECHECK_MS)
|
|
1238
|
+
}
|
|
1239
|
+
cancelRecheck = clock.setTimer(tick, INTERFACE_RECHECK_MS)
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
async function join(
|
|
1243
|
+
endpoint: HostPort,
|
|
1244
|
+
): Promise<'joined' | 'denied' | 'expired' | 'refused' | 'cancelled'> {
|
|
1245
|
+
if (!tls || !key) throw new NetworkError('off', 'The Namzu network is not running.')
|
|
1246
|
+
if (view && view.members.size > 1)
|
|
1247
|
+
throw new NetworkError('invalid', 'This machine is already in a network.')
|
|
1248
|
+
if (joining) throw new NetworkError('invalid', 'A request to join is already waiting.')
|
|
1249
|
+
joining = true
|
|
1250
|
+
const publicKey = key.publicKeyDer.toString('base64')
|
|
1251
|
+
const nonce = randomBytes(16).toString('base64')
|
|
1252
|
+
let client: NetClient | undefined
|
|
1253
|
+
joinCancelled = false
|
|
1254
|
+
try {
|
|
1255
|
+
client = await connectTo(endpoint, undefined).catch(() => undefined)
|
|
1256
|
+
if (!client) {
|
|
1257
|
+
client = await dialNet({ identity: tls, host: endpoint.host, port: endpoint.port, clock })
|
|
1258
|
+
}
|
|
1259
|
+
joinClient = client
|
|
1260
|
+
const first = await client.request({
|
|
1261
|
+
protocol: NET_PROTOCOL,
|
|
1262
|
+
op: 'join_request',
|
|
1263
|
+
machineName: selfName(),
|
|
1264
|
+
publicKey,
|
|
1265
|
+
nonce,
|
|
1266
|
+
})
|
|
1267
|
+
const pending = PendingFrameSchema.safeParse(first)
|
|
1268
|
+
if (!pending.success) {
|
|
1269
|
+
const reason = EndFrameSchema.safeParse(first)
|
|
1270
|
+
emit({
|
|
1271
|
+
type: 'join-ended',
|
|
1272
|
+
result: 'refused',
|
|
1273
|
+
reason: reason.success ? reason.data.reason : undefined,
|
|
1274
|
+
})
|
|
1275
|
+
return 'refused'
|
|
1276
|
+
}
|
|
1277
|
+
const code = joinCode(key.machineId, client.peer.machineId, nonce, pending.data.nonce)
|
|
1278
|
+
emit({ type: 'join-waiting', code, shownCode: formatJoinCode(code), endpoint })
|
|
1279
|
+
let final: unknown
|
|
1280
|
+
try {
|
|
1281
|
+
final = await client.nextFrame()
|
|
1282
|
+
} catch (error) {
|
|
1283
|
+
if (!joinCancelled) throw error
|
|
1284
|
+
emit({ type: 'join-ended', result: 'cancelled' })
|
|
1285
|
+
return 'cancelled'
|
|
1286
|
+
}
|
|
1287
|
+
const admitted = AdmittedFrameSchema.safeParse(final)
|
|
1288
|
+
if (!admitted.success) {
|
|
1289
|
+
const end = EndFrameSchema.safeParse(final)
|
|
1290
|
+
const result = end.success
|
|
1291
|
+
? end.data.status === 'denied'
|
|
1292
|
+
? 'denied'
|
|
1293
|
+
: end.data.status === 'expired'
|
|
1294
|
+
? 'expired'
|
|
1295
|
+
: 'refused'
|
|
1296
|
+
: 'refused'
|
|
1297
|
+
emit({ type: 'join-ended', result, reason: end.success ? end.data.reason : undefined })
|
|
1298
|
+
return result
|
|
1299
|
+
}
|
|
1300
|
+
const verdict = evaluateMembership(
|
|
1301
|
+
{ admissions: admitted.data.admissions, revocations: admitted.data.revocations },
|
|
1302
|
+
pending.data.netId,
|
|
1303
|
+
)
|
|
1304
|
+
if (verdict.netId !== pending.data.netId || !verdict.members.has(key.machineId)) {
|
|
1305
|
+
emit({
|
|
1306
|
+
type: 'join-ended',
|
|
1307
|
+
result: 'refused',
|
|
1308
|
+
reason: 'The network sent a membership list that did not check out.',
|
|
1309
|
+
})
|
|
1310
|
+
return 'refused'
|
|
1311
|
+
}
|
|
1312
|
+
if (cancelBrowse) cancelBrowse()
|
|
1313
|
+
cancelBrowse = undefined
|
|
1314
|
+
adopt(verdict)
|
|
1315
|
+
netId = verdict.netId
|
|
1316
|
+
foundedAt = undefined
|
|
1317
|
+
await persistMembership()
|
|
1318
|
+
for (const p of admitted.data.peers) {
|
|
1319
|
+
if (p.machineId === key.machineId) continue
|
|
1320
|
+
const existing = peerState.get(p.machineId)
|
|
1321
|
+
peerState.set(p.machineId, {
|
|
1322
|
+
name: sanitizeName(p.name),
|
|
1323
|
+
addresses: p.addresses,
|
|
1324
|
+
online: existing?.online ?? false,
|
|
1325
|
+
})
|
|
1326
|
+
}
|
|
1327
|
+
remember(client.peer.machineId, endpoint)
|
|
1328
|
+
setState('ready')
|
|
1329
|
+
emit({ type: 'joined', netId: netId as string, members: verdict.members.size })
|
|
1330
|
+
await advertise()
|
|
1331
|
+
for (const id of verdict.members.keys()) if (id !== key.machineId) void reconnect(id)
|
|
1332
|
+
return 'joined'
|
|
1333
|
+
} finally {
|
|
1334
|
+
joining = false
|
|
1335
|
+
joinClient = undefined
|
|
1336
|
+
client?.close()
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
function cancelJoin(): boolean {
|
|
1341
|
+
if (!joining || !joinClient) return false
|
|
1342
|
+
joinCancelled = true
|
|
1343
|
+
joinClient.close()
|
|
1344
|
+
return true
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
// ─── request handling ──────────────────────────────────────────────────
|
|
1348
|
+
|
|
1349
|
+
function peersForJoiner(): z.infer<typeof PeerEntrySchema>[] {
|
|
1350
|
+
const out: z.infer<typeof PeerEntrySchema>[] = [
|
|
1351
|
+
{ machineId: selfId(), name: selfName(), addresses: ourHostPorts().slice(0, 8) },
|
|
1352
|
+
]
|
|
1353
|
+
for (const [id, p] of peerState) {
|
|
1354
|
+
if (isMember(id) && id !== selfId())
|
|
1355
|
+
out.push({ machineId: id, name: p.name, addresses: p.addresses.slice(0, 4) })
|
|
1356
|
+
}
|
|
1357
|
+
return out.slice(0, MAX_MEMBERS)
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
function admittedFrame() {
|
|
1361
|
+
return { status: 'admitted', netId, admissions: adm, revocations: rev, peers: peersForJoiner() }
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
function buildSelfRoster(): Roster {
|
|
1365
|
+
const sessions: RosterSession[] = host
|
|
1366
|
+
.listLocalSessions()
|
|
1367
|
+
.slice(0, 64)
|
|
1368
|
+
.map((s) => ({
|
|
1369
|
+
ref: s.ref,
|
|
1370
|
+
name: s.name,
|
|
1371
|
+
folder: s.folder,
|
|
1372
|
+
state: s.state,
|
|
1373
|
+
mode: s.mode,
|
|
1374
|
+
...(s.role ? { role: s.role } : {}),
|
|
1375
|
+
acceptsMessages: s.acceptsMessages,
|
|
1376
|
+
kind: 'tui' as const,
|
|
1377
|
+
}))
|
|
1378
|
+
return {
|
|
1379
|
+
machine: {
|
|
1380
|
+
id: selfId(),
|
|
1381
|
+
name: selfName(),
|
|
1382
|
+
...(machine?.role ? { role: machine.role } : {}),
|
|
1383
|
+
platform,
|
|
1384
|
+
},
|
|
1385
|
+
sessions,
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
async function handle(request: NetRequest, ctx: ServerContext): Promise<unknown> {
|
|
1390
|
+
const peerId = ctx.peer.machineId
|
|
1391
|
+
switch (request.op) {
|
|
1392
|
+
case 'ping_net':
|
|
1393
|
+
// A machine alone in a network just founded says how old it is, so two that founded
|
|
1394
|
+
// together can tell which is younger; a network with others in it says nothing more.
|
|
1395
|
+
return netId
|
|
1396
|
+
? view && view.members.size <= 1 && foundedAt !== undefined
|
|
1397
|
+
? { ok: true, netId, ageMs: Math.max(0, clock.now() - foundedAt) }
|
|
1398
|
+
: { ok: true, netId }
|
|
1399
|
+
: { ok: true }
|
|
1400
|
+
case 'join_request':
|
|
1401
|
+
return handleJoinRequest(request, ctx)
|
|
1402
|
+
case 'hello': {
|
|
1403
|
+
const p = peerState.get(peerId) ?? {
|
|
1404
|
+
name: request.machineName,
|
|
1405
|
+
addresses: [],
|
|
1406
|
+
online: true,
|
|
1407
|
+
}
|
|
1408
|
+
p.name = sanitizeName(request.machineName)
|
|
1409
|
+
p.online = true
|
|
1410
|
+
p.seenAt = clock.now()
|
|
1411
|
+
peerState.set(peerId, p)
|
|
1412
|
+
for (const a of request.addresses) remember(peerId, a)
|
|
1413
|
+
void persistPeers()
|
|
1414
|
+
return { machineName: selfName(), addresses: ourHostPorts().slice(0, 8) }
|
|
1415
|
+
}
|
|
1416
|
+
case 'members_sync': {
|
|
1417
|
+
await mergeIn(request.admissions, request.revocations)
|
|
1418
|
+
return { admissions: adm, revocations: rev }
|
|
1419
|
+
}
|
|
1420
|
+
case 'join_pending': {
|
|
1421
|
+
const created = joiners.addRemote({
|
|
1422
|
+
requestId: request.requestId,
|
|
1423
|
+
name: sanitizeName(request.name),
|
|
1424
|
+
code: request.code,
|
|
1425
|
+
sourceAddr: request.sourceAddr,
|
|
1426
|
+
createdAt: request.createdAt,
|
|
1427
|
+
viaMachineId: request.viaMachineId,
|
|
1428
|
+
joinerMachineId: machineIdOf(Buffer.from(request.publicKey, 'base64')),
|
|
1429
|
+
joinerPublicKey: request.publicKey,
|
|
1430
|
+
})
|
|
1431
|
+
if (created) emit({ type: 'join-request', request: created })
|
|
1432
|
+
return { ok: true }
|
|
1433
|
+
}
|
|
1434
|
+
case 'join_decision':
|
|
1435
|
+
return handleJoinDecision(request, peerId)
|
|
1436
|
+
case 'roster':
|
|
1437
|
+
return buildSelfRoster()
|
|
1438
|
+
case 'role_set':
|
|
1439
|
+
return handleRoleSet(request, peerId)
|
|
1440
|
+
case 'net_deliver':
|
|
1441
|
+
return handleDeliver(request, peerId)
|
|
1442
|
+
case 'net_notice':
|
|
1443
|
+
return handleNotice(request, peerId)
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
async function handleJoinRequest(
|
|
1448
|
+
request: Extract<NetRequest, { op: 'join_request' }>,
|
|
1449
|
+
ctx: ServerContext,
|
|
1450
|
+
): Promise<unknown> {
|
|
1451
|
+
if (!netId || !view) return { status: 'refused', reason: 'This machine is not in a network.' }
|
|
1452
|
+
const joinerKey = Buffer.from(request.publicKey, 'base64')
|
|
1453
|
+
const joinerId = machineIdOf(joinerKey)
|
|
1454
|
+
if (joinerId !== ctx.peer.machineId)
|
|
1455
|
+
return { status: 'refused', reason: 'The key does not match the connection.' }
|
|
1456
|
+
if (view.members.has(joinerId)) return { ...admittedFrame() }
|
|
1457
|
+
if (view.removed.has(joinerId))
|
|
1458
|
+
return { status: 'refused', reason: 'This machine was removed from the network.' }
|
|
1459
|
+
const auto = await autoAdmitMode(ctx.sourceAddress).catch(() => undefined)
|
|
1460
|
+
const nonceM = randomBytes(16).toString('base64')
|
|
1461
|
+
const code = joinCode(joinerId, selfId(), request.nonce, nonceM)
|
|
1462
|
+
const requestId = randomUUID()
|
|
1463
|
+
const added = joiners.addLocal({
|
|
1464
|
+
requestId,
|
|
1465
|
+
name: sanitizeName(request.machineName),
|
|
1466
|
+
code,
|
|
1467
|
+
sourceAddr: ctx.sourceAddress,
|
|
1468
|
+
viaMachineId: selfId(),
|
|
1469
|
+
joinerMachineId: joinerId,
|
|
1470
|
+
joinerPublicKey: request.publicKey,
|
|
1471
|
+
})
|
|
1472
|
+
if (!added.ok)
|
|
1473
|
+
return {
|
|
1474
|
+
status: 'refused',
|
|
1475
|
+
reason:
|
|
1476
|
+
added.reason === 'rate' ? 'Asked again too soon.' : 'Too many requests are waiting.',
|
|
1477
|
+
}
|
|
1478
|
+
ctx.holdOpen()
|
|
1479
|
+
pendingConns.set(requestId, ctx)
|
|
1480
|
+
ctx.onClose(() => {
|
|
1481
|
+
pendingConns.delete(requestId)
|
|
1482
|
+
if (joiners.get(requestId)) {
|
|
1483
|
+
joiners.settle(requestId, 'deny')
|
|
1484
|
+
emit({ type: 'join-settled', requestId, result: 'deny' })
|
|
1485
|
+
}
|
|
1486
|
+
})
|
|
1487
|
+
// The joiner must read `pending` before any decision can reach it, so write it first.
|
|
1488
|
+
ctx.write({ status: 'pending', nonce: nonceM, netId })
|
|
1489
|
+
logAudit({
|
|
1490
|
+
event: 'join_requested',
|
|
1491
|
+
machine: { id12: shortMachineId(joinerId), name: added.entry.name },
|
|
1492
|
+
})
|
|
1493
|
+
if (auto) {
|
|
1494
|
+
try {
|
|
1495
|
+
// Admitted without asking: nobody is shown a request, so the other members are not told of one.
|
|
1496
|
+
emit({
|
|
1497
|
+
type: 'join-auto',
|
|
1498
|
+
requestId,
|
|
1499
|
+
name: added.entry.name,
|
|
1500
|
+
machineId: joinerId,
|
|
1501
|
+
mode: auto.mode,
|
|
1502
|
+
...(auto.network ? { network: auto.network } : {}),
|
|
1503
|
+
at: clock.now(),
|
|
1504
|
+
})
|
|
1505
|
+
await decideJoin(
|
|
1506
|
+
requestId,
|
|
1507
|
+
'allow',
|
|
1508
|
+
auto.mode === 'always'
|
|
1509
|
+
? 'automatically (network.autoAdmit is always)'
|
|
1510
|
+
: `automatically (trusted network ${auto.network})`,
|
|
1511
|
+
)
|
|
1512
|
+
return undefined
|
|
1513
|
+
} catch {
|
|
1514
|
+
// fall through: the request waits for a person like any other
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
emit({ type: 'join-request', request: added.entry })
|
|
1518
|
+
void gossipPending(added.entry, request.publicKey)
|
|
1519
|
+
return undefined
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
async function gossipPending(entry: PendingJoin, publicKey: string): Promise<void> {
|
|
1523
|
+
const frame = {
|
|
1524
|
+
protocol: NET_PROTOCOL,
|
|
1525
|
+
op: 'join_pending',
|
|
1526
|
+
requestId: entry.requestId,
|
|
1527
|
+
name: entry.name,
|
|
1528
|
+
code: entry.code,
|
|
1529
|
+
sourceAddr: entry.sourceAddr,
|
|
1530
|
+
createdAt: entry.createdAt,
|
|
1531
|
+
viaMachineId: selfId(),
|
|
1532
|
+
publicKey,
|
|
1533
|
+
}
|
|
1534
|
+
await Promise.all(
|
|
1535
|
+
[...(view?.members.keys() ?? [])]
|
|
1536
|
+
.filter((id) => id !== selfId())
|
|
1537
|
+
.map((id) => callMachine(id, frame).catch(() => undefined)),
|
|
1538
|
+
)
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
/** The name a joiner gave itself, so the members that let it in show it before its own greeting arrives. */
|
|
1542
|
+
function rememberJoinerName(machineId: string, name: string): void {
|
|
1543
|
+
if (peerState.has(machineId)) return
|
|
1544
|
+
peerState.set(machineId, { name: sanitizeName(name), addresses: [], online: false })
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
async function handleJoinDecision(
|
|
1548
|
+
request: Extract<NetRequest, { op: 'join_decision' }>,
|
|
1549
|
+
from: string,
|
|
1550
|
+
note?: string,
|
|
1551
|
+
): Promise<unknown> {
|
|
1552
|
+
const entry = joiners.get(request.requestId)
|
|
1553
|
+
if (!entry) {
|
|
1554
|
+
joiners.settle(request.requestId, request.decision)
|
|
1555
|
+
return { ok: false, reason: 'already' }
|
|
1556
|
+
}
|
|
1557
|
+
if (!entry.local) {
|
|
1558
|
+
// Another member decided about a request that went through a third machine: just settle it.
|
|
1559
|
+
joiners.settle(request.requestId, request.decision)
|
|
1560
|
+
if (request.admission) {
|
|
1561
|
+
rememberJoinerName(request.admission.machineId, entry.name)
|
|
1562
|
+
await mergeIn([request.admission], [])
|
|
1563
|
+
}
|
|
1564
|
+
emit({ type: 'join-settled', requestId: request.requestId, result: request.decision })
|
|
1565
|
+
return { ok: true }
|
|
1566
|
+
}
|
|
1567
|
+
if (joiners.decide(request.requestId, request.decision) !== 'ok')
|
|
1568
|
+
return { ok: false, reason: 'already' }
|
|
1569
|
+
const conn = pendingConns.get(request.requestId)
|
|
1570
|
+
pendingConns.delete(request.requestId)
|
|
1571
|
+
if (request.decision === 'allow') {
|
|
1572
|
+
const a = request.admission
|
|
1573
|
+
if (!a || a.machineId !== entry.joinerMachineId || a.admittedBy !== from) {
|
|
1574
|
+
conn?.write({ status: 'refused', reason: 'The admission did not match the request.' })
|
|
1575
|
+
conn?.close()
|
|
1576
|
+
return { ok: false }
|
|
1577
|
+
}
|
|
1578
|
+
rememberJoinerName(a.machineId, entry.name)
|
|
1579
|
+
await mergeIn([a], [])
|
|
1580
|
+
if (!isMember(a.machineId)) {
|
|
1581
|
+
conn?.write({ status: 'refused', reason: 'The admission did not check out.' })
|
|
1582
|
+
conn?.close()
|
|
1583
|
+
return { ok: false }
|
|
1584
|
+
}
|
|
1585
|
+
conn?.write(admittedFrame())
|
|
1586
|
+
logAudit({
|
|
1587
|
+
event: 'join_allowed',
|
|
1588
|
+
machine: { id12: shortMachineId(a.machineId), name: entry.name },
|
|
1589
|
+
decision: note ?? `by ${shortMachineId(from)}`,
|
|
1590
|
+
})
|
|
1591
|
+
emit({ type: 'join-settled', requestId: request.requestId, result: 'allow' })
|
|
1592
|
+
void pushSync()
|
|
1593
|
+
void gossipDecision(request.requestId, 'allow', a, from)
|
|
1594
|
+
} else {
|
|
1595
|
+
conn?.write({ status: 'denied' })
|
|
1596
|
+
logAudit({
|
|
1597
|
+
event: 'join_denied',
|
|
1598
|
+
machine: { id12: shortMachineId(entry.joinerMachineId ?? ''), name: entry.name },
|
|
1599
|
+
decision: `by ${shortMachineId(from)}`,
|
|
1600
|
+
})
|
|
1601
|
+
emit({ type: 'join-settled', requestId: request.requestId, result: 'deny' })
|
|
1602
|
+
void gossipDecision(request.requestId, 'deny', undefined, from)
|
|
1603
|
+
}
|
|
1604
|
+
conn?.close()
|
|
1605
|
+
return { ok: true }
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
async function gossipDecision(
|
|
1609
|
+
requestId: string,
|
|
1610
|
+
decision: 'allow' | 'deny',
|
|
1611
|
+
admission: Admission | undefined,
|
|
1612
|
+
except: string,
|
|
1613
|
+
): Promise<void> {
|
|
1614
|
+
const frame = {
|
|
1615
|
+
protocol: NET_PROTOCOL,
|
|
1616
|
+
op: 'join_decision',
|
|
1617
|
+
requestId,
|
|
1618
|
+
decision,
|
|
1619
|
+
...(admission ? { admission } : {}),
|
|
1620
|
+
}
|
|
1621
|
+
await Promise.all(
|
|
1622
|
+
[...(view?.members.keys() ?? [])]
|
|
1623
|
+
.filter((id) => id !== selfId() && id !== except)
|
|
1624
|
+
.map((id) => callMachine(id, frame).catch(() => undefined)),
|
|
1625
|
+
)
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
async function decideJoin(
|
|
1629
|
+
query: string,
|
|
1630
|
+
decision: 'allow' | 'deny',
|
|
1631
|
+
note?: string,
|
|
1632
|
+
): Promise<PendingJoin> {
|
|
1633
|
+
if (!key || !netId) throw new NetworkError('no_network', 'This machine is not in a network.')
|
|
1634
|
+
const entry = joiners.find(query)
|
|
1635
|
+
if (!entry) throw new NetworkError('unknown_target', 'No request to join matches that.')
|
|
1636
|
+
if (entry.local) {
|
|
1637
|
+
// This machine is the one the joiner reached: decide here.
|
|
1638
|
+
const admission =
|
|
1639
|
+
decision === 'allow'
|
|
1640
|
+
? signAdmission(
|
|
1641
|
+
key,
|
|
1642
|
+
netId,
|
|
1643
|
+
{
|
|
1644
|
+
machineId: entry.joinerMachineId as string,
|
|
1645
|
+
publicKey: entry.joinerPublicKey as string,
|
|
1646
|
+
},
|
|
1647
|
+
clock.now(),
|
|
1648
|
+
)
|
|
1649
|
+
: undefined
|
|
1650
|
+
await handleJoinDecision(
|
|
1651
|
+
{
|
|
1652
|
+
protocol: NET_PROTOCOL,
|
|
1653
|
+
op: 'join_decision',
|
|
1654
|
+
requestId: entry.requestId,
|
|
1655
|
+
decision,
|
|
1656
|
+
...(admission ? { admission } : {}),
|
|
1657
|
+
},
|
|
1658
|
+
selfId(),
|
|
1659
|
+
note,
|
|
1660
|
+
)
|
|
1661
|
+
return entry
|
|
1662
|
+
}
|
|
1663
|
+
const admission =
|
|
1664
|
+
decision === 'allow'
|
|
1665
|
+
? signAdmission(
|
|
1666
|
+
key,
|
|
1667
|
+
netId,
|
|
1668
|
+
{
|
|
1669
|
+
machineId: entry.joinerMachineId as string,
|
|
1670
|
+
publicKey: entry.joinerPublicKey as string,
|
|
1671
|
+
},
|
|
1672
|
+
clock.now(),
|
|
1673
|
+
)
|
|
1674
|
+
: undefined
|
|
1675
|
+
const reply = (await callMachine(entry.viaMachineId, {
|
|
1676
|
+
protocol: NET_PROTOCOL,
|
|
1677
|
+
op: 'join_decision',
|
|
1678
|
+
requestId: entry.requestId,
|
|
1679
|
+
decision,
|
|
1680
|
+
...(admission ? { admission } : {}),
|
|
1681
|
+
})) as { ok?: boolean }
|
|
1682
|
+
joiners.settle(entry.requestId, decision)
|
|
1683
|
+
if (reply?.ok === false)
|
|
1684
|
+
throw new NetworkError('refused', 'That request was already decided on another machine.')
|
|
1685
|
+
emit({ type: 'join-settled', requestId: entry.requestId, result: decision })
|
|
1686
|
+
return entry
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
// ─── roles ─────────────────────────────────────────────────────────────
|
|
1690
|
+
|
|
1691
|
+
/** Who set a role, on what, and a hash of the words: never the words. */
|
|
1692
|
+
function roleAudit(from: string, session: string, role: string | null) {
|
|
1693
|
+
return {
|
|
1694
|
+
machine: who(from),
|
|
1695
|
+
session,
|
|
1696
|
+
direction: from === selfId() ? undefined : ('in' as const),
|
|
1697
|
+
decision: role === null ? 'clear' : 'set',
|
|
1698
|
+
...(role === null
|
|
1699
|
+
? {}
|
|
1700
|
+
: { bytes: Buffer.byteLength(role, 'utf8'), textHash: textHash(role) }),
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
async function handleRoleSet(request: RoleSetRequest, from: string): Promise<unknown> {
|
|
1705
|
+
if (!roleBuckets.take(from))
|
|
1706
|
+
return { status: 'refused', reason: 'Too many role changes from that machine.' }
|
|
1707
|
+
const role = request.role === null ? null : (sanitizeRole(request.role) ?? null)
|
|
1708
|
+
const byName = peerState.get(from)?.name ?? sanitizeName(request.by.machineName)
|
|
1709
|
+
if ('machine' in request.target) {
|
|
1710
|
+
if (!machine) return { status: 'refused', reason: 'No machine.' }
|
|
1711
|
+
machine = { ...machine, ...(role === null ? { role: undefined } : { role }) }
|
|
1712
|
+
await store.writeMachine(machine)
|
|
1713
|
+
logAudit({ event: 'role_set', ...roleAudit(from, 'machine', role) })
|
|
1714
|
+
emit({ type: 'role', target: 'machine', role, byMachine: byName, at: request.at })
|
|
1715
|
+
return { status: 'applied' }
|
|
1716
|
+
}
|
|
1717
|
+
const ref = request.target.sessionRef
|
|
1718
|
+
const local = host.listLocalSessions().find((s) => s.ref === ref)
|
|
1719
|
+
if (!host.setLocalRole || !local) {
|
|
1720
|
+
return { status: 'refused', reason: 'That session is not running here.' }
|
|
1721
|
+
}
|
|
1722
|
+
// A role from another machine reaches the model as context nobody here has read. A session that
|
|
1723
|
+
// skips approvals takes none: the person sets its role at that terminal.
|
|
1724
|
+
if (from !== selfId() && (local.bypass === true || local.mode === 'bypass')) {
|
|
1725
|
+
logAudit({ event: 'role_refused', ...roleAudit(from, ref, role) })
|
|
1726
|
+
return {
|
|
1727
|
+
status: 'refused',
|
|
1728
|
+
reason: 'That session skips approvals, so its role is set at its own terminal.',
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
const ok = host.setLocalRole(ref, role, { by: byName, at: request.at })
|
|
1732
|
+
if (!ok) return { status: 'refused', reason: 'That session is not running here.' }
|
|
1733
|
+
logAudit({ event: 'role_set', ...roleAudit(from, ref, role) })
|
|
1734
|
+
emit({ type: 'role', target: ref, role, byMachine: byName, at: request.at })
|
|
1735
|
+
return { status: 'applied' }
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
async function setRole(target: { machineId: string; sessionRef?: string }, role: string | null) {
|
|
1739
|
+
if (!machine) throw new NetworkError('off', 'The Namzu network is not running.')
|
|
1740
|
+
const clean = role === null ? null : sanitizeRole(role)
|
|
1741
|
+
if (role !== null && clean === undefined)
|
|
1742
|
+
throw new NetworkError('invalid', 'A role needs some words.')
|
|
1743
|
+
const at = clock.now()
|
|
1744
|
+
const body = target.sessionRef ? { sessionRef: target.sessionRef } : { machine: true as const }
|
|
1745
|
+
if (target.machineId === selfId()) {
|
|
1746
|
+
return (await handleRoleSet(
|
|
1747
|
+
{
|
|
1748
|
+
protocol: NET_PROTOCOL,
|
|
1749
|
+
op: 'role_set',
|
|
1750
|
+
target: body,
|
|
1751
|
+
role: clean ?? null,
|
|
1752
|
+
by: { machineName: selfName() },
|
|
1753
|
+
at,
|
|
1754
|
+
},
|
|
1755
|
+
selfId(),
|
|
1756
|
+
)) as { status: 'applied' | 'refused'; reason?: string }
|
|
1757
|
+
}
|
|
1758
|
+
if (!isMember(target.machineId))
|
|
1759
|
+
throw new NetworkError('not_member', 'That machine is not in your network.')
|
|
1760
|
+
const reply = StatusReplySchema.safeParse(
|
|
1761
|
+
await callMachine(target.machineId, {
|
|
1762
|
+
protocol: NET_PROTOCOL,
|
|
1763
|
+
op: 'role_set',
|
|
1764
|
+
target: body,
|
|
1765
|
+
role: clean ?? null,
|
|
1766
|
+
by: { machineName: selfName() },
|
|
1767
|
+
at,
|
|
1768
|
+
}),
|
|
1769
|
+
)
|
|
1770
|
+
if (!reply.success)
|
|
1771
|
+
throw new NetworkError('bad_frame', 'The other machine answered something unexpected.')
|
|
1772
|
+
logAudit({
|
|
1773
|
+
event: reply.data.status === 'applied' ? 'role_set' : 'role_refused',
|
|
1774
|
+
machine: who(target.machineId),
|
|
1775
|
+
session: target.sessionRef ?? 'machine',
|
|
1776
|
+
direction: 'out',
|
|
1777
|
+
decision: clean === null || clean === undefined ? 'clear' : 'set',
|
|
1778
|
+
...(clean ? { bytes: Buffer.byteLength(clean, 'utf8'), textHash: textHash(clean) } : {}),
|
|
1779
|
+
...(reply.data.reason ? { reason: reply.data.reason } : {}),
|
|
1780
|
+
})
|
|
1781
|
+
return reply.data
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// ─── mail ──────────────────────────────────────────────────────────────
|
|
1785
|
+
|
|
1786
|
+
async function voucherMode(machineId: string, sessionRef: string): Promise<string | undefined> {
|
|
1787
|
+
const p = peerState.get(machineId)
|
|
1788
|
+
const stale = !p || p.rosterAt === undefined || clock.now() - p.rosterAt > ROSTER_FRESH_MS
|
|
1789
|
+
if (stale) {
|
|
1790
|
+
try {
|
|
1791
|
+
const roster = RosterSchema.safeParse(
|
|
1792
|
+
await callMachine(machineId, { protocol: NET_PROTOCOL, op: 'roster' }),
|
|
1793
|
+
)
|
|
1794
|
+
if (roster.success) applyRoster(machineId, roster.data)
|
|
1795
|
+
} catch {
|
|
1796
|
+
// no pull possible: the mode stays unconfirmed
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
return peerState.get(machineId)?.sessions?.find((s) => s.ref === sessionRef)?.mode
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
function remember256(id: string): boolean {
|
|
1803
|
+
if (seenMail.includes(id)) return true
|
|
1804
|
+
seenMail.push(id)
|
|
1805
|
+
if (seenMail.length > 256) seenMail.shift()
|
|
1806
|
+
return false
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
async function handleDeliver(request: NetDeliverRequest, from: string): Promise<unknown> {
|
|
1810
|
+
const fromName = peerState.get(from)?.name ?? from.slice(0, 12)
|
|
1811
|
+
const target = host.listLocalSessions().find((s) => s.ref === request.to.sessionRef)
|
|
1812
|
+
const text = request.text
|
|
1813
|
+
const refuse = (reason: string) => {
|
|
1814
|
+
logAudit({
|
|
1815
|
+
event: 'mail_refused',
|
|
1816
|
+
direction: 'in',
|
|
1817
|
+
machine: who(from),
|
|
1818
|
+
session: request.to.sessionRef,
|
|
1819
|
+
reason,
|
|
1820
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
1821
|
+
textHash: textHash(text),
|
|
1822
|
+
})
|
|
1823
|
+
return { status: 'refused', reason }
|
|
1824
|
+
}
|
|
1825
|
+
if (!target) return refuse('That session is not running here.')
|
|
1826
|
+
const vouched = await voucherMode(from, request.from.sessionRef)
|
|
1827
|
+
const decision = decideMail({
|
|
1828
|
+
scope: 'remote',
|
|
1829
|
+
text,
|
|
1830
|
+
hops: request.hops,
|
|
1831
|
+
receiver: {
|
|
1832
|
+
mode: target.mode,
|
|
1833
|
+
bypass: target.bypass === true,
|
|
1834
|
+
accepting: target.acceptsMessages,
|
|
1835
|
+
setting: options.acceptMail?.() ?? 'members',
|
|
1836
|
+
},
|
|
1837
|
+
sender: { claimedMode: request.from.mode, vouchedMode: vouched },
|
|
1838
|
+
rateOk: mailBuckets.take(from),
|
|
1839
|
+
pairCount: pairs.record(`${from}:${request.from.sessionRef}>${request.to.sessionRef}`),
|
|
1840
|
+
})
|
|
1841
|
+
if (decision.action === 'refuse') return refuse(decision.reason)
|
|
1842
|
+
const mail: RemoteMail = {
|
|
1843
|
+
id: request.id,
|
|
1844
|
+
from: {
|
|
1845
|
+
machineId: from,
|
|
1846
|
+
machineName: fromName,
|
|
1847
|
+
sessionRef: request.from.sessionRef,
|
|
1848
|
+
sessionName: sanitizeName(request.from.sessionName, 80),
|
|
1849
|
+
mode: vouched ?? request.from.mode,
|
|
1850
|
+
},
|
|
1851
|
+
text,
|
|
1852
|
+
inReplyTo: request.inReplyTo,
|
|
1853
|
+
hops: request.hops,
|
|
1854
|
+
allowedOnce: false,
|
|
1855
|
+
}
|
|
1856
|
+
if (decision.action === 'hold') {
|
|
1857
|
+
const key = `${from}:${request.from.sessionRef}:${request.id}`
|
|
1858
|
+
if (remember256(key))
|
|
1859
|
+
return {
|
|
1860
|
+
status: heldQueue.list().some((e) => e.item.id === request.id) ? 'held' : 'queued',
|
|
1861
|
+
}
|
|
1862
|
+
const perSender = heldQueue.list().filter((e) => e.item.machineId === from).length
|
|
1863
|
+
if (perSender >= 4) return refuse('Too many messages from that machine are waiting here.')
|
|
1864
|
+
const perTerminal = heldQueue.list().filter((e) => e.item.toSessionRef === target.ref).length
|
|
1865
|
+
if (perTerminal >= 8) return refuse('Too many messages are waiting for that terminal.')
|
|
1866
|
+
const now = clock.now()
|
|
1867
|
+
const entry: HeldMail = {
|
|
1868
|
+
id: request.id,
|
|
1869
|
+
machineId: from,
|
|
1870
|
+
machineName: fromName,
|
|
1871
|
+
fromSessionRef: request.from.sessionRef,
|
|
1872
|
+
fromSessionName: mail.from.sessionName,
|
|
1873
|
+
fromMode: mail.from.mode,
|
|
1874
|
+
toSessionRef: target.ref,
|
|
1875
|
+
text,
|
|
1876
|
+
inReplyTo: request.inReplyTo,
|
|
1877
|
+
hops: request.hops,
|
|
1878
|
+
reason: decision.reason,
|
|
1879
|
+
heldAt: now,
|
|
1880
|
+
expiresAt: now + 10 * 60 * 1000,
|
|
1881
|
+
}
|
|
1882
|
+
if (!heldQueue.hold(request.id, entry))
|
|
1883
|
+
return refuse('Too many messages are waiting for this machine.')
|
|
1884
|
+
logAudit({
|
|
1885
|
+
event: 'mail_held',
|
|
1886
|
+
direction: 'in',
|
|
1887
|
+
machine: who(from),
|
|
1888
|
+
session: target.ref,
|
|
1889
|
+
reason: decision.reason,
|
|
1890
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
1891
|
+
textHash: textHash(text),
|
|
1892
|
+
})
|
|
1893
|
+
emit({ type: 'held', mail: entry })
|
|
1894
|
+
return { status: 'held', reason: decision.reason }
|
|
1895
|
+
}
|
|
1896
|
+
if (remember256(`${from}:${request.from.sessionRef}:${request.id}`)) return { status: 'queued' }
|
|
1897
|
+
const result = await host.deliverLocal(target.ref, mail)
|
|
1898
|
+
if (result.status === 'refused')
|
|
1899
|
+
return refuse(result.reason ?? 'That terminal declined the message.')
|
|
1900
|
+
logAudit({
|
|
1901
|
+
event: 'mail_accepted',
|
|
1902
|
+
direction: 'in',
|
|
1903
|
+
machine: who(from),
|
|
1904
|
+
session: target.ref,
|
|
1905
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
1906
|
+
textHash: textHash(text),
|
|
1907
|
+
})
|
|
1908
|
+
return { status: 'queued' }
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
async function notifySender(mail: HeldMail, outcome: NetOutcome, detail?: string): Promise<void> {
|
|
1912
|
+
try {
|
|
1913
|
+
await callMachine(mail.machineId, {
|
|
1914
|
+
protocol: NET_PROTOCOL,
|
|
1915
|
+
op: 'net_notice',
|
|
1916
|
+
about: { id: mail.id },
|
|
1917
|
+
outcome,
|
|
1918
|
+
...(detail ? { detail: detail.slice(0, 200) } : {}),
|
|
1919
|
+
from: { sessionRef: mail.toSessionRef },
|
|
1920
|
+
})
|
|
1921
|
+
} catch {
|
|
1922
|
+
// the sender is offline; it finds out when it looks
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
async function handleNotice(request: NetNoticeRequest, from: string): Promise<unknown> {
|
|
1927
|
+
const expected = sent.get(request.about.id)
|
|
1928
|
+
if (!expected || expected.machineId !== from) return { ok: false }
|
|
1929
|
+
if (request.outcome !== 'queued' && request.outcome !== 'held') sent.delete(request.about.id)
|
|
1930
|
+
const settled: Partial<Record<NetOutcome, AuditEntry['event']>> = {
|
|
1931
|
+
queued: 'mail_allowed',
|
|
1932
|
+
refused: 'mail_denied',
|
|
1933
|
+
expired: 'mail_expired',
|
|
1934
|
+
}
|
|
1935
|
+
const event = settled[request.outcome]
|
|
1936
|
+
if (event && event !== undefined)
|
|
1937
|
+
logAudit({
|
|
1938
|
+
event,
|
|
1939
|
+
direction: 'out',
|
|
1940
|
+
machine: who(from),
|
|
1941
|
+
session: expected.session,
|
|
1942
|
+
bytes: expected.bytes,
|
|
1943
|
+
textHash: expected.textHash,
|
|
1944
|
+
})
|
|
1945
|
+
emit({
|
|
1946
|
+
type: 'mail-outcome',
|
|
1947
|
+
id: request.about.id,
|
|
1948
|
+
outcome: request.outcome,
|
|
1949
|
+
machineId: from,
|
|
1950
|
+
detail: request.detail === undefined ? undefined : sanitizeName(request.detail, 200),
|
|
1951
|
+
})
|
|
1952
|
+
return { ok: true }
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
async function releaseHeld(id: string, allow: boolean): Promise<void> {
|
|
1956
|
+
const entry = heldQueue.release(id)
|
|
1957
|
+
if (!entry) throw new NetworkError('unknown_target', 'That message is no longer waiting.')
|
|
1958
|
+
const mail = entry.item
|
|
1959
|
+
if (!allow) {
|
|
1960
|
+
logAudit({
|
|
1961
|
+
event: 'mail_denied',
|
|
1962
|
+
direction: 'in',
|
|
1963
|
+
machine: who(mail.machineId),
|
|
1964
|
+
session: mail.toSessionRef,
|
|
1965
|
+
})
|
|
1966
|
+
emit({ type: 'held-resolved', id, result: 'denied' })
|
|
1967
|
+
await notifySender(mail, 'refused', 'The person at that terminal did not allow the message.')
|
|
1968
|
+
return
|
|
1969
|
+
}
|
|
1970
|
+
const result = await host.deliverLocal(mail.toSessionRef, {
|
|
1971
|
+
id: mail.id,
|
|
1972
|
+
from: {
|
|
1973
|
+
machineId: mail.machineId,
|
|
1974
|
+
machineName: mail.machineName,
|
|
1975
|
+
sessionRef: mail.fromSessionRef,
|
|
1976
|
+
sessionName: mail.fromSessionName,
|
|
1977
|
+
mode: mail.fromMode,
|
|
1978
|
+
},
|
|
1979
|
+
text: mail.text,
|
|
1980
|
+
inReplyTo: mail.inReplyTo,
|
|
1981
|
+
hops: mail.hops,
|
|
1982
|
+
allowedOnce: true,
|
|
1983
|
+
})
|
|
1984
|
+
if (result.status === 'refused') {
|
|
1985
|
+
logAudit({
|
|
1986
|
+
event: 'mail_denied',
|
|
1987
|
+
direction: 'in',
|
|
1988
|
+
machine: who(mail.machineId),
|
|
1989
|
+
session: mail.toSessionRef,
|
|
1990
|
+
reason: result.reason,
|
|
1991
|
+
})
|
|
1992
|
+
emit({ type: 'held-resolved', id, result: 'denied' })
|
|
1993
|
+
await notifySender(mail, 'refused', result.reason ?? 'That terminal declined the message.')
|
|
1994
|
+
return
|
|
1995
|
+
}
|
|
1996
|
+
logAudit({
|
|
1997
|
+
event: 'mail_allowed',
|
|
1998
|
+
direction: 'in',
|
|
1999
|
+
machine: who(mail.machineId),
|
|
2000
|
+
session: mail.toSessionRef,
|
|
2001
|
+
})
|
|
2002
|
+
emit({ type: 'held-resolved', id, result: 'allowed' })
|
|
2003
|
+
await notifySender(mail, 'queued')
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
async function send(
|
|
2007
|
+
target: { machineId: string; sessionRef: string },
|
|
2008
|
+
text: string,
|
|
2009
|
+
from: { sessionRef: string; sessionName: string; mode: string },
|
|
2010
|
+
opts: { inReplyTo?: string; hops?: number } = {},
|
|
2011
|
+
) {
|
|
2012
|
+
if (!machine) throw new NetworkError('off', 'The Namzu network is not running.')
|
|
2013
|
+
if (!isMember(target.machineId) || target.machineId === selfId())
|
|
2014
|
+
throw new NetworkError('not_member', 'That machine is not in your network.')
|
|
2015
|
+
if (text.trim().length === 0) throw new NetworkError('invalid', 'The message is empty.')
|
|
2016
|
+
if (Buffer.byteLength(text, 'utf8') > MAX_NET_TEXT_BYTES)
|
|
2017
|
+
throw new NetworkError('invalid', 'The message is too long.')
|
|
2018
|
+
const hops = opts.hops ?? 0
|
|
2019
|
+
if (hops > MAX_HOPS)
|
|
2020
|
+
throw new NetworkError('invalid', 'This conversation between sessions is going in circles.')
|
|
2021
|
+
const id = randomUUID()
|
|
2022
|
+
const reply = DeliverReplyParse.safeParse(
|
|
2023
|
+
await callMachine(target.machineId, {
|
|
2024
|
+
protocol: NET_PROTOCOL,
|
|
2025
|
+
op: 'net_deliver',
|
|
2026
|
+
id,
|
|
2027
|
+
to: { sessionRef: target.sessionRef },
|
|
2028
|
+
from: {
|
|
2029
|
+
sessionRef: from.sessionRef,
|
|
2030
|
+
sessionName: sanitizeName(from.sessionName, 80),
|
|
2031
|
+
mode: from.mode,
|
|
2032
|
+
kind: 'tui',
|
|
2033
|
+
},
|
|
2034
|
+
text,
|
|
2035
|
+
...(opts.inReplyTo ? { inReplyTo: opts.inReplyTo } : {}),
|
|
2036
|
+
hops,
|
|
2037
|
+
}),
|
|
2038
|
+
)
|
|
2039
|
+
if (!reply.success)
|
|
2040
|
+
throw new NetworkError('bad_frame', 'The other machine answered something unexpected.')
|
|
2041
|
+
const bytes = Buffer.byteLength(text, 'utf8')
|
|
2042
|
+
const hash = textHash(text)
|
|
2043
|
+
logAudit({
|
|
2044
|
+
event:
|
|
2045
|
+
reply.data.status === 'refused'
|
|
2046
|
+
? 'mail_refused'
|
|
2047
|
+
: reply.data.status === 'held'
|
|
2048
|
+
? 'mail_held'
|
|
2049
|
+
: 'mail_accepted',
|
|
2050
|
+
direction: 'out',
|
|
2051
|
+
machine: who(target.machineId),
|
|
2052
|
+
session: target.sessionRef,
|
|
2053
|
+
bytes,
|
|
2054
|
+
textHash: hash,
|
|
2055
|
+
...(reply.data.reason ? { reason: reply.data.reason } : {}),
|
|
2056
|
+
})
|
|
2057
|
+
if (reply.data.status !== 'refused') {
|
|
2058
|
+
sent.set(id, {
|
|
2059
|
+
machineId: target.machineId,
|
|
2060
|
+
at: clock.now(),
|
|
2061
|
+
session: target.sessionRef,
|
|
2062
|
+
bytes,
|
|
2063
|
+
textHash: hash,
|
|
2064
|
+
})
|
|
2065
|
+
if (sent.size > 256) sent.delete(sent.keys().next().value as string)
|
|
2066
|
+
}
|
|
2067
|
+
return { id, ...reply.data }
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
// ─── roster view ───────────────────────────────────────────────────────
|
|
2071
|
+
|
|
2072
|
+
async function roster(opts: { refresh?: boolean } = {}): Promise<RosterView> {
|
|
2073
|
+
if (!machine) return { machines: [] }
|
|
2074
|
+
if (opts.refresh !== false) {
|
|
2075
|
+
await Promise.all(
|
|
2076
|
+
[...(view?.members.keys() ?? [])]
|
|
2077
|
+
.filter((id) => id !== selfId())
|
|
2078
|
+
.map(async (id) => {
|
|
2079
|
+
try {
|
|
2080
|
+
const r = RosterSchema.safeParse(
|
|
2081
|
+
await callMachine(id, { protocol: NET_PROTOCOL, op: 'roster' }),
|
|
2082
|
+
)
|
|
2083
|
+
if (r.success) applyRoster(id, r.data)
|
|
2084
|
+
} catch {
|
|
2085
|
+
// shown offline below
|
|
2086
|
+
}
|
|
2087
|
+
}),
|
|
2088
|
+
)
|
|
2089
|
+
}
|
|
2090
|
+
const now = clock.now()
|
|
2091
|
+
const own = buildSelfRoster()
|
|
2092
|
+
const machines: RosterMachineView[] = [
|
|
2093
|
+
{
|
|
2094
|
+
machineId: selfId(),
|
|
2095
|
+
name: selfName(),
|
|
2096
|
+
status: 'self',
|
|
2097
|
+
role: own.machine.role,
|
|
2098
|
+
sessions: own.sessions,
|
|
2099
|
+
},
|
|
2100
|
+
]
|
|
2101
|
+
for (const id of [...(view?.members.keys() ?? [])].filter((m) => m !== selfId())) {
|
|
2102
|
+
const p = peerState.get(id)
|
|
2103
|
+
const online =
|
|
2104
|
+
p?.online === true &&
|
|
2105
|
+
p.rosterAt !== undefined &&
|
|
2106
|
+
now - (p.seenAt ?? 0) < ROSTER_FRESH_MS * 4
|
|
2107
|
+
machines.push({
|
|
2108
|
+
machineId: id,
|
|
2109
|
+
name: p?.name ?? id.slice(0, 12),
|
|
2110
|
+
status: online || (opts.refresh === false && p?.online === true) ? 'online' : 'offline',
|
|
2111
|
+
seenAt: p?.seenAt,
|
|
2112
|
+
role: p?.role,
|
|
2113
|
+
sessions: p?.sessions
|
|
2114
|
+
? online
|
|
2115
|
+
? p.sessions
|
|
2116
|
+
: offlineSessions(p.sessions, p.rosterAt ?? 0, now)
|
|
2117
|
+
: [],
|
|
2118
|
+
})
|
|
2119
|
+
}
|
|
2120
|
+
return { machines }
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
// ─── lifecycle ─────────────────────────────────────────────────────────
|
|
2124
|
+
|
|
2125
|
+
async function stopNetworking(): Promise<void> {
|
|
2126
|
+
cancelBrowse?.()
|
|
2127
|
+
cancelRecheck?.()
|
|
2128
|
+
cancelBrowse = undefined
|
|
2129
|
+
cancelRecheck = undefined
|
|
2130
|
+
for (const off of offDiscovery.splice(0)) off()
|
|
2131
|
+
joiners.clear()
|
|
2132
|
+
// Held mail lives in the terminal that runs the network: when it stops, each sender is told.
|
|
2133
|
+
const stillHeld = heldQueue.list().map((e) => e.item)
|
|
2134
|
+
heldQueue.clear()
|
|
2135
|
+
await Promise.allSettled(
|
|
2136
|
+
stillHeld.map((mail) =>
|
|
2137
|
+
notifySender(mail, 'expired', 'The terminal holding the message was closed.'),
|
|
2138
|
+
),
|
|
2139
|
+
)
|
|
2140
|
+
for (const c of pendingConns.values()) c.close()
|
|
2141
|
+
pendingConns.clear()
|
|
2142
|
+
await discovery.close().catch(() => undefined)
|
|
2143
|
+
await Promise.all(netListeners.splice(0).map((l) => l.close()))
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
async function close(): Promise<void> {
|
|
2147
|
+
if (closed) return
|
|
2148
|
+
closed = true
|
|
2149
|
+
const wasOn = state !== 'off' && state !== 'removed'
|
|
2150
|
+
await stopNetworking()
|
|
2151
|
+
if (wasOn) logAudit({ event: 'network_off' })
|
|
2152
|
+
await audit.append({ at: clock.now(), event: 'network_off' }).catch(() => undefined)
|
|
2153
|
+
started = false
|
|
2154
|
+
setState('off')
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
return {
|
|
2158
|
+
start,
|
|
2159
|
+
status: () => ({
|
|
2160
|
+
state,
|
|
2161
|
+
reason: stateReason,
|
|
2162
|
+
machine:
|
|
2163
|
+
machine && key
|
|
2164
|
+
? { id: key.machineId, name: machine.name ?? selfName(), role: machine.role }
|
|
2165
|
+
: undefined,
|
|
2166
|
+
netId,
|
|
2167
|
+
members: view?.members.size ?? 0,
|
|
2168
|
+
port,
|
|
2169
|
+
pendingJoins: joiners.list().length,
|
|
2170
|
+
held: heldQueue.size,
|
|
2171
|
+
nearbyNetworks: nearby.size,
|
|
2172
|
+
}),
|
|
2173
|
+
identity: () => (key && machine ? { machineId: key.machineId, name: selfName() } : undefined),
|
|
2174
|
+
on(listener) {
|
|
2175
|
+
listeners.add(listener)
|
|
2176
|
+
return () => listeners.delete(listener)
|
|
2177
|
+
},
|
|
2178
|
+
roster,
|
|
2179
|
+
members: () =>
|
|
2180
|
+
[...(view?.members.keys() ?? [])].map((id) => ({
|
|
2181
|
+
machineId: id,
|
|
2182
|
+
name: id === key?.machineId ? selfName() : (peerState.get(id)?.name ?? id.slice(0, 12)),
|
|
2183
|
+
self: id === key?.machineId,
|
|
2184
|
+
})),
|
|
2185
|
+
pendingJoins: () => joiners.list(),
|
|
2186
|
+
async allow(q, opts = {}) {
|
|
2187
|
+
if (opts.trust) {
|
|
2188
|
+
const entry = joiners.find(q)
|
|
2189
|
+
if (!entry) throw new NetworkError('unknown_target', 'No request to join matches that.')
|
|
2190
|
+
if (!(await networkOf(entry.sourceAddr)))
|
|
2191
|
+
throw new NetworkError(
|
|
2192
|
+
'invalid',
|
|
2193
|
+
'This network cannot be recognised (its gateway cannot be read), so it cannot be trusted.',
|
|
2194
|
+
)
|
|
2195
|
+
}
|
|
2196
|
+
const entry = await decideJoin(q, 'allow')
|
|
2197
|
+
if (opts.trust)
|
|
2198
|
+
await trustNetwork(
|
|
2199
|
+
entry.sourceAddr,
|
|
2200
|
+
typeof opts.trust === 'string' ? opts.trust : undefined,
|
|
2201
|
+
)
|
|
2202
|
+
return entry
|
|
2203
|
+
},
|
|
2204
|
+
networkOf,
|
|
2205
|
+
trustedNetworks: trustedList,
|
|
2206
|
+
trustNetwork,
|
|
2207
|
+
untrustNetwork,
|
|
2208
|
+
renameNetwork,
|
|
2209
|
+
deny: (q) => decideJoin(q, 'deny'),
|
|
2210
|
+
async remove(machineId, opts = {}) {
|
|
2211
|
+
if (!key || !netId || !view)
|
|
2212
|
+
throw new NetworkError('no_network', 'This machine is not in a network.')
|
|
2213
|
+
if (!view.members.has(machineId))
|
|
2214
|
+
throw new NetworkError('unknown_target', 'That machine is not in your network.')
|
|
2215
|
+
const before = new Set(view.members.keys())
|
|
2216
|
+
const revocation = signRevocation(key, netId, machineId, opts.cascade === true, clock.now())
|
|
2217
|
+
await mergeIn([], [revocation])
|
|
2218
|
+
const removedNow = [...before].filter((id) => !view?.members.has(id))
|
|
2219
|
+
// Tell everyone, the removed machines too, so they learn it and reset.
|
|
2220
|
+
await pushSync()
|
|
2221
|
+
return { removed: removedNow }
|
|
2222
|
+
},
|
|
2223
|
+
admittedBy: (id) => (view ? admittedBy(view, id) : []),
|
|
2224
|
+
async rename(name) {
|
|
2225
|
+
const clean = sanitizeName(name)
|
|
2226
|
+
if (clean.length === 0 || !machine)
|
|
2227
|
+
throw new NetworkError('invalid', 'A machine needs a name.')
|
|
2228
|
+
machine = { ...machine, name: clean }
|
|
2229
|
+
await store.writeMachine(machine)
|
|
2230
|
+
logAudit({ event: 'machine_renamed' })
|
|
2231
|
+
void Promise.all(
|
|
2232
|
+
[...(view?.members.keys() ?? [])]
|
|
2233
|
+
.filter((id) => id !== selfId())
|
|
2234
|
+
.map((id) =>
|
|
2235
|
+
callMachine(id, {
|
|
2236
|
+
protocol: NET_PROTOCOL,
|
|
2237
|
+
op: 'hello',
|
|
2238
|
+
machineName: clean,
|
|
2239
|
+
addresses: ourHostPorts().slice(0, 8),
|
|
2240
|
+
protocolMax: 1,
|
|
2241
|
+
}).catch(() => undefined),
|
|
2242
|
+
),
|
|
2243
|
+
)
|
|
2244
|
+
},
|
|
2245
|
+
setRole,
|
|
2246
|
+
send,
|
|
2247
|
+
resolve: (text) => {
|
|
2248
|
+
const machines: RosterMachineView[] = [
|
|
2249
|
+
{
|
|
2250
|
+
machineId: selfId(),
|
|
2251
|
+
name: selfName(),
|
|
2252
|
+
status: 'self',
|
|
2253
|
+
sessions: buildSelfRoster().sessions,
|
|
2254
|
+
},
|
|
2255
|
+
]
|
|
2256
|
+
for (const [id, p] of peerState) {
|
|
2257
|
+
if (id === selfId() || !isMember(id)) continue
|
|
2258
|
+
machines.push({
|
|
2259
|
+
machineId: id,
|
|
2260
|
+
name: p.name,
|
|
2261
|
+
status: p.online ? 'online' : 'offline',
|
|
2262
|
+
sessions: p.sessions ?? [],
|
|
2263
|
+
})
|
|
2264
|
+
}
|
|
2265
|
+
return resolveSessionTarget({ machines }, text)
|
|
2266
|
+
},
|
|
2267
|
+
async add(text) {
|
|
2268
|
+
const h = parseHostPort(text)
|
|
2269
|
+
if (!tls) throw new NetworkError('off', 'The Namzu network is not running.')
|
|
2270
|
+
if (!view || view.members.size <= 1) {
|
|
2271
|
+
void join(h).catch(() => undefined)
|
|
2272
|
+
return 'join-requested'
|
|
2273
|
+
}
|
|
2274
|
+
const client = await connectTo(h)
|
|
2275
|
+
try {
|
|
2276
|
+
await greet(client, h)
|
|
2277
|
+
} finally {
|
|
2278
|
+
client.close()
|
|
2279
|
+
}
|
|
2280
|
+
return 'added'
|
|
2281
|
+
},
|
|
2282
|
+
join,
|
|
2283
|
+
cancelJoin,
|
|
2284
|
+
nearbyNetworks: () =>
|
|
2285
|
+
[...nearby.entries()].flatMap(([id, list]) =>
|
|
2286
|
+
list.slice(0, 1).map((e) => ({ netId: id, host: e.host, port: e.port })),
|
|
2287
|
+
),
|
|
2288
|
+
held: () => heldQueue.list().map((e) => e.item),
|
|
2289
|
+
allowHeld: (id) => releaseHeld(id, true),
|
|
2290
|
+
denyHeld: (id) => releaseHeld(id, false),
|
|
2291
|
+
async reportDelivered(machineId, mailId, fromSessionRef) {
|
|
2292
|
+
await callMachine(machineId, {
|
|
2293
|
+
protocol: NET_PROTOCOL,
|
|
2294
|
+
op: 'net_notice',
|
|
2295
|
+
about: { id: mailId },
|
|
2296
|
+
outcome: 'delivered',
|
|
2297
|
+
from: { sessionRef: fromSessionRef },
|
|
2298
|
+
}).catch(() => undefined)
|
|
2299
|
+
},
|
|
2300
|
+
close,
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
export { MAX_NAME_LENGTH }
|