sidepaw-companion-openclaw 0.3.0 → 1.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/README.md +21 -11
- package/access.mjs +1 -1
- package/approvals.mjs +88 -0
- package/delivery.mjs +1 -1
- package/envelope.mjs +7 -6
- package/events.mjs +27 -2
- package/hooks.mjs +9 -2
- package/identity.mjs +2 -2
- package/index.mjs +41 -20
- package/notification.mjs +85 -16
- package/openclaw.plugin.json +2 -2
- package/outbox.mjs +7 -12
- package/package.json +3 -2
- package/relay.mjs +3 -3
- package/service.mjs +2 -2
- package/subscriptions.mjs +10 -8
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# Sidepaw Companion for OpenClaw
|
|
2
2
|
|
|
3
|
-
`sidepaw-companion-openclaw` connects Sidepaw to your OpenClaw gateway.
|
|
3
|
+
`sidepaw-companion-openclaw` connects Sidepaw to your OpenClaw gateway. It sends encrypted notifications for finished replies, pending questions, new messages in explicitly subscribed conversations, and pending approvals.
|
|
4
4
|
|
|
5
|
-
Requires OpenClaw 2026.10.8 or later and Node 24+. The
|
|
5
|
+
Requires OpenClaw 2026.10.8 or later and Node 24+. The plugin ID is `sidepaw-companion`. Approval notifications use the gateway's approval runtime client (`createOperatorApprovalsGatewayClient`, OpenClaw 2026.10.10 or later); on an older gateway, messages keep working and approvals stay off.
|
|
6
6
|
|
|
7
7
|
## Set up from Sidepaw
|
|
8
8
|
|
|
@@ -12,26 +12,36 @@ The agent installs Companion using OpenClaw's supported plugin manager. Sidepaw
|
|
|
12
12
|
|
|
13
13
|
## Instructions for the setup agent
|
|
14
14
|
|
|
15
|
-
1. Use the request's `plugins.install` parameters, including `source: npm`, the exact `spec`, `expectedPluginId:
|
|
15
|
+
1. Use the request's `plugins.install` parameters, including `source: npm`, the exact `spec`, `expectedPluginId: sidepaw-companion`, `expectedIntegrity`, and `pin: true`. For npm, use `openclaw gateway call plugins.install --params '<the supplied JSON>' --json` from the gateway's environment, with its configured authentication. Do not print or copy credentials. Never substitute `latest` or bypass an integrity mismatch.
|
|
16
16
|
2. Inspect the plugin through `plugins.inspect`. Enable it through `plugins.setEnabled`, following the gateway's capability-review and installation-policy workflow. Obtain required approval; do not automatically acknowledge new warnings or broaden permissions. If deployment is managed externally, stop and report the administrator action needed.
|
|
17
|
-
3. Grant only `plugins.entries.
|
|
18
|
-
4. Leave iPhone enrollment to Sidepaw. The app calls `
|
|
17
|
+
3. Grant only `plugins.entries.sidepaw-companion.hooks.allowConversationAccess: true`. Use `config.get` and a narrowly scoped `config.patch` with its current `baseHash`. Preserve unrelated configuration. Follow the gateway's supported reload/restart workflow and wait for the connection to return.
|
|
18
|
+
4. Leave iPhone enrollment to Sidepaw. The app calls `sidepaw.push.enable` through its paired administrator connection, then enrolls its verified phone and explicit conversations. Never read pairing files, copy tokens, request Apple keys, create Firebase credentials, or change billing.
|
|
19
19
|
5. Report the installed version and any remaining administrator action. Do not claim that notifications reached the iPhone.
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
If the request says it replaces an earlier Sidepaw notification plugin, follow its exact steps: install and enable this package first, and remove the earlier plugin only after this one reports ready.
|
|
22
|
+
|
|
23
|
+
## Updates
|
|
24
|
+
|
|
25
|
+
In **Settings → Notifications**, **Update Companion** reviews a separate request to the agent for the relay's exact version and checksum. Publishing a package or installing an iOS update does not silently update a gateway. Sidepaw reads the running version from `sidepaw.push.status`.
|
|
26
|
+
|
|
27
|
+
For an update, use the supplied `plugins.install` JSON with `mode: update` and `enable: false`. Never uninstall, remove state, substitute `latest`, or downgrade a newer installation. Preserve the service identity, subscriptions, outbox, hook grants, relay approvals, and preferences. Any additional permissions or policy warnings need the person's review.
|
|
22
28
|
|
|
23
29
|
## Access and privacy
|
|
24
30
|
|
|
25
|
-
Companion reads conversation events and pending
|
|
31
|
+
Companion reads conversation events, pending questions and pending approvals for notification delivery. It encrypts each alert for the recipient iPhone before sending it to Sidepaw's relay. Apple credentials remain with Sidepaw; this package contains none. The relay receives encrypted alerts and device delivery metadata.
|
|
32
|
+
|
|
33
|
+
The notification service device has only `operator.read` and `operator.questions`. Approvals are read through the gateway's local approval runtime client, which can see every pending approval; Companion calls only `exec.approval.get` and `plugin.approval.list` on it and never resolves an approval. Decisions are made on the iPhone, through its own paired operator connection, after it re-reads the live request. While Companion is enabled, the gateway counts it as an approval route, so a request with no other route waits for its timeout instead of being refused at once.
|
|
34
|
+
|
|
35
|
+
Pairing, registration, expiry, category preferences and, for approvals and questions, the request's pending state are rechecked before every delivery. Turning notifications off revokes phone delivery.
|
|
26
36
|
|
|
27
|
-
|
|
37
|
+
An approval alert carries a bounded summary, the command (shortened when long), host, working folder, agent, expiry, allowed decisions, and the SHA-256 digest of the full command text. The phone refuses a decision when the live request no longer matches that digest.
|
|
28
38
|
|
|
29
39
|
## Development and release
|
|
30
40
|
|
|
31
|
-
|
|
41
|
+
Run `node --test GatewayPush/*.test.mjs PushRelay/*.test.mjs` from the repository root. The SDK acceptance script uses an isolated synthetic gateway, never a personal configuration:
|
|
32
42
|
|
|
33
43
|
```
|
|
34
|
-
|
|
44
|
+
GATEWAY_SDK_ROOT=/path/to/isolated/node_modules/openclaw node GatewayPush/sdk.integration.mjs
|
|
35
45
|
```
|
|
36
46
|
|
|
37
|
-
Pack and inspect this directory before publishing. Publish the exact reviewed tarball, then set the relay's
|
|
47
|
+
Pack and inspect this directory before publishing. Publish the exact reviewed tarball, then set the relay's Companion 1.0 pin to that artifact. Package publication, relay configuration readback, and real-device delivery are separate release checks.
|
package/access.mjs
CHANGED
|
@@ -15,7 +15,7 @@ export class GatewayAccess {
|
|
|
15
15
|
await this.stop();
|
|
16
16
|
if (!bootstrapToken && !this.identity.token) return;
|
|
17
17
|
const config = this.context.config.gateway ?? {};
|
|
18
|
-
if (config.mode === 'remote') throw new Error('
|
|
18
|
+
if (config.mode === 'remote') throw new Error('Sidepaw Companion must run on the Gateway');
|
|
19
19
|
const port = Number(process.env.OPENCLAW_GATEWAY_PORT ?? config.port ?? 18789);
|
|
20
20
|
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error('Invalid Gateway port');
|
|
21
21
|
let tlsFingerprint;
|
package/approvals.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { actionDigest } from './notification.mjs';
|
|
2
|
+
|
|
3
|
+
const valid = value => typeof value === 'string' && !!value && value === value.trim() && Buffer.byteLength(value) <= 1000 && !/[\x00-\x1f\x7f]/u.test(value);
|
|
4
|
+
const text = value => typeof value === 'string' && value.trim() ? value : undefined;
|
|
5
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value) ? value : null;
|
|
6
|
+
const firstLine = value => text(value)?.split('\n').find(line => line.trim())?.trim();
|
|
7
|
+
const READ_METHODS = new Set(['exec.approval.get', 'plugin.approval.list']);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Pending approvals, observed through the gateway's own approval-runtime client
|
|
11
|
+
* (`createOperatorApprovalsGatewayClient`). Approval records are bound to the
|
|
12
|
+
* device that started the turn, so an ordinary paired service device can't see them.
|
|
13
|
+
* Companion only reads: it never calls a resolve method; the phone decides.
|
|
14
|
+
*/
|
|
15
|
+
export function createApprovalSource({ createClient, config, schedule = setTimeout, cancel = clearTimeout }) {
|
|
16
|
+
let client, listener, generation = 0, timer;
|
|
17
|
+
const emit = payload => { if (listener) listener('approval.requested', payload); };
|
|
18
|
+
|
|
19
|
+
async function request(method, params) {
|
|
20
|
+
if (!client || !READ_METHODS.has(method)) throw new Error('Approval access unavailable');
|
|
21
|
+
return client.request(method, params, { timeoutMs: 5000 });
|
|
22
|
+
}
|
|
23
|
+
/** The exact text the phone shows; the digest binds a decision to it. */
|
|
24
|
+
async function project(event) {
|
|
25
|
+
const payload = record(event?.payload), id = payload?.id, asked = record(payload?.request);
|
|
26
|
+
if (!valid(id) || !asked) return null;
|
|
27
|
+
if (event.event === 'exec.approval.requested') {
|
|
28
|
+
const live = record(await request('exec.approval.get', { id }));
|
|
29
|
+
if (!live || !text(live.commandText)) return null;
|
|
30
|
+
return { approvalKind: 'exec', approvalId: id, details: {
|
|
31
|
+
command: live.commandText, digest: actionDigest(live.commandText),
|
|
32
|
+
summary: firstLine(live.commandPreview) ?? firstLine(live.commandText),
|
|
33
|
+
host: text(live.host) ?? text(asked.host), cwd: text(asked.cwd), agent: text(live.agentId) ?? text(asked.agentId),
|
|
34
|
+
reason: firstLine(asked.warningText), expiresAtMs: live.expiresAtMs ?? payload.expiresAtMs,
|
|
35
|
+
decisions: Array.isArray(live.allowedDecisions) ? live.allowedDecisions : [],
|
|
36
|
+
} };
|
|
37
|
+
}
|
|
38
|
+
if (event.event === 'plugin.approval.requested') {
|
|
39
|
+
const title = text(asked.title), description = text(asked.description) ?? '';
|
|
40
|
+
if (!title) return null;
|
|
41
|
+
return { approvalKind: 'plugin', approvalId: id, details: {
|
|
42
|
+
title, summary: firstLine(description) ?? title, digest: actionDigest(`${title}\n${description}`),
|
|
43
|
+
agent: text(asked.agentId), expiresAtMs: payload.expiresAtMs,
|
|
44
|
+
decisions: Array.isArray(asked.allowedDecisions) ? asked.allowedDecisions : ['allow-once', 'deny'],
|
|
45
|
+
} };
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
async function connect(current) {
|
|
50
|
+
try {
|
|
51
|
+
const next = await createClient({ config, clientDisplayName: 'Sidepaw Companion',
|
|
52
|
+
onEvent: event => {
|
|
53
|
+
if (current !== generation || !/^(exec|plugin)\.approval\.requested$/u.test(event?.event ?? '')) return;
|
|
54
|
+
project(event).then(value => { if (value && current === generation) emit(value); }).catch(() => {});
|
|
55
|
+
},
|
|
56
|
+
onConnectError: () => {}, onClose: () => {},
|
|
57
|
+
});
|
|
58
|
+
if (current !== generation) { await next.stopAndWait?.({ timeoutMs: 1000 }).catch(() => {}); return; }
|
|
59
|
+
client = next; client.start();
|
|
60
|
+
} catch {
|
|
61
|
+
// The approvals runtime is optional: messages keep working. Retry quietly.
|
|
62
|
+
if (current === generation) { timer = schedule(() => { timer = undefined; void connect(current); }, 30000); timer?.unref?.(); }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
subscribe(callback) {
|
|
67
|
+
if (listener) throw new Error('Approval source already subscribed');
|
|
68
|
+
listener = callback; const current = ++generation;
|
|
69
|
+
void connect(current);
|
|
70
|
+
return () => {
|
|
71
|
+
listener = undefined; generation++;
|
|
72
|
+
if (timer) { cancel(timer); timer = undefined; }
|
|
73
|
+
const closing = client; client = undefined;
|
|
74
|
+
void closing?.stopAndWait?.({ timeoutMs: 1000 }).catch(() => {});
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
/** Revalidate before every send, like questions: still pending, same kind. */
|
|
78
|
+
async isPending(kind, id) {
|
|
79
|
+
if (kind === 'exec') {
|
|
80
|
+
try { return record(await request('exec.approval.get', { id }))?.id === id; }
|
|
81
|
+
catch (error) { if (client && /unknown|expired/iu.test(error?.message ?? '')) return false; throw error; }
|
|
82
|
+
}
|
|
83
|
+
const response = await request('plugin.approval.list', {});
|
|
84
|
+
const list = Array.isArray(response) ? response : Array.isArray(response?.approvals) ? response.approvals : [];
|
|
85
|
+
return list.some(item => item?.id === id);
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
package/delivery.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* still paired and return its current registration; no APNs credential or
|
|
4
4
|
* device token is persisted in this queue.
|
|
5
5
|
*/
|
|
6
|
-
export async function
|
|
6
|
+
export async function processNextAlert({ ledger, resolveDestination, auth, send, shouldContinue = () => true, now = Date.now(), leaseMs = 30000, retryMs = 30000 }) {
|
|
7
7
|
if (!Number.isSafeInteger(now) || now < 0 || !Number.isSafeInteger(retryMs) || retryMs < 0) throw new Error('Invalid retry timing');
|
|
8
8
|
const job = ledger.claimNext(now, leaseMs);
|
|
9
9
|
if (!job) return { state: 'empty' };
|
package/envelope.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createCipheriv, createHash, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes } from 'node:crypto';
|
|
2
|
-
import {
|
|
2
|
+
import { makeAlert } from './notification.mjs';
|
|
3
3
|
|
|
4
|
-
export const
|
|
4
|
+
export const envelopeVersion = 2;
|
|
5
|
+
export const contextFor = (handle, eventId) => Buffer.from(`Sidepaw Push v2\n${handle}\n${eventId}`);
|
|
5
6
|
const x25519Prefix = Buffer.from('302a300506032b656e032100', 'hex');
|
|
6
7
|
|
|
7
8
|
/** X25519 + HKDF-SHA256 + AES-256-GCM. Only the recipient holds the decryption key. */
|
|
@@ -9,11 +10,11 @@ export function encryptAlert({ relayHandle, encryptionPublicKey, alert, testId }
|
|
|
9
10
|
if (!/^[a-zA-Z0-9_-]{32,128}$/.test(relayHandle)) throw new Error('Invalid relay handle');
|
|
10
11
|
const recipient = Buffer.from(encryptionPublicKey, 'base64');
|
|
11
12
|
if (recipient.length !== 32 || recipient.toString('base64') !== encryptionPublicKey) throw new Error('Invalid recipient key');
|
|
12
|
-
const { bodyData, eventId } =
|
|
13
|
+
const { bodyData, eventId } = makeAlert(alert);
|
|
13
14
|
const content = JSON.parse(bodyData);
|
|
14
15
|
if (testId) {
|
|
15
|
-
content.aps.alert = { title: '
|
|
16
|
-
content.
|
|
16
|
+
content.aps.alert = { title: 'Sidepaw', body: 'Your notifications are working.' };
|
|
17
|
+
content.sidepawTestId = testId;
|
|
17
18
|
}
|
|
18
19
|
const { privateKey, publicKey } = generateKeyPairSync('x25519');
|
|
19
20
|
const peer = createPublicKey({key: Buffer.concat([x25519Prefix, recipient]), type: 'spki', format: 'der'});
|
|
@@ -25,7 +26,7 @@ export function encryptAlert({ relayHandle, encryptionPublicKey, alert, testId }
|
|
|
25
26
|
const ciphertext = Buffer.concat([cipher.update(Buffer.from(JSON.stringify(content))), cipher.final(), cipher.getAuthTag()]);
|
|
26
27
|
secret.fill(0); key.fill(0);
|
|
27
28
|
const envelope = {
|
|
28
|
-
version:
|
|
29
|
+
version: envelopeVersion, relayHandle, eventId,
|
|
29
30
|
keyId: createHash('sha256').update(recipient).digest('hex'),
|
|
30
31
|
ephemeralKey: publicKey.export({type:'spki',format:'der'}).subarray(-32).toString('base64'),
|
|
31
32
|
salt: salt.toString('base64'), nonce: nonce.toString('base64'), ciphertext: ciphertext.toString('base64'),
|
package/events.mjs
CHANGED
|
@@ -36,8 +36,10 @@ function targetFor(event, value, defaultAgentId) {
|
|
|
36
36
|
if (value.status !== 'pending' || !valid(value.id)) return null;
|
|
37
37
|
const first = Array.isArray(value.questions) ? asRecord(value.questions[0]) : null;
|
|
38
38
|
if (!first || typeof first.question !== 'string' || !first.question.trim()) return null;
|
|
39
|
+
const options = Array.isArray(first.options) ? first.options.map(option => asRecord(option)?.label ?? option).filter(valid) : [];
|
|
39
40
|
return { sessionKey, agentId, runId: valid(value.runId) ? value.runId : undefined,
|
|
40
|
-
messageId: `question:${value.id}`, preview: first.question
|
|
41
|
+
messageId: `question:${value.id}`, preview: first.question,
|
|
42
|
+
question: valid(first.questionId) ? { id: value.id, questionId: first.questionId, options: first.multiSelect === true ? [] : options } : undefined };
|
|
41
43
|
}
|
|
42
44
|
if (event === 'session.message') {
|
|
43
45
|
if (value.historyDelta === true || value.replay === true || !valid(value.messageId)) return null;
|
|
@@ -62,6 +64,7 @@ function targetFor(event, value, defaultAgentId) {
|
|
|
62
64
|
*/
|
|
63
65
|
export function ingestGatewayEvent({ event, payload, gatewayDeviceId, registrations, ledger, now = Date.now() }) {
|
|
64
66
|
if (!valid(gatewayDeviceId) || !Array.isArray(registrations)) return [];
|
|
67
|
+
if (event === 'approval.requested') return ingestApproval({ payload, gatewayDeviceId, registrations, ledger, now });
|
|
65
68
|
const results = [];
|
|
66
69
|
for (const registration of registrations) {
|
|
67
70
|
if (!registration || !valid(registration.nodeId)) continue;
|
|
@@ -75,9 +78,31 @@ export function ingestGatewayEvent({ event, payload, gatewayDeviceId, registrati
|
|
|
75
78
|
if (event === 'session.message' ? !isMain : !isMain && !isTracked) continue;
|
|
76
79
|
const name = asRecord(registration.agentNames)?.[target.agentId];
|
|
77
80
|
const alert = { gatewayDeviceId, sessionKey: target.sessionKey, agentId: target.agentId,
|
|
78
|
-
messageId: target.messageId, agentName: typeof name === 'string' ? name : undefined, preview: target.preview
|
|
81
|
+
messageId: target.messageId, agentName: typeof name === 'string' ? name : undefined, preview: target.preview,
|
|
82
|
+
...(target.question ? { question: target.question } : {}) };
|
|
79
83
|
try { results.push({ nodeId: registration.nodeId, ...ledger.enqueue(registration.nodeId, alert, now) }); }
|
|
80
84
|
catch { /* A malformed or oversized event must not interrupt gateway delivery. */ }
|
|
81
85
|
}
|
|
82
86
|
return results;
|
|
83
87
|
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A pending approval reaches every enrolled phone that keeps approvals on: deciding is
|
|
91
|
+
* the operator's, not one conversation's. The source has already projected and bounded it.
|
|
92
|
+
*/
|
|
93
|
+
function ingestApproval({ payload, gatewayDeviceId, registrations, ledger, now }) {
|
|
94
|
+
const value = asRecord(payload);
|
|
95
|
+
if (!value || !['exec', 'plugin'].includes(value.approvalKind) || !valid(value.approvalId) || !asRecord(value.details)) return [];
|
|
96
|
+
if (!Number.isSafeInteger(value.details.expiresAtMs) || value.details.expiresAtMs <= now) return [];
|
|
97
|
+
const results = [];
|
|
98
|
+
for (const registration of registrations) {
|
|
99
|
+
if (!registration || !valid(registration.nodeId) || registration.preferences?.approvals === false) continue;
|
|
100
|
+
const agent = value.details.agent;
|
|
101
|
+
const name = valid(agent) ? asRecord(registration.agentNames)?.[agent] : undefined;
|
|
102
|
+
const alert = { type: 'approval', gatewayDeviceId, approvalKind: value.approvalKind, approvalId: value.approvalId,
|
|
103
|
+
agentName: typeof name === 'string' ? name : undefined, details: value.details };
|
|
104
|
+
try { results.push({ nodeId: registration.nodeId, ...ledger.enqueue(registration.nodeId, alert, now) }); }
|
|
105
|
+
catch { /* A malformed approval must not interrupt gateway delivery. */ }
|
|
106
|
+
}
|
|
107
|
+
return results;
|
|
108
|
+
}
|
package/hooks.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Bridge OpenClaw plugin hooks to
|
|
1
|
+
/** Bridge OpenClaw plugin hooks to Companion's normalized gateway event interface. */
|
|
2
2
|
const valid = value => typeof value === 'string' && !!value && value === value.trim() && Buffer.byteLength(value) <= 1000 && !/[\x00-\x1f\x7f]/u.test(value);
|
|
3
3
|
const same = (a,b) => typeof a === 'string' && typeof b === 'string' && Buffer.from(a).equals(Buffer.from(b));
|
|
4
4
|
const identity = (event, ctx) => {
|
|
@@ -19,7 +19,14 @@ export function createHookEventSource({ api, request, schedule = setTimeout, can
|
|
|
19
19
|
for (const [key, value] of runs) if (value.updated < cutoff) runs.delete(key);
|
|
20
20
|
while (runs.size > 512) runs.delete(runs.keys().next().value);
|
|
21
21
|
};
|
|
22
|
-
const boundedText = text =>
|
|
22
|
+
const boundedText = text => {
|
|
23
|
+
let result = '', count = 0;
|
|
24
|
+
for (const {segment} of new Intl.Segmenter(undefined,{granularity:'grapheme'}).segment(typeof text === 'string' ? text : '')) {
|
|
25
|
+
if (++count > 2000) return result + '…';
|
|
26
|
+
result += segment;
|
|
27
|
+
}
|
|
28
|
+
return result;
|
|
29
|
+
};
|
|
23
30
|
const usable = text => text.trim() && !/^(?:NO_REPLY\s*)+$/iu.test(text.trim());
|
|
24
31
|
const merge = (key, patch = {}) => {
|
|
25
32
|
if (!key || incognito(key.sessionKey)) return null;
|
package/identity.mjs
CHANGED
|
@@ -6,10 +6,10 @@ import { dirname } from 'node:path';
|
|
|
6
6
|
export async function loadIdentity(path) {
|
|
7
7
|
try {
|
|
8
8
|
const metadata = await stat(path);
|
|
9
|
-
if (!metadata.isFile() || (metadata.mode & 0o077)) throw new Error('
|
|
9
|
+
if (!metadata.isFile() || (metadata.mode & 0o077)) throw new Error('Companion identity must be private');
|
|
10
10
|
const identity = JSON.parse(await readFile(path,'utf8'));
|
|
11
11
|
const derived = createPublicKey(identity.privateKeyPem).export({type:'spki',format:'der'}).subarray(-32);
|
|
12
|
-
if (identity.publicKey !== derived.toString('base64') || identity.deviceId !== createHash('sha256').update(derived).digest('hex')) throw new Error('Invalid
|
|
12
|
+
if (identity.publicKey !== derived.toString('base64') || identity.deviceId !== createHash('sha256').update(derived).digest('hex')) throw new Error('Invalid Companion identity');
|
|
13
13
|
return identity;
|
|
14
14
|
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
15
15
|
const {publicKey,privateKey} = generateKeyPairSync('ed25519');
|
package/index.mjs
CHANGED
|
@@ -7,20 +7,35 @@ import { SubscriptionStore } from './subscriptions.mjs';
|
|
|
7
7
|
import { GatewayAccess } from './access.mjs';
|
|
8
8
|
import { loadIdentity, saveIdentity } from './identity.mjs';
|
|
9
9
|
import { relayOrigin, relaySender } from './relay.mjs';
|
|
10
|
+
import { createApprovalSource } from './approvals.mjs';
|
|
11
|
+
import { defaultPreferences } from './subscriptions.mjs';
|
|
12
|
+
import packageInfo from './package.json' with { type: 'json' };
|
|
10
13
|
|
|
11
14
|
const same = (a,b) => typeof a === 'string' && a === b;
|
|
12
15
|
const opaque = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{32,128}$/.test(value);
|
|
13
16
|
const key = value => typeof value === 'string' && Buffer.from(value,'base64').length === 32 && Buffer.from(value,'base64').toString('base64') === value;
|
|
14
17
|
|
|
15
|
-
export
|
|
18
|
+
export const pluginId = 'sidepaw-companion';
|
|
19
|
+
const preferenceFor = alert => alert.type === 'approval' ? 'approvals' : alert.messageId.startsWith('question:') ? 'questions' : alert.messageId.startsWith('message:') ? 'incoming' : 'replies';
|
|
20
|
+
|
|
21
|
+
export function createCompanionPlugin({
|
|
16
22
|
loadGatewaySDK = () => import('openclaw/plugin-sdk/gateway-runtime'),
|
|
17
23
|
loadPairingSDK = () => import('openclaw/plugin-sdk/device-bootstrap'),
|
|
18
24
|
loadDispatchSDK = () => import('openclaw/plugin-sdk/gateway-method-runtime'),
|
|
19
25
|
makeAccess = options => new GatewayAccess(options), makeSender = relaySender,
|
|
26
|
+
makeApprovals = options => createApprovalSource(options),
|
|
20
27
|
} = {}) {
|
|
21
|
-
return {id:
|
|
22
|
-
let context, store, ledger, identity, identityPath, access, service, pairingSDK, starting, resumeJob, generation=0;
|
|
28
|
+
return {id:pluginId,name:'Sidepaw Companion',description:'Encrypted notifications for paired Sidepaw devices.',register(api) {
|
|
29
|
+
let context, store, ledger, identity, identityPath, access, service, pairingSDK, gatewaySDK, approvals, starting, resumeJob, generation=0;
|
|
23
30
|
const source = createHookEventSource({api,request:(...args) => access.request(...args)});
|
|
31
|
+
// Conversation hooks and approvals feed one service; either can be unavailable alone.
|
|
32
|
+
const subscribe = listener => {
|
|
33
|
+
const stopHooks = source.subscribe(listener);
|
|
34
|
+
approvals = makeApprovals({createClient:gatewaySDK.createOperatorApprovalsGatewayClient,config:context.config});
|
|
35
|
+
let stopApprovals;
|
|
36
|
+
try { stopApprovals = approvals.subscribe(listener); } catch { approvals = undefined; }
|
|
37
|
+
return () => { stopHooks(); stopApprovals?.(); approvals = undefined; };
|
|
38
|
+
};
|
|
24
39
|
const assertStarted = () => { if (!store || !identity || !context) throw new Error('Notification service is starting'); };
|
|
25
40
|
const pairings = async () => (await pairingSDK.listDevicePairing(context.stateDir)).paired;
|
|
26
41
|
const currentPairing = (pairs,nodeId) => pairs.find(pair => pair.deviceId === nodeId &&
|
|
@@ -42,7 +57,7 @@ export function createHarborPushPlugin({
|
|
|
42
57
|
const current=generation;
|
|
43
58
|
const gateway = await access.request('gateway.identity.get');
|
|
44
59
|
if (current !== generation || !gateway?.deviceId) return;
|
|
45
|
-
const next = new GatewayPushService({ledger,subscribe
|
|
60
|
+
const next = new GatewayPushService({ledger,subscribe,gatewayDeviceId:gateway.deviceId,
|
|
46
61
|
getRegistrations:async () => {
|
|
47
62
|
const pairs=await pairings();
|
|
48
63
|
return store.list().flatMap(item => {
|
|
@@ -53,8 +68,12 @@ export function createHarborPushPlugin({
|
|
|
53
68
|
resolveDestination:async (nodeId,alert) => {
|
|
54
69
|
const enrollment=approvedEnrollment(await pairings(),nodeId);
|
|
55
70
|
if (!enrollment || !same(enrollment.registration.gatewayDeviceId,alert.gatewayDeviceId)) return {state:'removed'};
|
|
56
|
-
const preference=
|
|
71
|
+
const preference=preferenceFor(alert);
|
|
57
72
|
if (enrollment.preferences[preference] === false) return {state:'removed'};
|
|
73
|
+
if (preference === 'approvals') {
|
|
74
|
+
if (!approvals) return {state:'unavailable'};
|
|
75
|
+
return await approvals.isPending(alert.approvalKind,alert.approvalId) ? {state:'ready',destination:{registration:enrollment.registration}} : {state:'removed'};
|
|
76
|
+
}
|
|
58
77
|
if (preference === 'questions') {
|
|
59
78
|
const response=await access.request('question.list');
|
|
60
79
|
if (!Array.isArray(response?.questions)) return {state:'unavailable'};
|
|
@@ -63,15 +82,15 @@ export function createHarborPushPlugin({
|
|
|
63
82
|
const subscription=store.list().find(item => item.nodeId === nodeId);
|
|
64
83
|
if (!subscription || (!same(subscription.mainSessionKey,alert.sessionKey) && !subscription.trackedRuns.some(run => same(run.sessionKey,alert.sessionKey)))) return {state:'removed'};
|
|
65
84
|
return {state:'ready',destination:{registration:enrollment.registration}};
|
|
66
|
-
},send,onError:category => context.logger.warn(`
|
|
85
|
+
},send,onError:category => context.logger.warn(`Sidepaw notifications ${category} unavailable`),
|
|
67
86
|
});
|
|
68
87
|
next.start(); service=next;
|
|
69
88
|
}
|
|
70
|
-
const handler = (name,scope,run) => api.registerGatewayMethod(`
|
|
89
|
+
const handler = (name,scope,run) => api.registerGatewayMethod(`sidepaw.push.${name}`,async options => {
|
|
71
90
|
try {
|
|
72
91
|
assertStarted();
|
|
73
92
|
if (!options.params || typeof options.params !== 'object' || Array.isArray(options.params)) throw new Error('Invalid parameters');
|
|
74
|
-
const allowed={status:['relayOrigin'],enable:['relayOrigin'],enroll:['registration'],configure:['topic','mainSessionKey','defaultAgentId','agentNames'],track:['sessionKey','runId'],preferences:
|
|
93
|
+
const allowed={status:['relayOrigin'],enable:['relayOrigin'],enroll:['registration'],configure:['topic','mainSessionKey','defaultAgentId','agentNames'],track:['sessionKey','runId'],preferences:Object.keys(defaultPreferences),disable:[],test:[]}[name];
|
|
75
94
|
if (Object.keys(options.params).some(key => !allowed.includes(key))) throw new Error('Unexpected parameter');
|
|
76
95
|
const current=generation, nodeId=options.client?.connect?.device?.id;
|
|
77
96
|
const assertCurrent=() => {
|
|
@@ -88,11 +107,12 @@ export function createHarborPushPlugin({
|
|
|
88
107
|
handler('status','operator.read',async ({nodeId,params}) => {
|
|
89
108
|
const origin=params.relayOrigin ? relayOrigin(params.relayOrigin):undefined;
|
|
90
109
|
const enrollment=approvedEnrollment(await pairings(),nodeId);
|
|
91
|
-
return {protocolVersion:2,nodeId,gatewaySigningPublicKey:identity.publicKey,
|
|
92
|
-
serviceReady:access.ready && !!service,conversationAccess:context.config.plugins?.entries?.[
|
|
110
|
+
return {protocolVersion:2,companionVersion:packageInfo.version,nodeId,gatewaySigningPublicKey:identity.publicKey,
|
|
111
|
+
serviceReady:access.ready && !!service,conversationAccess:context.config.plugins?.entries?.[pluginId]?.hooks?.allowConversationAccess === true,
|
|
112
|
+
approvalsReady:!!approvals,
|
|
93
113
|
relayApproved:!!origin && (identity.allowedOrigins ?? []).includes(origin),
|
|
94
114
|
enrolled:!!enrollment,expiresAtMs:enrollment?.registration.expiresAtMs,
|
|
95
|
-
preferences:enrollment?.preferences ?? {
|
|
115
|
+
preferences:enrollment?.preferences ?? {...defaultPreferences}};
|
|
96
116
|
});
|
|
97
117
|
handler('enable','operator.admin',async ({params,assertCurrent}) => {
|
|
98
118
|
const origin=relayOrigin(params.relayOrigin);
|
|
@@ -137,17 +157,18 @@ export function createHarborPushPlugin({
|
|
|
137
157
|
if (!result.ok) throw new Error('Test delivery unavailable');
|
|
138
158
|
return {testId,status:'accepted'};
|
|
139
159
|
});
|
|
140
|
-
api.registerService({id:
|
|
160
|
+
api.registerService({id:pluginId,apiVersion:2,reload:{configPrefixes:[`plugins.entries.${pluginId}.hooks`]},async start(value) {
|
|
141
161
|
context=value; generation++;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
162
|
+
const folder=join(context.stateDir,pluginId);
|
|
163
|
+
identityPath=join(folder,'identity.json'); identity=await loadIdentity(identityPath);
|
|
164
|
+
store=new SubscriptionStore(join(folder,'subscriptions.sqlite'));
|
|
165
|
+
ledger=new PushDeliveryLedger(join(folder,'outbox.sqlite'));
|
|
166
|
+
gatewaySDK=await loadGatewaySDK(); pairingSDK=await loadPairingSDK();
|
|
167
|
+
access=makeAccess({...gatewaySDK,...pairingSDK,identity,path:identityPath,context});
|
|
147
168
|
await access.start();
|
|
148
169
|
const resume=async () => { try {ledger.pruneFinished(Date.now()-7*86400000);await startDelivery();} catch {} };
|
|
149
|
-
if (!context.scheduler) throw new Error('
|
|
150
|
-
resumeJob=context.scheduler.schedule({id:'
|
|
170
|
+
if (!context.scheduler) throw new Error('Sidepaw notifications require the Gateway service scheduler');
|
|
171
|
+
resumeJob=context.scheduler.schedule({id:'sidepaw-notifications-resume',delayMs:1000,everyMs:10000,run:resume});
|
|
151
172
|
await resume();
|
|
152
173
|
},async stop() {
|
|
153
174
|
generation++; await resumeJob?.stop(); await starting?.catch(() => {}); await service?.stop(); service=undefined; await access?.stop();
|
|
@@ -155,4 +176,4 @@ export function createHarborPushPlugin({
|
|
|
155
176
|
}});
|
|
156
177
|
}};
|
|
157
178
|
}
|
|
158
|
-
export default
|
|
179
|
+
export default createCompanionPlugin();
|
package/notification.mjs
CHANGED
|
@@ -4,32 +4,101 @@ const exact = (v, name, max = 1024) => {
|
|
|
4
4
|
if (typeof v !== 'string' || !v || v !== v.trim() || Buffer.byteLength(v) > max || /[\x00-\x1f\x7f]/u.test(v)) throw new Error(`Invalid ${name}`);
|
|
5
5
|
return v;
|
|
6
6
|
};
|
|
7
|
+
const optional = (v, max) => typeof v === 'string' && v.trim() ? fitText(clean(v).replace(/\s+/gu, ' ').trim(), max) : undefined;
|
|
8
|
+
const clean = v => v.replace(/\r\n?/gu, '\n').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/gu, '').trim();
|
|
7
9
|
const digest = (...parts) => createHash('sha256').update(JSON.stringify(parts)).digest('hex');
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
const segments = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|
|
11
|
+
// Includes routing and JSON escaping. Leaves room for GCM, base64, and the envelope
|
|
12
|
+
// under the existing relay limits; no server or cryptographic contract change.
|
|
13
|
+
export const alertByteLimit = 2000;
|
|
14
|
+
export const messageKind = 'sidepaw.chat.message';
|
|
15
|
+
export const approvalKinds = Object.freeze({ exec: 'exec.approval.requested', plugin: 'plugin.approval.requested' });
|
|
16
|
+
const decisionNames = new Set(['allow-once', 'allow-always', 'deny']);
|
|
17
|
+
|
|
18
|
+
function fitText(value, bytes) {
|
|
19
|
+
let result = '', used = 0;
|
|
20
|
+
for (const { segment } of segments.segment(value)) {
|
|
21
|
+
const size = Buffer.byteLength(JSON.stringify(segment)) - 2;
|
|
22
|
+
if (used + size > bytes) {
|
|
23
|
+
while (result && Buffer.byteLength(JSON.stringify(result + '…')) - 2 > bytes) {
|
|
24
|
+
result = Array.from(segments.segment(result), part => part.segment).slice(0, -1).join('');
|
|
25
|
+
}
|
|
26
|
+
const boundary = result.lastIndexOf(' ');
|
|
27
|
+
if (boundary > result.length - 60 && boundary > result.length / 2) result = result.slice(0, boundary);
|
|
28
|
+
return result.trimEnd() + '…';
|
|
29
|
+
}
|
|
30
|
+
result += segment; used += size;
|
|
13
31
|
}
|
|
14
32
|
return result;
|
|
15
|
-
}
|
|
33
|
+
}
|
|
16
34
|
|
|
17
|
-
|
|
18
|
-
|
|
35
|
+
function finish(payload, fill) {
|
|
36
|
+
const available = alertByteLimit - Buffer.byteLength(JSON.stringify(payload));
|
|
37
|
+
if (available < 32) throw new Error('Notification routing exceeds encrypted payload budget');
|
|
38
|
+
fill(available);
|
|
39
|
+
const bodyData = Buffer.from(JSON.stringify(payload));
|
|
40
|
+
if (bodyData.length > alertByteLimit) throw new Error('Notification exceeds encrypted payload budget');
|
|
41
|
+
return bodyData;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A finished reply, a pending question, or an incoming message in one conversation. */
|
|
45
|
+
function messageAlert({ gatewayDeviceId, sessionKey, agentId, messageId, agentName, preview, question }) {
|
|
19
46
|
gatewayDeviceId = exact(gatewayDeviceId, 'gateway identity');
|
|
20
47
|
sessionKey = exact(sessionKey, 'session key');
|
|
21
48
|
agentId = exact(agentId, 'agent id');
|
|
22
49
|
messageId = exact(messageId, 'message id');
|
|
23
|
-
const title =
|
|
24
|
-
const text = typeof preview === 'string' ? preview
|
|
25
|
-
const body = text ? utf8Prefix(text, 220) : 'New message';
|
|
50
|
+
const title = optional(agentName, 100) ?? 'Your agent';
|
|
51
|
+
const text = typeof preview === 'string' ? clean(preview) : '';
|
|
26
52
|
const conversation = digest(gatewayDeviceId, sessionKey, agentId);
|
|
27
53
|
const event = digest(gatewayDeviceId, sessionKey, agentId, messageId);
|
|
28
54
|
const payload = {
|
|
29
|
-
aps: { alert: { title, body }, sound: 'default', 'thread-id': `
|
|
30
|
-
openclaw: { kind:
|
|
55
|
+
aps: { alert: { title, body: '' }, sound: 'default', 'thread-id': `sidepaw.${conversation}` },
|
|
56
|
+
openclaw: { kind: messageKind, gatewayDeviceId, sessionKey, agentId, messageId },
|
|
31
57
|
};
|
|
32
|
-
|
|
33
|
-
if (
|
|
34
|
-
|
|
58
|
+
// A question's options become buttons. Bounded: four short labels at most.
|
|
59
|
+
if (question && typeof question === 'object') {
|
|
60
|
+
const options = (Array.isArray(question.options) ? question.options : []).map(value => optional(value, 64)).filter(Boolean).slice(0, 4);
|
|
61
|
+
payload.openclaw.question = { id: exact(question.id, 'question id', 256), questionId: exact(question.questionId, 'question field', 256), options };
|
|
62
|
+
}
|
|
63
|
+
const bodyData = finish(payload, available => { payload.aps.alert.body = fitText(text || 'New message', available); });
|
|
64
|
+
return { bodyData, eventId: event, collapseId: `sidepaw.${event.slice(0, 48)}` };
|
|
35
65
|
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* An exec or plugin approval. The routing keeps the shape the app already parses; `details`
|
|
69
|
+
* describes the action, and `digest` binds a decision to the exact full command text.
|
|
70
|
+
*/
|
|
71
|
+
function approvalAlert({ gatewayDeviceId, approvalKind, approvalId, agentName, details = {} }) {
|
|
72
|
+
gatewayDeviceId = exact(gatewayDeviceId, 'gateway identity');
|
|
73
|
+
approvalId = exact(approvalId, 'approval id', 512);
|
|
74
|
+
const kind = approvalKinds[approvalKind];
|
|
75
|
+
if (!kind || !details || typeof details !== 'object') throw new Error('Invalid approval');
|
|
76
|
+
if (!/^[a-f0-9]{64}$/u.test(details.digest ?? '') || !Number.isSafeInteger(details.expiresAtMs)) throw new Error('Invalid approval details');
|
|
77
|
+
const decisions = Array.isArray(details.decisions) ? [...new Set(details.decisions.filter(value => decisionNames.has(value)))] : [];
|
|
78
|
+
const event = digest(gatewayDeviceId, 'approval', approvalKind, approvalId);
|
|
79
|
+
const summary = optional(details.summary, 240);
|
|
80
|
+
const bounded = {
|
|
81
|
+
summary, host: optional(details.host, 120), cwd: optional(details.cwd, 240),
|
|
82
|
+
agent: optional(agentName ?? details.agent, 100), reason: optional(details.reason, 240),
|
|
83
|
+
expiresAtMs: details.expiresAtMs, decisions, digest: details.digest, command: '',
|
|
84
|
+
};
|
|
85
|
+
for (const key of Object.keys(bounded)) if (bounded[key] === undefined) delete bounded[key];
|
|
86
|
+
const title = approvalKind === 'exec' ? 'Approval needed' : optional(details.title, 100) ?? 'Approval needed';
|
|
87
|
+
const payload = {
|
|
88
|
+
aps: { alert: { title, body: summary ?? 'Review the requested action.' }, sound: 'default', 'thread-id': `sidepaw.approvals.${digest(gatewayDeviceId)}` },
|
|
89
|
+
openclaw: { kind, approvalId, gatewayDeviceId, details: bounded },
|
|
90
|
+
};
|
|
91
|
+
const command = typeof details.command === 'string' ? clean(details.command) : '';
|
|
92
|
+
const bodyData = finish(payload, available => {
|
|
93
|
+
if (command) bounded.command = fitText(command, Math.min(available, 900)); else delete bounded.command;
|
|
94
|
+
});
|
|
95
|
+
return { bodyData, eventId: event, collapseId: `sidepaw.${event.slice(0, 48)}` };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Exact identifiers remain in the app payload; hashes are used for APNs metadata. */
|
|
99
|
+
export function makeAlert(alert) {
|
|
100
|
+
return alert?.type === 'approval' ? approvalAlert(alert) : messageAlert(alert ?? {});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** SHA-256 hex of the exact action text the phone compares before deciding. */
|
|
104
|
+
export const actionDigest = text => createHash('sha256').update(String(text), 'utf8').digest('hex');
|
package/openclaw.plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"id": "
|
|
2
|
+
"id": "sidepaw-companion",
|
|
3
3
|
"name": "Sidepaw Companion",
|
|
4
|
-
"description": "Connect Sidepaw to OpenClaw
|
|
4
|
+
"description": "Connect Sidepaw to OpenClaw: encrypted notifications for subscribed conversations and pending approvals.",
|
|
5
5
|
"configSchema": {
|
|
6
6
|
"type": "object",
|
|
7
7
|
"additionalProperties": false,
|
package/outbox.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { chmodSync, mkdirSync } from 'node:fs';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
4
|
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
-
import {
|
|
5
|
+
import { makeAlert } from './notification.mjs';
|
|
6
6
|
|
|
7
7
|
const hash = (v) => createHash('sha256').update(v).digest('hex');
|
|
8
8
|
const isDigest = (v) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
|
|
@@ -35,11 +35,8 @@ export class PushDeliveryLedger {
|
|
|
35
35
|
CREATE INDEX IF NOT EXISTS deliveries_retention ON deliveries(state,updated_at);
|
|
36
36
|
CREATE TABLE IF NOT EXISTS pending_payloads (
|
|
37
37
|
recipient TEXT NOT NULL, event TEXT NOT NULL, node_id TEXT NOT NULL,
|
|
38
|
-
alert_json TEXT NOT NULL, PRIMARY KEY(recipient,event)
|
|
38
|
+
alert_json TEXT NOT NULL, expires_at INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(recipient,event)
|
|
39
39
|
);`);
|
|
40
|
-
if (!this.db.prepare('PRAGMA table_info(pending_payloads)').all().some(column => column.name === 'expires_at')) {
|
|
41
|
-
this.db.exec('ALTER TABLE pending_payloads ADD COLUMN expires_at INTEGER NOT NULL DEFAULT 0');
|
|
42
|
-
}
|
|
43
40
|
}
|
|
44
41
|
claim(recipient, event, now = Date.now(), leaseMs = 30000) {
|
|
45
42
|
if (!isDigest(recipient) || !isDigest(event) || !millis(now) || !millis(leaseMs) || leaseMs === 0 || !millis(now + leaseMs)) throw new Error('Invalid delivery claim');
|
|
@@ -58,18 +55,16 @@ export class PushDeliveryLedger {
|
|
|
58
55
|
const recipient = recipientKeyFromNode(nodeId);
|
|
59
56
|
this.pruneExpired(now);
|
|
60
57
|
if (this.db.prepare('SELECT COUNT(*) AS n FROM pending_payloads WHERE recipient=?').get(recipient).n >= 128) return {inserted:false};
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
const stored =
|
|
64
|
-
|
|
65
|
-
};
|
|
66
|
-
delete stored.kind;
|
|
58
|
+
// Validates and bounds the alert; the stored input rebuilds the same payload at delivery.
|
|
59
|
+
const { eventId } = makeAlert(alert);
|
|
60
|
+
const stored = JSON.stringify(alert);
|
|
61
|
+
if (Buffer.byteLength(stored) > 16384) throw new Error('Notification input too large');
|
|
67
62
|
this.db.exec('BEGIN IMMEDIATE');
|
|
68
63
|
try {
|
|
69
64
|
const inserted = this.db.prepare(`INSERT OR IGNORE INTO deliveries
|
|
70
65
|
(recipient,event,state,retry_at,updated_at) VALUES(?,?,'retry',0,?)`).run(recipient, eventId, now).changes;
|
|
71
66
|
if (inserted === 1) this.db.prepare(`INSERT INTO pending_payloads(recipient,event,node_id,alert_json,expires_at)
|
|
72
|
-
VALUES(?,?,?,?,?)`).run(recipient, eventId, nodeId,
|
|
67
|
+
VALUES(?,?,?,?,?)`).run(recipient, eventId, nodeId, stored, now + (alert.type === 'approval' ? Math.max(1000, Math.min(3600000, alert.details.expiresAtMs - now)) : 3600000));
|
|
73
68
|
this.db.exec('COMMIT');
|
|
74
69
|
return { inserted: inserted === 1, eventId };
|
|
75
70
|
} catch (error) { this.db.exec('ROLLBACK'); throw error; }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sidepaw-companion-openclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"registry": "https://registry.npmjs.org/"
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
},
|
|
23
23
|
"files": [
|
|
24
24
|
"access.mjs",
|
|
25
|
+
"approvals.mjs",
|
|
25
26
|
"delivery.mjs",
|
|
26
27
|
"envelope.mjs",
|
|
27
28
|
"events.mjs",
|
|
@@ -36,5 +37,5 @@
|
|
|
36
37
|
"openclaw.plugin.json",
|
|
37
38
|
"README.md"
|
|
38
39
|
],
|
|
39
|
-
"description": "Sidepaw Companion for OpenClaw
|
|
40
|
+
"description": "Sidepaw Companion for OpenClaw: private, encrypted notifications and approvals for your iPhone."
|
|
40
41
|
}
|
package/relay.mjs
CHANGED
|
@@ -3,16 +3,16 @@ import { encryptAlert } from './envelope.mjs';
|
|
|
3
3
|
|
|
4
4
|
export function relayOrigin(value) {
|
|
5
5
|
const url = new URL(value);
|
|
6
|
-
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw new Error('Invalid
|
|
6
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw new Error('Invalid Sidepaw relay origin');
|
|
7
7
|
return url.origin;
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
export function relaySender({identity,allowedOrigins,fetch:request = fetch,now = Date.now}) {
|
|
11
11
|
return async ({registration,alert,testId}) => {
|
|
12
12
|
const origin = relayOrigin(registration.relayOrigin);
|
|
13
|
-
if (!allowedOrigins.includes(origin)) throw new Error('
|
|
13
|
+
if (!allowedOrigins.includes(origin)) throw new Error('Sidepaw relay is not approved');
|
|
14
14
|
const envelope = encryptAlert({...registration,alert,testId});
|
|
15
|
-
const bytes = Buffer.from(JSON.stringify({operation:'
|
|
15
|
+
const bytes = Buffer.from(JSON.stringify({operation:'sidepaw.push.send',relayHandle:registration.relayHandle,
|
|
16
16
|
sendGrant:registration.sendGrant,issuedAtMs:now(),envelope}));
|
|
17
17
|
const response = await request(`${origin}/v1/push/send`,{
|
|
18
18
|
method:'POST',headers:{'content-type':'application/json'},redirect:'error',signal:AbortSignal.timeout(15000),
|
package/service.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ingestGatewayEvent } from './events.mjs';
|
|
2
|
-
import {
|
|
2
|
+
import { processNextAlert } from './delivery.mjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Connects a gateway's authenticated live event source to the durable queue.
|
|
@@ -56,7 +56,7 @@ export class GatewayPushService {
|
|
|
56
56
|
}
|
|
57
57
|
async pump(generation) {
|
|
58
58
|
for (let index = 0; index < this.batchSize && this.running && generation === this.generation; index++) {
|
|
59
|
-
const result = await
|
|
59
|
+
const result = await processNextAlert({ ledger: this.ledger, resolveDestination: this.resolveDestination,
|
|
60
60
|
auth: this.auth, send: this.send, shouldContinue: () => this.running && generation === this.generation,
|
|
61
61
|
now: this.now(), retryMs: this.retryMs });
|
|
62
62
|
if (result.state === 'empty') break;
|
package/subscriptions.mjs
CHANGED
|
@@ -7,6 +7,7 @@ const validNode = v => valid(v, 256) && /^[\x21-\x7e]+$/u.test(v);
|
|
|
7
7
|
const validSession = v => valid(v) && /^agent:[^:]+:.+/u.test(v);
|
|
8
8
|
const same = (a, b) => typeof a === 'string' && typeof b === 'string' && Buffer.from(a).equals(Buffer.from(b));
|
|
9
9
|
const TTL = 7 * 24 * 60 * 60 * 1000;
|
|
10
|
+
export const defaultPreferences = Object.freeze({replies:true,questions:true,incoming:true,approvals:true});
|
|
10
11
|
|
|
11
12
|
/** Locally scoped device subscriptions, without APNs tokens or message contents. */
|
|
12
13
|
export class SubscriptionStore {
|
|
@@ -15,16 +16,13 @@ export class SubscriptionStore {
|
|
|
15
16
|
this.db = new DatabaseSync(path);
|
|
16
17
|
if (path !== ':memory:') chmodSync(path, 0o600);
|
|
17
18
|
this.db.exec(`PRAGMA busy_timeout=5000;
|
|
18
|
-
CREATE TABLE IF NOT EXISTS subscriptions (node_id TEXT PRIMARY KEY, topic TEXT NOT NULL, main_session TEXT NOT NULL, agent_id TEXT NOT NULL);
|
|
19
|
+
CREATE TABLE IF NOT EXISTS subscriptions (node_id TEXT PRIMARY KEY, topic TEXT NOT NULL, main_session TEXT NOT NULL, agent_id TEXT NOT NULL, agent_names_json TEXT NOT NULL DEFAULT '{}');
|
|
19
20
|
CREATE TABLE IF NOT EXISTS tracked_runs (node_id TEXT NOT NULL, session_key TEXT NOT NULL, run_id TEXT NOT NULL, expires_at INTEGER NOT NULL, PRIMARY KEY(node_id,session_key,run_id));
|
|
20
21
|
CREATE INDEX IF NOT EXISTS tracked_expiry ON tracked_runs(expires_at);`);
|
|
21
22
|
this.db.exec(`CREATE TABLE IF NOT EXISTS relay_enrollments (
|
|
22
23
|
node_id TEXT PRIMARY KEY, registration_json TEXT NOT NULL, pairing_key TEXT NOT NULL,
|
|
23
24
|
pairing_approved_at INTEGER NOT NULL, preferences_json TEXT NOT NULL
|
|
24
25
|
);`);
|
|
25
|
-
if (!this.db.prepare('PRAGMA table_info(subscriptions)').all().some(column => column.name === 'agent_names_json')) {
|
|
26
|
-
this.db.exec("ALTER TABLE subscriptions ADD COLUMN agent_names_json TEXT NOT NULL DEFAULT '{}'");
|
|
27
|
-
}
|
|
28
26
|
}
|
|
29
27
|
configure(nodeId, { topic, mainSessionKey, defaultAgentId, agentNames = {} }) {
|
|
30
28
|
if (!validNode(nodeId) || !valid(topic, 255) || !validSession(mainSessionKey) || !valid(defaultAgentId, 200) || mainSessionKey.split(':')[1] !== defaultAgentId) throw new Error('Invalid subscription');
|
|
@@ -54,15 +52,19 @@ export class SubscriptionStore {
|
|
|
54
52
|
if (!validNode(nodeId) || !pairing?.publicKey || !Number.isSafeInteger(pairing.approvedAtMs)) throw new Error('Invalid enrollment');
|
|
55
53
|
this.db.prepare(`INSERT INTO relay_enrollments VALUES(?,?,?,?,?) ON CONFLICT(node_id) DO UPDATE SET
|
|
56
54
|
registration_json=excluded.registration_json,pairing_key=excluded.pairing_key,pairing_approved_at=excluded.pairing_approved_at`)
|
|
57
|
-
.run(nodeId,JSON.stringify(registration),pairing.publicKey,pairing.approvedAtMs,JSON.stringify(
|
|
55
|
+
.run(nodeId,JSON.stringify(registration),pairing.publicKey,pairing.approvedAtMs,JSON.stringify(defaultPreferences));
|
|
58
56
|
}
|
|
59
57
|
enrollment(nodeId) {
|
|
60
58
|
const row = this.db.prepare('SELECT * FROM relay_enrollments WHERE node_id=?').get(nodeId);
|
|
61
|
-
return row ? {registration:JSON.parse(row.registration_json),pairingKey:row.pairing_key,pairingApprovedAt:row.pairing_approved_at,preferences:JSON.parse(row.preferences_json)}:null;
|
|
59
|
+
return row ? {registration:JSON.parse(row.registration_json),pairingKey:row.pairing_key,pairingApprovedAt:row.pairing_approved_at,preferences:{...defaultPreferences,...JSON.parse(row.preferences_json)}}:null;
|
|
62
60
|
}
|
|
61
|
+
/** A partial update: categories the phone omits keep their saved value. */
|
|
63
62
|
setPreferences(nodeId, preferences) {
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
const keys = preferences && typeof preferences === 'object' ? Object.keys(preferences) : [];
|
|
64
|
+
if (!keys.length || keys.some(key => !Object.hasOwn(defaultPreferences,key) || typeof preferences[key] !== 'boolean')) throw new Error('Invalid notification preferences');
|
|
65
|
+
const current = this.enrollment(nodeId);
|
|
66
|
+
if (!current) throw new Error('Enroll this phone first');
|
|
67
|
+
this.db.prepare('UPDATE relay_enrollments SET preferences_json=? WHERE node_id=?').run(JSON.stringify({...current.preferences,...preferences}),nodeId);
|
|
66
68
|
}
|
|
67
69
|
remove(nodeId) {
|
|
68
70
|
this.db.prepare('DELETE FROM relay_enrollments WHERE node_id=?').run(nodeId);
|