granttap-mcp 0.8.129 → 0.8.131
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/apps/bridge/src/monitor/support/runtime.ts +1 -1
- package/apps/bridge/src/reply/index.ts +15 -2
- package/apps/bridge/src/reply/native-completion.ts +35 -0
- package/apps/bridge/src/session-catalog/README.md +7 -1
- package/apps/bridge/src/session-catalog/observed-state.ts +18 -5
- package/apps/bridge/src/session-catalog/open-chat-updates.ts +4 -11
- package/apps/bridge/src/task-dispatch/worker/monitor.ts +4 -2
- package/apps/bridge/src/task-dispatch/worker/readiness.ts +1 -1
- package/cursor-plugin/README.md +1 -1
- package/cursor-plugin/mcp.json +1 -1
- package/cursor-plugin/stdio-bootstrap.cjs +1 -1
- package/package.json +1 -1
- package/packages/core/crypto.ts +4 -2
- package/packages/core/relay-client.ts +2 -1
- package/packages/core/shared-box/README.md +15 -0
- package/packages/core/shared-box/index.ts +39 -0
|
@@ -243,7 +243,7 @@ export function startSessionMonitor(client: RelayClient): SessionMonitor {
|
|
|
243
243
|
publish: openChatUpdates({
|
|
244
244
|
catalog: () => publishedCatalog(client), subscriptions,
|
|
245
245
|
active: () => !closed && client.isConnected && leadership.acquire(),
|
|
246
|
-
publish: (id, status) => publishSessionEvents(client, id, status),
|
|
246
|
+
publish: (id, status) => publishSessionEvents(client, id, status, undefined, {history: true}),
|
|
247
247
|
}),
|
|
248
248
|
});
|
|
249
249
|
|
|
@@ -15,6 +15,7 @@ import { abortProcesses, runProcess } from "./process";
|
|
|
15
15
|
import { routingPrompt } from "./payload/routing";
|
|
16
16
|
import type { DeliveryOptions, ReplyResult } from "./payload/types";
|
|
17
17
|
import { deliveryIntent } from './payload/identity';
|
|
18
|
+
import {NativeTurnCompletions, type NativeCompletionProof} from './native-completion';
|
|
18
19
|
import {
|
|
19
20
|
runCursorNew,
|
|
20
21
|
runCursorResume,
|
|
@@ -34,11 +35,14 @@ export function resolveAgentWorkspace(cwd: string | undefined, agent: CodingAgen
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
const inFlight = new Map<string, Promise<ReplyResult | null>>();
|
|
38
|
+
const physicalRuns = new Set<Promise<ReplyResult>>();
|
|
39
|
+
const nativeCompletions = new NativeTurnCompletions();
|
|
37
40
|
|
|
38
41
|
export function isDeliveryInFlight(sessionId: string): boolean { return inFlight.has(sessionId); }
|
|
39
42
|
|
|
40
43
|
/** Acknowledging a message does not finish the provider turn or permit a runtime handoff. */
|
|
41
|
-
export function hasPendingDeliveries(): boolean { return inFlight.size > 0; }
|
|
44
|
+
export function hasPendingDeliveries(): boolean { return inFlight.size > 0 || physicalRuns.size > 0; }
|
|
45
|
+
export const completeObservedNativeTurn = (key: string, proof: NativeCompletionProof) => nativeCompletions.complete(key, proof);
|
|
42
46
|
|
|
43
47
|
/** Request a stop for owned processes; confirmation arrives only on process exit. */
|
|
44
48
|
export function stopDeliveries(sessionId: string): number {
|
|
@@ -164,7 +168,14 @@ export function createGrokSession(
|
|
|
164
168
|
|
|
165
169
|
function queued(key: string, run: () => Promise<ReplyResult>): Promise<ReplyResult> {
|
|
166
170
|
const previous = inFlight.get(key) ?? Promise.resolve(null);
|
|
167
|
-
const next = previous.then(
|
|
171
|
+
const next = previous.then(async () => {
|
|
172
|
+
const native = nativeCompletions.begin(key);
|
|
173
|
+
const physical = Promise.resolve().then(run);
|
|
174
|
+
physicalRuns.add(physical);
|
|
175
|
+
void physical.then(() => physicalRuns.delete(physical), () => physicalRuns.delete(physical));
|
|
176
|
+
try { return await Promise.race([physical, native.result]); }
|
|
177
|
+
finally { native.close(); }
|
|
178
|
+
});
|
|
168
179
|
const settled = next.finally(() => {
|
|
169
180
|
if (inFlight.get(key) === tracked) inFlight.delete(key);
|
|
170
181
|
});
|
|
@@ -194,6 +205,8 @@ function runClaude(
|
|
|
194
205
|
timeoutMs: number,
|
|
195
206
|
options: DeliveryOptions,
|
|
196
207
|
): Promise<ReplyResult> {
|
|
208
|
+
nativeCompletions.bind(session.sessionId, text, key => localTaskTransfers()
|
|
209
|
+
.nativeSession({...session, sessionId: key}).sessionId);
|
|
197
210
|
const disabled = loadRuntimeConfig().sessionMcpDisabled[session.sessionId] ?? [];
|
|
198
211
|
const mcpArgs = disabled.length === 0
|
|
199
212
|
? []
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import type {ReplyResult} from './payload/types';
|
|
3
|
+
|
|
4
|
+
export const nativePromptDigest = (text: string) => createHash('sha256').update(text).digest('hex');
|
|
5
|
+
export type NativeCompletionProof = {nativeSessionId: string; promptAt: number; completedAt: number;
|
|
6
|
+
promptDigests: string[]; text: string};
|
|
7
|
+
type Run = {key: string; startedAt: number; nativeId?: string; digest?: string;
|
|
8
|
+
resolve: (result: ReplyResult) => void; result: Promise<ReplyResult>; completed: boolean};
|
|
9
|
+
|
|
10
|
+
/** Match this invocation's exact native prompt before releasing its confirmed final answer. */
|
|
11
|
+
export class NativeTurnCompletions {
|
|
12
|
+
private readonly runs = new Map<string, Run>();
|
|
13
|
+
constructor(private readonly now = Date.now) {}
|
|
14
|
+
begin(key: string) {
|
|
15
|
+
let resolve!: Run['resolve'];
|
|
16
|
+
const result = new Promise<ReplyResult>(done => {resolve = done});
|
|
17
|
+
const run: Run = {key, startedAt: this.now(), resolve, result, completed: false};
|
|
18
|
+
this.runs.set(key, run);
|
|
19
|
+
return {result, close: () => {if (this.runs.get(key) === run) this.runs.delete(key)}};
|
|
20
|
+
}
|
|
21
|
+
bind(nativeId: string, prompt: string, nativeForKey: (key: string) => string) {
|
|
22
|
+
const run = [...this.runs.values()].find(item => !item.nativeId && nativeForKey(item.key) === nativeId);
|
|
23
|
+
if (run) {run.nativeId = nativeId; run.digest = nativePromptDigest(prompt)}
|
|
24
|
+
}
|
|
25
|
+
complete(key: string, proof: NativeCompletionProof): boolean {
|
|
26
|
+
const run = this.runs.get(key);
|
|
27
|
+
if (!run || run.completed || run.nativeId !== proof.nativeSessionId || !run.digest
|
|
28
|
+
|| !proof.promptDigests.includes(run.digest) || proof.promptAt < run.startedAt
|
|
29
|
+
|| proof.completedAt < proof.promptAt || proof.completedAt > this.now() + 5_000
|
|
30
|
+
|| !proof.text.trim()) return false;
|
|
31
|
+
run.completed = true;
|
|
32
|
+
run.resolve({ok: true, text: proof.text, delivery: 'native'});
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -33,7 +33,7 @@ readers. Checkout observations are scoped to one asynchronous scan, so unrelated
|
|
|
33
33
|
requests cannot inherit an old directory result. Socket recovery immediately
|
|
34
34
|
republishes the current catalog instead of waiting for the next periodic tick.
|
|
35
35
|
|
|
36
|
-
Open
|
|
36
|
+
Open chats follow a separate two-second loop of known native sources.
|
|
37
37
|
Only changed source revisions send encrypted transcript heads; reads and sends
|
|
38
38
|
remain single-flight and bounded to eight chats per pass. Claude end-turn and
|
|
39
39
|
Codex turn events update execution state immediately after observation. The same
|
|
@@ -43,3 +43,9 @@ Full discoveries recheck known native execution state immediately before sending
|
|
|
43
43
|
their catalog, so a scan started during a turn cannot restore stale Working after
|
|
44
44
|
an independently delivered completion. Runtime handoff also waits for owned
|
|
45
45
|
provider turns to settle, including work already acknowledged to the phone.
|
|
46
|
+
|
|
47
|
+
Fast open-chat heads use bounded native root pages. Closed chats and child
|
|
48
|
+
conversations remain on their independent refresh/request paths. A Claude final
|
|
49
|
+
can finish its matched logical turn while its physical CLI drains background
|
|
50
|
+
work: native identity, exact routed prompt hash and prompt/final timestamps must
|
|
51
|
+
all match. Physical processes remain tracked for Stop and runtime handoff.
|
|
@@ -11,10 +11,12 @@ import {observeCodexTurn,codexTurnState,type CodexTurnClock} from '../sessions/s
|
|
|
11
11
|
import {ts} from '../sessions/support/common';
|
|
12
12
|
import {grokResumeActivity} from '../providers/grok-activity';
|
|
13
13
|
import {cursorConversationSession} from '../sessions/cursor';
|
|
14
|
+
import {nativePromptDigest, type NativeCompletionProof} from '../reply/native-completion';
|
|
14
15
|
|
|
15
|
-
type NativeClock={revision:string;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock
|
|
16
|
+
type NativeClock={revision:string;identity:string;bytes:number;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock;
|
|
17
|
+
promptAt:number;promptDigests:string[];completion?:NativeCompletionProof};
|
|
16
18
|
const clocks=new Map<string,NativeClock>();
|
|
17
|
-
export type SessionObservation={session:SessionInfo;revision:string};
|
|
19
|
+
export type SessionObservation={session:SessionInfo;revision:string;completion?:NativeCompletionProof};
|
|
18
20
|
|
|
19
21
|
/** Discovery may have started before an open chat finished its turn. Recheck before publication. */
|
|
20
22
|
export function refreshObservedCatalog(status: SessionsStatus): SessionsStatus {
|
|
@@ -47,12 +49,22 @@ export function observeSessionExecution(input:SessionInfo):SessionObservation|un
|
|
|
47
49
|
let clock=clocks.get(key);
|
|
48
50
|
if(clock?.revision!==revision){
|
|
49
51
|
const window=previousNativeLines(path,native.sessionId);if(!window)return;
|
|
50
|
-
|
|
52
|
+
const identity = `${stat.dev}:${stat.ino}`;
|
|
53
|
+
const append = clock?.identity === identity && stat.size > clock.bytes;
|
|
54
|
+
clock={revision,identity,bytes:stat.size,lastActivityAt:0,claude:append?{...clock!.claude}:{},codex:{},
|
|
55
|
+
promptAt:append?clock!.promptAt:0,promptDigests:append?clock!.promptDigests:[],completion:append?clock!.completion:undefined};
|
|
51
56
|
for(const line of window.lines){
|
|
52
57
|
let row;try{row=JSON.parse(line.text)}catch{continue}
|
|
53
58
|
if(row.isSidechain===true||row.sessionId&&row.sessionId!==native.sessionId)continue;
|
|
54
59
|
clock.lastActivityAt=Math.max(clock.lastActivityAt,ts(row.timestamp));
|
|
55
|
-
if(native.agent==='claude')
|
|
60
|
+
if(native.agent==='claude'){
|
|
61
|
+
observeClaudeTurn(row,clock.claude);
|
|
62
|
+
const content=row.message?.content;
|
|
63
|
+
const texts=typeof content==='string'?[content]:Array.isArray(content)?content.filter(b=>b?.type==='text'&&typeof b.text==='string').map(b=>b.text):[];
|
|
64
|
+
if(row.type==='user'&&texts.length){clock.promptAt=ts(row.timestamp);clock.promptDigests=[...texts,texts.join('\n')].map(nativePromptDigest)}
|
|
65
|
+
if(row.type==='assistant'&&clock.claude.turnEnded)clock.completion={nativeSessionId:native.sessionId,
|
|
66
|
+
promptAt:clock.promptAt,promptDigests:clock.promptDigests,completedAt:ts(row.timestamp),text:texts.join('\n')};
|
|
67
|
+
}else observeCodexTurn(row,clock.codex);
|
|
56
68
|
}
|
|
57
69
|
clocks.delete(key);clocks.set(key,clock);
|
|
58
70
|
while(clocks.size>256)clocks.delete(clocks.keys().next().value!);
|
|
@@ -60,6 +72,7 @@ export function observeSessionExecution(input:SessionInfo):SessionObservation|un
|
|
|
60
72
|
const at=Math.max(input.lastActivityAt,clock!.lastActivityAt);
|
|
61
73
|
const state=native.agent==='claude'?claudeTurnState(clock!.claude,at,input.state)
|
|
62
74
|
:clock!.codex.startedAt||clock!.codex.endedAt?codexTurnState(clock!.codex,at):input.state;
|
|
63
|
-
return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}
|
|
75
|
+
return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`,
|
|
76
|
+
...(native.agent==='claude'&&clock!.claude.turnEnded&&clock!.completion?{completion:clock!.completion}:{})};
|
|
64
77
|
}catch{return;}
|
|
65
78
|
}
|
|
@@ -13,26 +13,19 @@ export function openChatUpdates(options: {
|
|
|
13
13
|
}): () => Promise<void> {
|
|
14
14
|
const revisions = new Map<string, string>();
|
|
15
15
|
const observe = options.observe ?? observeSessionExecution;
|
|
16
|
-
let cursor = 0,
|
|
16
|
+
let cursor = 0, running = false;
|
|
17
17
|
return async () => {
|
|
18
18
|
if (running || !options.active()) return;
|
|
19
19
|
const status = options.catalog();
|
|
20
20
|
if (!status) return;
|
|
21
21
|
const known = new Map([...status.sessions, ...(status.history ?? [])]
|
|
22
22
|
.map(session => [session.sessionId, session]));
|
|
23
|
-
const ids = [...
|
|
24
|
-
...status.sessions.filter(session => session.state === 'working').map(session => session.sessionId)])]
|
|
25
|
-
.filter(id => known.has(id));
|
|
23
|
+
const ids = [...options.subscriptions].filter(id => known.has(id));
|
|
26
24
|
const activeIds = new Set(ids);
|
|
27
25
|
for (const id of revisions.keys()) if (!activeIds.has(id)) revisions.delete(id);
|
|
28
26
|
if (!ids.length) return;
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
const selected = Array.from({length: Math.min(8, opened.length)}, (_, offset) => opened[(openCursor + offset) % opened.length]!);
|
|
32
|
-
openCursor = opened.length ? (openCursor + selected.length) % opened.length : 0;
|
|
33
|
-
const remaining = Math.min(8 - selected.length, background.length);
|
|
34
|
-
selected.push(...Array.from({length: remaining}, (_, offset) => background[(cursor + offset) % background.length]!));
|
|
35
|
-
cursor = background.length ? (cursor + remaining) % background.length : 0;
|
|
27
|
+
const selected = Array.from({length: Math.min(8, ids.length)}, (_, offset) => ids[(cursor + offset) % ids.length]!);
|
|
28
|
+
cursor = (cursor + selected.length) % ids.length;
|
|
36
29
|
running = true;
|
|
37
30
|
try {
|
|
38
31
|
for (const id of selected) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import type { PeerConfig, RelayClient } from '../../../../../packages/core/relay-client';
|
|
3
3
|
import { configDir, isSessionPaused } from '../../config';
|
|
4
|
-
import { isDeliveryInFlight } from '../../reply';
|
|
4
|
+
import { completeObservedNativeTurn, isDeliveryInFlight } from '../../reply';
|
|
5
5
|
import { publishedCatalog } from '../../session-catalog';
|
|
6
6
|
import { handleUserMessage } from '../../monitor/handlers/user-message';
|
|
7
7
|
import { handleTaskCreate } from '../../monitor/handlers/task-create';
|
|
@@ -43,7 +43,9 @@ export function startTaskDispatchMonitor(input: {
|
|
|
43
43
|
const catalog = publishedCatalog(input.client);
|
|
44
44
|
const session = [...(catalog?.sessions ?? []), ...(catalog?.history ?? [])]
|
|
45
45
|
.find(item => item.sessionId === job.sessionId);
|
|
46
|
-
const
|
|
46
|
+
const native = dispatchSessionObservation(session, catalog?.generatedAt);
|
|
47
|
+
if (job.sessionId && native.completion) completeObservedNativeTurn(job.sessionId, native.completion);
|
|
48
|
+
const observation = { ...native,
|
|
47
49
|
inFlight: isDeliveryInFlight(job.sessionId ?? `__new_${job.operation.agent ?? 'codex'}_task__`),
|
|
48
50
|
paused: !!job.sessionId && isSessionPaused(job.sessionId) };
|
|
49
51
|
const ready = taskDispatchReady(job, observation);
|
|
@@ -5,7 +5,7 @@ import { observeSessionExecution } from '../../session-catalog/observed-state';
|
|
|
5
5
|
export function dispatchSessionObservation(session: SessionInfo | undefined, generatedAt?: number) {
|
|
6
6
|
const fresh = session && observeSessionExecution(session);
|
|
7
7
|
return { session: fresh?.session ?? session, generatedAt: fresh ? Date.now() : generatedAt,
|
|
8
|
-
nativeState: fresh?.session.state };
|
|
8
|
+
nativeState: fresh?.session.state, completion: fresh?.completion };
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
/** Manual release bypasses busy state only. Pause, native admission and policy still win. */
|
package/cursor-plugin/README.md
CHANGED
|
@@ -10,7 +10,7 @@ keeps each phone response tied to the exact originating chat and prompt.
|
|
|
10
10
|
Install the supported CLI on this computer, then run:
|
|
11
11
|
|
|
12
12
|
```bash
|
|
13
|
-
npm install -g granttap-mcp@0.8.
|
|
13
|
+
npm install -g granttap-mcp@0.8.131
|
|
14
14
|
granttap setup
|
|
15
15
|
granttap status
|
|
16
16
|
```
|
package/cursor-plugin/mcp.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"command": "node",
|
|
5
5
|
"args": [
|
|
6
6
|
"-e",
|
|
7
|
-
"\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.
|
|
7
|
+
"\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.131\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
|
|
8
8
|
]
|
|
9
9
|
}
|
|
10
10
|
}
|
|
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
|
|
|
7
7
|
const { existsSync } = require("node:fs");
|
|
8
8
|
const { delimiter, dirname, join } = require("node:path");
|
|
9
9
|
|
|
10
|
-
const PACKAGE = "granttap-mcp@0.8.
|
|
10
|
+
const PACKAGE = "granttap-mcp@0.8.131";
|
|
11
11
|
const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
|
|
12
12
|
const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
|
|
13
13
|
? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
|
package/package.json
CHANGED
package/packages/core/crypto.ts
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
* QR code scanned by the phone). Nothing here ever leaves the device unsealed.
|
|
12
12
|
*/
|
|
13
13
|
import nacl from "tweetnacl";
|
|
14
|
+
import {sharedBoxKey} from './shared-box';
|
|
15
|
+
export {clearSharedBoxKeys} from './shared-box';
|
|
14
16
|
|
|
15
17
|
export type KeyPair = { publicKey: string; secretKey: string }; // base64
|
|
16
18
|
|
|
@@ -30,7 +32,7 @@ export function seal(
|
|
|
30
32
|
): { nonce: string; box: string } {
|
|
31
33
|
const msg = new TextEncoder().encode(JSON.stringify(payload));
|
|
32
34
|
const nonce = nacl.randomBytes(nacl.box.nonceLength);
|
|
33
|
-
const box = nacl.box(msg, nonce,
|
|
35
|
+
const box = nacl.box.after(msg, nonce, sharedBoxKey(theirPublicKey, mySecretKey));
|
|
34
36
|
return { nonce: b64(nonce), box: b64(box) };
|
|
35
37
|
}
|
|
36
38
|
|
|
@@ -52,7 +54,7 @@ export function open(
|
|
|
52
54
|
): unknown | null {
|
|
53
55
|
let opened: Uint8Array | null = null;
|
|
54
56
|
try {
|
|
55
|
-
opened = nacl.box.open(ub64(box), ub64(nonce),
|
|
57
|
+
opened = nacl.box.open.after(ub64(box), ub64(nonce), sharedBoxKey(theirPublicKey, mySecretKey));
|
|
56
58
|
} catch {
|
|
57
59
|
return null;
|
|
58
60
|
}
|
|
@@ -6,7 +6,7 @@ import { OutboundFrameQueue, sendEncryptedPayload, priorityControlPayload } from
|
|
|
6
6
|
import { openRelayMessage, parseRelayControl, waitForRelayPayload } from "./relay-inbound";
|
|
7
7
|
import { consumeTaskJobOffer, type TaskDispatchListener } from "./task-dispatch";
|
|
8
8
|
import { Payload, type Role } from "../protocol/schema";
|
|
9
|
-
import { peerPublicKeys } from "./crypto";
|
|
9
|
+
import { clearSharedBoxKeys, peerPublicKeys } from "./crypto";
|
|
10
10
|
import type { PeerConfig, RelayClientOptions, SendOptions } from "./relay-client-types";
|
|
11
11
|
export type { PeerConfig, RelayClientOptions, SendOptions } from "./relay-client-types";
|
|
12
12
|
import { RelayMessageAcceptance } from "./replay-store";
|
|
@@ -264,6 +264,7 @@ export class RelayClient {
|
|
|
264
264
|
}
|
|
265
265
|
|
|
266
266
|
close(): void {
|
|
267
|
+
clearSharedBoxKeys();
|
|
267
268
|
this.frames?.cancel();
|
|
268
269
|
this.socketHealth.stop();
|
|
269
270
|
this.admissionLease.stop();
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Shared NaCl box keys
|
|
2
|
+
|
|
3
|
+
Repeated device envelopes reuse NaCl's documented `box.before` precomputation.
|
|
4
|
+
`box.after` and `box.open.after` produce and read the existing NaCl wire format;
|
|
5
|
+
every envelope still uses a fresh random nonce. Both devices' key bytes identify
|
|
6
|
+
the cache entry, so key rotation cannot select an older pairing's shared key.
|
|
7
|
+
|
|
8
|
+
The process-local LRU holds at most 64 keys for 60 seconds of monotonic time.
|
|
9
|
+
Expiration is enforced on lookup. Eviction, expiry and explicit transport close
|
|
10
|
+
zero the cached key material. Decoded private-key scratch buffers are zeroed on
|
|
11
|
+
each lookup; cache identifiers are SHA-256 digests, not raw private keys.
|
|
12
|
+
|
|
13
|
+
Tests in `tests/` cover direct NaCl interoperability, rotation, authentication,
|
|
14
|
+
fresh nonces, bounded derivation and erasure. This module uses the
|
|
15
|
+
GrantTap Commercial Source License.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {performance} from 'node:perf_hooks';
|
|
3
|
+
import nacl from 'tweetnacl';
|
|
4
|
+
|
|
5
|
+
/** Bounded, process-local NaCl precomputation; raw private keys never become cache identities. */
|
|
6
|
+
export function createSharedBoxCache(options: {
|
|
7
|
+
capacity?: number; ttlMs?: number; now?: () => number;
|
|
8
|
+
derive?: (publicKey: Uint8Array, secretKey: Uint8Array) => Uint8Array;
|
|
9
|
+
} = {}) {
|
|
10
|
+
const capacity = Number.isSafeInteger(options.capacity) && options.capacity! > 0 ? Math.min(256, options.capacity!) : 64;
|
|
11
|
+
const ttlMs = Number.isFinite(options.ttlMs) && options.ttlMs! > 0 ? options.ttlMs! : 60_000;
|
|
12
|
+
const now = options.now ?? (() => performance.now()), derive = options.derive ?? nacl.box.before;
|
|
13
|
+
const entries = new Map<string, {key: Uint8Array; expiresAt: number}>();
|
|
14
|
+
return {
|
|
15
|
+
get(publicKey: string, secretKey: string): Uint8Array {
|
|
16
|
+
const pub = Buffer.from(publicKey, 'base64'), secret = Buffer.from(secretKey, 'base64');
|
|
17
|
+
try {
|
|
18
|
+
if (pub.length !== nacl.box.publicKeyLength) throw Error('bad public key size');
|
|
19
|
+
if (secret.length !== nacl.box.secretKeyLength) throw Error('bad secret key size');
|
|
20
|
+
const identity = createHash('sha256').update(pub).update(secret).digest('hex'), at = now();
|
|
21
|
+
const hit = entries.get(identity);
|
|
22
|
+
if (hit && hit.expiresAt > at) {entries.delete(identity); entries.set(identity, hit); return hit.key}
|
|
23
|
+
for (const [id, entry] of entries) if (entry.expiresAt <= at) {entry.key.fill(0); entries.delete(id)}
|
|
24
|
+
const key = derive(pub, secret);
|
|
25
|
+
entries.set(identity, {key, expiresAt: at + ttlMs});
|
|
26
|
+
while (entries.size > capacity) {
|
|
27
|
+
const id = entries.keys().next().value!;
|
|
28
|
+
entries.get(id)!.key.fill(0); entries.delete(id);
|
|
29
|
+
}
|
|
30
|
+
return key;
|
|
31
|
+
} finally {secret.fill(0)}
|
|
32
|
+
},
|
|
33
|
+
clear() {for (const entry of entries.values()) entry.key.fill(0); entries.clear()},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const sharedBoxes = createSharedBoxCache();
|
|
38
|
+
export const sharedBoxKey = (publicKey: string, secretKey: string) => sharedBoxes.get(publicKey, secretKey);
|
|
39
|
+
export const clearSharedBoxKeys = () => sharedBoxes.clear();
|