@qvac/core 0.1.6 → 0.2.1

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.
Files changed (100) hide show
  1. package/.claude/skills/compaction/SKILL.md +1 -1
  2. package/.claude/skills/gh-stack/SKILL.md +24 -24
  3. package/.claude/skills/gh-stack/references/commands.md +2 -2
  4. package/.claude/skills/js-house-style/SKILL.md +1 -1
  5. package/.claude/skills/pr-create/SKILL.md +46 -3
  6. package/.claude/skills/pr-review/SKILL.md +76 -7
  7. package/CLAUDE.md +3 -0
  8. package/README.md +10 -5
  9. package/dist-lib/lib/api/agents.js +3 -3
  10. package/dist-lib/lib/api/chat-groups.d.ts +1 -1
  11. package/dist-lib/lib/api/chat-groups.js +5 -3
  12. package/dist-lib/lib/api/chat.js +2 -2
  13. package/dist-lib/lib/api/current-mesh.d.ts +3 -2
  14. package/dist-lib/lib/api/current-mesh.js +4 -3
  15. package/dist-lib/lib/api/devices.js +1 -0
  16. package/dist-lib/lib/api/index.js +2 -0
  17. package/dist-lib/lib/api/members.d.ts +3 -0
  18. package/dist-lib/lib/api/members.js +23 -0
  19. package/dist-lib/lib/api/mesh.d.ts +14 -3
  20. package/dist-lib/lib/api/mesh.js +20 -3
  21. package/dist-lib/lib/api/watchable.d.ts +1 -1
  22. package/dist-lib/lib/api/watchable.js +1 -1
  23. package/dist-lib/lib/core/agent.d.ts +1 -0
  24. package/dist-lib/lib/core/agent.js +29 -1
  25. package/dist-lib/lib/core/chat-group.d.ts +4 -0
  26. package/dist-lib/lib/core/chat-group.js +43 -1
  27. package/dist-lib/lib/core/chat.d.ts +10 -0
  28. package/dist-lib/lib/core/chat.js +75 -9
  29. package/dist-lib/lib/core/contract/index.js +2 -0
  30. package/dist-lib/lib/core/contract/joined-meshes.d.ts +2 -0
  31. package/dist-lib/lib/core/contract/joined-meshes.js +41 -0
  32. package/dist-lib/lib/core/contract/members.js +68 -2
  33. package/dist-lib/lib/core/contract/writers.js +19 -3
  34. package/dist-lib/lib/core/departures.d.ts +3 -1
  35. package/dist-lib/lib/core/departures.js +6 -4
  36. package/dist-lib/lib/core/device-attestation.d.ts +8 -0
  37. package/dist-lib/lib/core/device-attestation.js +25 -0
  38. package/dist-lib/lib/core/device-invites.d.ts +9 -0
  39. package/dist-lib/lib/core/device-invites.js +40 -0
  40. package/dist-lib/lib/core/files/index.d.ts +2 -1
  41. package/dist-lib/lib/core/files/index.js +1 -1
  42. package/dist-lib/lib/core/files/store/index.d.ts +1 -0
  43. package/dist-lib/lib/core/files/store/server.d.ts +5 -4
  44. package/dist-lib/lib/core/files/store/server.js +10 -6
  45. package/dist-lib/lib/core/helpers/index.d.ts +1 -1
  46. package/dist-lib/lib/core/hosted-agents.d.ts +3 -1
  47. package/dist-lib/lib/core/hosted-agents.js +9 -3
  48. package/dist-lib/lib/core/identity.d.ts +10 -0
  49. package/dist-lib/lib/core/identity.js +45 -0
  50. package/dist-lib/lib/core/invite.d.ts +3 -0
  51. package/dist-lib/lib/core/invite.js +8 -2
  52. package/dist-lib/lib/core/local/index.d.ts +22 -7
  53. package/dist-lib/lib/core/local/index.js +202 -66
  54. package/dist-lib/lib/core/membership.d.ts +8 -2
  55. package/dist-lib/lib/core/membership.js +33 -9
  56. package/dist-lib/lib/core/mesh-seed-handoff.d.ts +17 -0
  57. package/dist-lib/lib/core/mesh-seed-handoff.js +34 -0
  58. package/dist-lib/lib/core/mesh.d.ts +12 -1
  59. package/dist-lib/lib/core/mesh.js +36 -7
  60. package/dist-lib/lib/core/migrations/index.d.ts +3 -1
  61. package/dist-lib/lib/core/migrations/index.js +2 -2
  62. package/dist-lib/lib/core/migrations/membership.js +27 -15
  63. package/dist-lib/lib/core/rank.d.ts +14 -0
  64. package/dist-lib/lib/core/rank.js +23 -0
  65. package/dist-lib/lib/core/sync/index.js +6 -0
  66. package/dist-lib/lib/core.d.ts +91 -13
  67. package/dist-lib/lib/core.js +1051 -207
  68. package/dist-lib/schema/build.js +3 -2
  69. package/dist-lib/schema/engine.js +153 -9
  70. package/dist-lib/schema/field-order.js +4 -1
  71. package/dist-lib/schema/local.js +32 -0
  72. package/dist-lib/schema/qvac.js +45 -6
  73. package/dist-lib/spec/bind.js +35 -0
  74. package/dist-lib/spec/calls.js +37 -27
  75. package/dist-lib/spec/capabilities.d.ts +30 -10
  76. package/dist-lib/spec/hrpc/hrpc.json +135 -5
  77. package/dist-lib/spec/hrpc/index.js +130 -9
  78. package/dist-lib/spec/hrpc/messages.js +408 -14
  79. package/dist-lib/spec/hyperschema/index.js +408 -14
  80. package/dist-lib/spec/hyperschema/schema.json +309 -1
  81. package/dist-lib/spec/hyperschema/types.d.ts +90 -1
  82. package/dist-lib/spec/local/hyperdb/db.json +46 -1
  83. package/dist-lib/spec/local/hyperdb/index.js +209 -2
  84. package/dist-lib/spec/local/hyperdb/messages.js +557 -90
  85. package/dist-lib/spec/local/hyperschema/index.js +240 -2
  86. package/dist-lib/spec/local/hyperschema/schema.json +120 -1
  87. package/dist-lib/spec/local/hyperschema/types.d.ts +33 -1
  88. package/dist-lib/spec/mesh/hyperdb/db.json +16 -1
  89. package/dist-lib/spec/mesh/hyperdb/index.js +71 -2
  90. package/dist-lib/spec/mesh/hyperdb/messages.js +571 -192
  91. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +13 -1
  92. package/dist-lib/spec/mesh/hyperdispatch/index.js +35 -1
  93. package/dist-lib/spec/mesh/hyperdispatch/messages.js +283 -20
  94. package/dist-lib/spec/mesh/hyperschema/index.js +283 -20
  95. package/dist-lib/spec/mesh/hyperschema/schema.json +179 -1
  96. package/dist-lib/spec/mesh/hyperschema/types.d.ts +45 -1
  97. package/package.json +4 -4
  98. package/tui/app.mjs +416 -50
  99. package/tui/boot.mjs +1 -1
  100. package/tui/lib/sidebar.mjs +3 -2
@@ -1,9 +1,13 @@
1
1
  import { randomId } from "./id.js";
2
+ import { place } from "./rank.js";
2
3
  const CHAT_GROUPS = '@qvac/chat-groups';
3
4
  const ACTIVE_CHAT_GROUPS = '@qvac/active-chat-groups';
4
5
  const NAME_MAX_LENGTH = 100;
6
+ export function groupSortKey(group) {
7
+ return group.rank || group.createdAt;
8
+ }
5
9
  export function byGroupOrder(a, b) {
6
- return b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1);
10
+ return groupSortKey(b) - groupSortKey(a) || (a.id < b.id ? -1 : 1);
7
11
  }
8
12
  export async function listChatGroupsIn(snap) {
9
13
  const groups = await snap.find(ACTIVE_CHAT_GROUPS).toArray();
@@ -70,6 +74,44 @@ async function patchChatGroup(store, id, patch) {
70
74
  export async function renameChatGroup(store, id, name) {
71
75
  return patchChatGroup(store, id, { name: assertGroupName(name) });
72
76
  }
77
+ export async function moveChatGroup(store, id, { afterId }) {
78
+ const anchor = afterId || undefined;
79
+ if (anchor === id)
80
+ throw new Error(`a chat group cannot be placed after itself: ${id}`);
81
+ const now = Date.now();
82
+ const snap = store.view.snapshot();
83
+ let current;
84
+ let placement;
85
+ try {
86
+ const group = await snap.get(CHAT_GROUPS, { id });
87
+ if (!group || group.deletedAt)
88
+ throw new Error(`chat group not found: ${id}`);
89
+ current = group;
90
+ const siblings = (await listChatGroupsIn(snap)).filter((sibling) => sibling.id !== id);
91
+ let at = -1;
92
+ if (anchor) {
93
+ at = siblings.findIndex((sibling) => sibling.id === anchor);
94
+ if (at === -1)
95
+ throw new Error(`chat group not found: ${anchor}`);
96
+ }
97
+ placement = place(siblings, groupSortKey, { at, now });
98
+ }
99
+ finally {
100
+ await snap.close();
101
+ }
102
+ const stamp = (row, rank) => ({
103
+ ...row,
104
+ rank,
105
+ updatedAt: Math.max(now, row.updatedAt)
106
+ });
107
+ const batch = store.batch();
108
+ for (const { row, rank } of placement.respaced) {
109
+ batch.dispatch('put-chat-group', { group: stamp(row, rank) });
110
+ }
111
+ batch.dispatch('put-chat-group', { group: stamp(current, placement.rank) });
112
+ await batch.flush();
113
+ return mustGetActiveChatGroup(store, id);
114
+ }
73
115
  export async function deleteChatGroup(store, id) {
74
116
  const current = await mustGetChatGroup(store, id);
75
117
  const now = Date.now();
@@ -8,12 +8,18 @@ export interface Sidebar {
8
8
  readonly chats: ChatListing[];
9
9
  readonly groups: QvacChatGroup[];
10
10
  }
11
+ export declare function chatSortKey(chat: {
12
+ rank?: number;
13
+ rankedAt?: number;
14
+ lastActivityAt: number;
15
+ }): number;
11
16
  export declare function liveGroupIds(snap: HyperDB): Promise<Set<string>>;
12
17
  export declare function lastActivity(snap: HyperDB): Promise<Map<string, number>>;
13
18
  export declare function enrichChat(store: Mesh, chat: QvacChat): Promise<ChatListing>;
14
19
  export declare function enrichIn(snap: HyperDB, chat: QvacChat): Promise<ChatListing>;
15
20
  export declare function enrichAll(chats: ReadonlyArray<QvacChat>, activity: Map<string, number>, liveGroups: Set<string>): ChatListing[];
16
21
  export declare function listSidebar(store: Mesh): Promise<Sidebar>;
22
+ export declare function listSidebarIn(snap: HyperDB): Promise<Sidebar>;
17
23
  export declare function listChats(store: Mesh): Promise<ChatListing[]>;
18
24
  export declare function getChat(store: Mesh, id: string): Promise<QvacChat | null>;
19
25
  export declare function mustGetChat(store: Mesh, id: string): Promise<QvacChat>;
@@ -30,6 +36,10 @@ export declare function createChat(store: Mesh, input: {
30
36
  export declare function renameChat(store: Mesh, id: string, title: string): Promise<ChatListing>;
31
37
  export declare function setChatRagEnabled(store: Mesh, id: string, ragEnabled: boolean): Promise<ChatListing>;
32
38
  export declare function setChatGroup(store: Mesh, id: string, groupId: string | null | undefined): Promise<ChatListing>;
39
+ export declare function moveChat(store: Mesh, id: string, { groupId, afterId }: {
40
+ groupId?: string | null;
41
+ afterId?: string | null;
42
+ }): Promise<ChatListing>;
33
43
  export declare function setChatWebSearchEnabled(store: Mesh, id: string, webSearchEnabled: boolean): Promise<ChatListing>;
34
44
  export declare function removeChatKnowledge(store: Mesh, chatId: string, at: number): Promise<void>;
35
45
  export declare function removeChatAttachments(store: Mesh, deviceId: Buffer, chatId: string, at: number): Promise<void>;
@@ -2,6 +2,7 @@ import { listChatGroupsIn, mustGetActiveChatGroup } from "./chat-group.js";
2
2
  import { appendChunk, listChunks, updateOp } from "./chunk.js";
3
3
  import { randomId } from "./id.js";
4
4
  import { assertRemovableAt } from "./files/index.js";
5
+ import { place } from "./rank.js";
5
6
  const CHATS = '@qvac/chats';
6
7
  const CHAT_GROUPS = '@qvac/chat-groups';
7
8
  const ACTIVE_CHATS = '@qvac/active-chats';
@@ -9,8 +10,11 @@ const ACTIVE_CHATS_BY_AGENT = '@qvac/active-chats-by-agent';
9
10
  const ACTIVE_CHAT_GROUPS = '@qvac/active-chat-groups';
10
11
  const CHUNK_COUNTERS = '@qvac/chunk-counters';
11
12
  const TERMINAL_RUN_STATES = new Set(['completed', 'failed', 'canceled']);
13
+ export function chatSortKey(chat) {
14
+ return chat.rank && (chat.rankedAt ?? 0) >= chat.lastActivityAt ? chat.rank : chat.lastActivityAt;
15
+ }
12
16
  function byChatOrder(a, b) {
13
- return a.lastActivityAt - b.lastActivityAt || (a.id < b.id ? -1 : 1);
17
+ return chatSortKey(a) - chatSortKey(b) || (a.id < b.id ? -1 : 1);
14
18
  }
15
19
  export async function liveGroupIds(snap) {
16
20
  const groups = await snap.find(ACTIVE_CHAT_GROUPS).toArray();
@@ -51,15 +55,18 @@ export function enrichAll(chats, activity, liveGroups) {
51
55
  export async function listSidebar(store) {
52
56
  const snap = store.view.snapshot();
53
57
  try {
54
- const chats = await snap.find(ACTIVE_CHATS).toArray();
55
- const [activity, groups] = await Promise.all([lastActivity(snap), listChatGroupsIn(snap)]);
56
- const live = new Set(groups.map((group) => group.id));
57
- return { chats: enrichAll(chats, activity, live).sort(byChatOrder), groups };
58
+ return await listSidebarIn(snap);
58
59
  }
59
60
  finally {
60
61
  await snap.close();
61
62
  }
62
63
  }
64
+ export async function listSidebarIn(snap) {
65
+ const chats = await snap.find(ACTIVE_CHATS).toArray();
66
+ const [activity, groups] = await Promise.all([lastActivity(snap), listChatGroupsIn(snap)]);
67
+ const live = new Set(groups.map((group) => group.id));
68
+ return { chats: enrichAll(chats, activity, live).sort(byChatOrder), groups };
69
+ }
63
70
  export async function listChats(store) {
64
71
  return (await listSidebar(store)).chats;
65
72
  }
@@ -107,7 +114,9 @@ export async function createChat(store, input) {
107
114
  return listingOf(chat, false, undefined);
108
115
  }
109
116
  async function patchChat(store, id, patch) {
110
- const current = await mustGetActiveChat(store, id);
117
+ return patchChatRow(store, await mustGetActiveChat(store, id), patch);
118
+ }
119
+ async function patchChatRow(store, current, patch) {
111
120
  const updated = { ...current, ...patch, updatedAt: Date.now() };
112
121
  await store.dispatch('put-chat', { chat: updated });
113
122
  return enrichChat(store, updated);
@@ -119,9 +128,66 @@ export function setChatRagEnabled(store, id, ragEnabled) {
119
128
  return patchChat(store, id, { ragEnabled });
120
129
  }
121
130
  export async function setChatGroup(store, id, groupId) {
122
- if (groupId)
123
- await mustGetActiveChatGroup(store, groupId);
124
- return patchChat(store, id, { groupId: groupId || undefined });
131
+ const target = groupId || undefined;
132
+ if (target)
133
+ await mustGetActiveChatGroup(store, target);
134
+ const current = await mustGetActiveChat(store, id);
135
+ const kept = (current.groupId || undefined) === target;
136
+ return patchChatRow(store, current, kept ? { groupId: target } : { groupId: target, rank: undefined, rankedAt: undefined });
137
+ }
138
+ export async function moveChat(store, id, { groupId, afterId }) {
139
+ const target = groupId || undefined;
140
+ const anchor = afterId || undefined;
141
+ if (anchor === id)
142
+ throw new Error(`a chat cannot be placed after itself: ${id}`);
143
+ const now = Date.now();
144
+ const snap = store.view.snapshot();
145
+ let moved;
146
+ let placement;
147
+ let stored;
148
+ try {
149
+ if (target) {
150
+ const group = await snap.get(CHAT_GROUPS, { id: target });
151
+ if (!group || group.deletedAt)
152
+ throw new Error(`chat group not found: ${target}`);
153
+ }
154
+ const { chats } = await listSidebarIn(snap);
155
+ const me = chats.find((chat) => chat.id === id);
156
+ if (!me)
157
+ throw new Error(`chat not found: ${id}`);
158
+ moved = me;
159
+ const siblings = chats
160
+ .filter((sibling) => sibling.id !== id && (sibling.groupId || undefined) === target)
161
+ .reverse();
162
+ let at = -1;
163
+ if (anchor) {
164
+ at = siblings.findIndex((sibling) => sibling.id === anchor);
165
+ if (at === -1) {
166
+ throw new Error(`chat ${anchor} is not in the ${target ? `group ${target}` : 'ungrouped list'}`);
167
+ }
168
+ }
169
+ placement = place(siblings, chatSortKey, { at, now });
170
+ stored = new Map(await Promise.all(placement.respaced.map(async ({ row }) => [row.id, (await snap.get(CHATS, { id: row.id })) ?? row])));
171
+ }
172
+ finally {
173
+ await snap.close();
174
+ }
175
+ const stamp = (chat, lastActivityAt, rank) => ({
176
+ ...chat,
177
+ rank,
178
+ rankedAt: Math.max(now, lastActivityAt),
179
+ updatedAt: Math.max(now, chat.updatedAt ?? 0)
180
+ });
181
+ const batch = store.batch();
182
+ for (const { row, rank } of placement.respaced) {
183
+ batch.dispatch('put-chat', { chat: stamp(stored.get(row.id), row.lastActivityAt, rank) });
184
+ }
185
+ const { lastActivityAt, ...chat } = moved;
186
+ batch.dispatch('put-chat', {
187
+ chat: { ...stamp(chat, lastActivityAt, placement.rank), groupId: target }
188
+ });
189
+ await batch.flush();
190
+ return enrichChat(store, await mustGetActiveChat(store, id));
125
191
  }
126
192
  export function setChatWebSearchEnabled(store, id, webSearchEnabled) {
127
193
  return patchChat(store, id, { webSearchEnabled });
@@ -7,6 +7,7 @@ import { registerChunkRoutes } from "./chunks.js";
7
7
  import { registerDeviceRoutes } from "./devices.js";
8
8
  import { registerIndexingRoutes } from "./indexing.js";
9
9
  import { registerKnowledgeRoutes } from "./knowledge.js";
10
+ import { registerJoinedMeshRoutes } from "./joined-meshes.js";
10
11
  import { registerMemberRoutes } from "./members.js";
11
12
  import { registerSeedDefaultsRoutes } from "./seed-defaults.js";
12
13
  import { registerToolActivityRoutes } from "./tool-activity.js";
@@ -26,5 +27,6 @@ export function registerRoutes(router) {
26
27
  registerToolConfigsRoutes(router);
27
28
  registerToolActivityRoutes(router);
28
29
  registerAttestationRoutes(router);
30
+ registerJoinedMeshRoutes(router);
29
31
  registerMemberRoutes(router);
30
32
  }
@@ -0,0 +1,2 @@
1
+ import type { Router } from '../../../spec/mesh/hyperdispatch/index.js';
2
+ export declare function registerJoinedMeshRoutes(router: Router): void;
@@ -0,0 +1,41 @@
1
+ import { liveDeviceForWriter, trackActivity } from "./activity.js";
2
+ const JOINED_MESHES = '@qvac/joined-meshes';
3
+ export function registerJoinedMeshRoutes(router) {
4
+ router.add('@qvac/put-joined-mesh', trackActivity(async ({ room }, { tx, node, log }) => {
5
+ const author = await liveDeviceForWriter(tx, node.key);
6
+ if (!author?.memberId?.equals(room.memberId)) {
7
+ log?.warn('contract', 'put-joined-mesh refused: author is not a device of that member', {
8
+ meshKey: room.meshKey.toString('hex').slice(0, 8)
9
+ });
10
+ return;
11
+ }
12
+ const existing = await tx.get(JOINED_MESHES, { meshKey: room.meshKey });
13
+ if (existing && existing.joinedAt > room.joinedAt) {
14
+ log?.debug('contract', 'put-joined-mesh dropped: stale joinedAt', {
15
+ meshKey: room.meshKey.toString('hex').slice(0, 8)
16
+ });
17
+ return;
18
+ }
19
+ const rejoin = Boolean(existing) && room.joinedAt > existing.joinedAt;
20
+ const next = existing ? merge(room, existing, rejoin) : room;
21
+ await tx.insert(JOINED_MESHES, next);
22
+ log?.debug('contract', next.leftAt ? 'joined room released' : 'joined room recorded', {
23
+ meshKey: room.meshKey.toString('hex').slice(0, 8)
24
+ });
25
+ return next;
26
+ }));
27
+ }
28
+ function merge(room, existing, rejoin) {
29
+ const relabels = (room.labeledAt ?? 0) > (existing.labeledAt ?? 0);
30
+ const remarks = (room.sharedAt ?? 0) > (existing.sharedAt ?? 0);
31
+ return {
32
+ meshKey: room.meshKey,
33
+ memberId: room.memberId,
34
+ joinedAt: room.joinedAt,
35
+ leftAt: rejoin ? room.leftAt : room.leftAt || existing.leftAt,
36
+ label: relabels ? room.label : existing.label,
37
+ labeledAt: relabels ? room.labeledAt : existing.labeledAt,
38
+ shared: remarks ? room.shared : existing.shared,
39
+ sharedAt: remarks ? room.sharedAt : existing.sharedAt
40
+ };
41
+ }
@@ -1,9 +1,19 @@
1
- import { verifyDeviceProof } from "../identity.js";
1
+ import { bareDeviceProof, claimAttestation, verifyDeviceProof, verifyMemberClaim } from "../identity.js";
2
2
  import { liveDeviceForWriter, trackActivity } from "./activity.js";
3
3
  const DEVICES = '@qvac/devices';
4
4
  const MEMBERS = '@qvac/members';
5
+ function hex(buffer) {
6
+ return buffer.toString('hex').slice(0, 16);
7
+ }
5
8
  function link(device, memberId, proof, attestedAt) {
6
- return { ...device, memberId, memberProof: proof, attestedAt };
9
+ return {
10
+ ...device,
11
+ memberId,
12
+ memberProof: proof,
13
+ attestedAt,
14
+ claimedMemberId: null,
15
+ inviteToken: null
16
+ };
7
17
  }
8
18
  export function registerMemberRoutes(router) {
9
19
  router.add('@qvac/mint-member', trackActivity(async ({ member, proof }, { tx, node, log }) => {
@@ -59,6 +69,62 @@ export function registerMemberRoutes(router) {
59
69
  await tx.insert(MEMBERS, next);
60
70
  return next;
61
71
  }));
72
+ router.add('@qvac/join-member', trackActivity(async ({ member, proof }, context) => {
73
+ const { tx, node, log, meshPublicKey } = context;
74
+ const author = await liveDeviceForWriter(tx, node.key);
75
+ const ids = {
76
+ writer: hex(node.key),
77
+ device: author ? hex(author.id) : null,
78
+ member: hex(member.id)
79
+ };
80
+ if (!author) {
81
+ log?.warn('contract', 'join-member dropped: the writer has no device row', ids);
82
+ return;
83
+ }
84
+ if (author.memberId) {
85
+ if (author.memberId.equals(member.id)) {
86
+ log?.debug('contract', 'join-member dropped: the device is already owned by this member', ids);
87
+ }
88
+ else {
89
+ log?.warn('contract', 'join-member dropped: the device is owned by another member', {
90
+ ...ids,
91
+ owner: hex(author.memberId)
92
+ });
93
+ }
94
+ return;
95
+ }
96
+ const attestation = claimAttestation(meshPublicKey, author.id, node.key);
97
+ const valid = await verifyMemberClaim(proof, {
98
+ memberId: member.id,
99
+ deviceId: author.id,
100
+ attestation
101
+ });
102
+ if (!valid) {
103
+ log?.warn('contract', 'join-member dropped: the claim does not bind this mesh and writer', {
104
+ ...ids,
105
+ mesh: hex(meshPublicKey),
106
+ proofBytes: proof.byteLength
107
+ });
108
+ return;
109
+ }
110
+ const stored = bareDeviceProof(proof);
111
+ if (!stored) {
112
+ log?.warn('contract', 'join-member dropped: the proof does not re-encode', ids);
113
+ return;
114
+ }
115
+ const existing = await tx.get(MEMBERS, { id: member.id });
116
+ const joined = existing ?? {
117
+ id: member.id,
118
+ name: member.name,
119
+ joinedAt: member.joinedAt,
120
+ updatedAt: member.updatedAt
121
+ };
122
+ if (!existing)
123
+ await tx.insert(MEMBERS, joined);
124
+ await tx.insert(DEVICES, link(author, member.id, stored, member.joinedAt));
125
+ log?.info('contract', 'member joined', ids);
126
+ return joined;
127
+ }));
62
128
  router.add('@qvac/attest-member-device', async (op, { tx, node, log }) => {
63
129
  const device = await tx.get(DEVICES, { id: op.deviceId });
64
130
  if (!device) {
@@ -1,7 +1,8 @@
1
1
  import crypto from 'hypercore-crypto';
2
2
  import { markWriterRevoked, trackActivity } from "./activity.js";
3
+ import { verifyWriterClaim } from "../device-attestation.js";
3
4
  const DEVICES = '@qvac/devices';
4
- async function admitDevice({ tx, log }, id, device, writerKey) {
5
+ async function admitDevice({ tx, meshPublicKey, log }, id, device, writerKey, claim) {
5
6
  const existing = await tx.get(DEVICES, { id });
6
7
  if (!device) {
7
8
  if (!existing)
@@ -14,6 +15,19 @@ async function admitDevice({ tx, log }, id, device, writerKey) {
14
15
  log?.debug('contract', 'admission refused: claim is not newer than the device row');
15
16
  return 'refused';
16
17
  }
18
+ if (existing?.writerKey &&
19
+ !existing.writerKey.equals(writerKey) &&
20
+ !verifyWriterClaim(claim?.deviceSignature, {
21
+ meshPublicKey,
22
+ deviceId: id,
23
+ writerKey,
24
+ joinedAt: device.joinedAt
25
+ })) {
26
+ log?.warn('contract', 'admission refused: the device did not sign for this writer key', {
27
+ id: id.toString('hex').slice(0, 16)
28
+ });
29
+ return 'refused';
30
+ }
17
31
  const alreadyAdmitted = existing && !existing.revoked && existing.writerKey?.equals(writerKey) === true;
18
32
  await tx.insert(DEVICES, {
19
33
  ...existing,
@@ -30,6 +44,8 @@ async function admitDevice({ tx, log }, id, device, writerKey) {
30
44
  appBuild: device.appBuild ?? existing?.appBuild,
31
45
  appChannel: device.appChannel ?? existing?.appChannel,
32
46
  platform: device.platform ?? existing?.platform,
47
+ claimedMemberId: claim?.claimedMemberId ?? existing?.claimedMemberId,
48
+ inviteToken: claim?.inviteToken ?? existing?.inviteToken,
33
49
  id,
34
50
  writerKey,
35
51
  revoked: false,
@@ -51,7 +67,7 @@ export function registerWriterRoutes(router) {
51
67
  await context.host.addWriter(payload.writerKey);
52
68
  return;
53
69
  }
54
- const admission = await admitDevice(context, payload.device.id, payload.device, payload.writerKey);
70
+ const admission = await admitDevice(context, payload.device.id, payload.device, payload.writerKey, payload);
55
71
  if (admission !== 'admitted')
56
72
  return;
57
73
  await context.host.addWriter(payload.writerKey);
@@ -103,7 +119,7 @@ export function registerWriterRoutes(router) {
103
119
  await context.host.addWriter(context.node.key);
104
120
  return;
105
121
  }
106
- const admission = await admitDevice(context, id, payload.device, context.node.key);
122
+ const admission = await admitDevice(context, id, payload.device, context.node.key, payload);
107
123
  if (admission === 'refused')
108
124
  return;
109
125
  await context.host.addWriter(context.node.key);
@@ -10,6 +10,7 @@ interface DepartureRows {
10
10
  }
11
11
  export interface PendingDeparturesOptions {
12
12
  swarm: Hyperswarm;
13
+ isPooled: (key: Buffer) => boolean;
13
14
  logger?: Logger | null;
14
15
  blindPeerKeys?: ReadonlyArray<Buffer>;
15
16
  blindPeeringOpts?: BlindPeeringOpts;
@@ -23,12 +24,13 @@ export declare class PendingDepartures {
23
24
  private readonly _blindPeerKeys;
24
25
  private readonly _blindPeeringOpts;
25
26
  private readonly _wakeup;
27
+ private readonly _isPooled;
26
28
  private readonly _active;
27
29
  private readonly _parked;
28
30
  private readonly _lock;
29
31
  private _closing;
30
32
  constructor(store: Corestore, local: DepartureRows, opts: PendingDeparturesOptions);
31
- flush(activeKey?: Buffer | null): void;
33
+ flush(): void;
32
34
  private _flush;
33
35
  private _deliver;
34
36
  park(key: Buffer): Promise<void>;
@@ -9,6 +9,7 @@ export class PendingDepartures {
9
9
  _blindPeerKeys;
10
10
  _blindPeeringOpts;
11
11
  _wakeup;
12
+ _isPooled;
12
13
  _active = new Map();
13
14
  _parked = new Set();
14
15
  _lock = new ScopeLock();
@@ -17,15 +18,16 @@ export class PendingDepartures {
17
18
  this._store = store;
18
19
  this._local = local;
19
20
  this._swarm = opts.swarm;
21
+ this._isPooled = opts.isPooled;
20
22
  this._log = opts.logger ?? null;
21
23
  this._blindPeerKeys = opts.blindPeerKeys ?? [];
22
24
  this._blindPeeringOpts = opts.blindPeeringOpts;
23
25
  this._wakeup = opts.wakeup;
24
26
  }
25
- flush(activeKey) {
26
- void this._flush(activeKey ?? null).catch((err) => this._log?.warn(SCOPE, 'departure flush failed', err));
27
+ flush() {
28
+ void this._flush().catch((err) => this._log?.warn(SCOPE, 'departure flush failed', err));
27
29
  }
28
- async _flush(activeKey) {
30
+ async _flush() {
29
31
  await this._lock.lock();
30
32
  try {
31
33
  if (this._closing)
@@ -34,7 +36,7 @@ export class PendingDepartures {
34
36
  if (this._closing)
35
37
  return;
36
38
  const hex = row.key.toString('hex');
37
- if (activeKey?.equals(row.key) || this._parked.has(hex) || this._active.has(hex)) {
39
+ if (this._isPooled(row.key) || this._parked.has(hex) || this._active.has(hex)) {
38
40
  continue;
39
41
  }
40
42
  const mesh = new Mesh(this._store, {
@@ -1,6 +1,14 @@
1
+ export interface WriterClaimBinding {
2
+ readonly meshPublicKey: Buffer;
3
+ readonly deviceId: Buffer;
4
+ readonly writerKey: Buffer;
5
+ readonly joinedAt: number;
6
+ }
1
7
  export interface DeviceAttestation {
2
8
  readonly deviceId: Buffer;
3
9
  readonly signature: Buffer;
4
10
  }
5
11
  export declare function signDeviceAttestation(secretKey: Buffer, deviceId: Buffer): DeviceAttestation;
6
12
  export declare function verifyDeviceAttestation(publicKey: Buffer, attestation: DeviceAttestation): boolean;
13
+ export declare function signWriterClaim(secretKey: Buffer, binding: WriterClaimBinding): Buffer;
14
+ export declare function verifyWriterClaim(signature: Buffer | null | undefined, binding: WriterClaimBinding): boolean;
@@ -1,4 +1,6 @@
1
+ import c from 'compact-encoding';
1
2
  import crypto from 'hypercore-crypto';
3
+ const [WRITER_CLAIM_NAMESPACE] = crypto.namespace('@qvac/core/device-writer-claim', 1);
2
4
  export function signDeviceAttestation(secretKey, deviceId) {
3
5
  return { deviceId, signature: crypto.sign(deviceId, secretKey) };
4
6
  }
@@ -10,3 +12,26 @@ export function verifyDeviceAttestation(publicKey, attestation) {
10
12
  return false;
11
13
  }
12
14
  }
15
+ function writerClaimMessage(binding) {
16
+ const joinedAt = c.encode(c.uint, binding.joinedAt);
17
+ return crypto.hash([
18
+ WRITER_CLAIM_NAMESPACE,
19
+ binding.meshPublicKey,
20
+ binding.deviceId,
21
+ binding.writerKey,
22
+ joinedAt
23
+ ]);
24
+ }
25
+ export function signWriterClaim(secretKey, binding) {
26
+ return crypto.sign(writerClaimMessage(binding), secretKey);
27
+ }
28
+ export function verifyWriterClaim(signature, binding) {
29
+ if (!signature)
30
+ return false;
31
+ try {
32
+ return crypto.verify(writerClaimMessage(binding), signature, binding.deviceId);
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
@@ -0,0 +1,9 @@
1
+ export interface DeviceInvites {
2
+ issue(): Promise<Buffer>;
3
+ redeem(token: Buffer | null | undefined, deviceId: Buffer): Promise<boolean>;
4
+ }
5
+ export interface DeviceInviteStore {
6
+ get(key: string): Promise<unknown>;
7
+ set(key: string, value: unknown): Promise<void>;
8
+ }
9
+ export declare function openDeviceInvites(store: DeviceInviteStore): DeviceInvites;
@@ -0,0 +1,40 @@
1
+ import crypto from 'hypercore-crypto';
2
+ import ScopeLock from 'scope-lock';
3
+ import { deviceInviteToken } from "./identity.js";
4
+ const NONCES_KEY = 'device-invite-nonces';
5
+ export function openDeviceInvites(store) {
6
+ const lock = new ScopeLock();
7
+ async function nonces() {
8
+ const value = await store.get(NONCES_KEY);
9
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : [];
10
+ }
11
+ return {
12
+ async issue() {
13
+ const nonce = crypto.randomBytes(32);
14
+ await lock.lock();
15
+ try {
16
+ await store.set(NONCES_KEY, [...(await nonces()), nonce.toString('hex')]);
17
+ }
18
+ finally {
19
+ lock.unlock();
20
+ }
21
+ return nonce;
22
+ },
23
+ async redeem(token, deviceId) {
24
+ if (!token)
25
+ return false;
26
+ await lock.lock();
27
+ try {
28
+ const issued = await nonces();
29
+ const spent = issued.findIndex((hex) => deviceInviteToken(Buffer.from(hex, 'hex'), deviceId).equals(token));
30
+ if (spent === -1)
31
+ return false;
32
+ await store.set(NONCES_KEY, issued.filter((_, index) => index !== spent));
33
+ return true;
34
+ }
35
+ finally {
36
+ lock.unlock();
37
+ }
38
+ }
39
+ };
40
+ }
@@ -130,4 +130,5 @@ export declare class Files extends EventEmitter {
130
130
  export { MemoryVectorIndex, RAG_KNOWLEDGE_OFF_NOTICE, RAG_TRUNCATED_NOTICE, RAG_UNAVAILABLE_NOTICE, WEB_TOOLS, chooseRagNotice, citedByPhraseOverlap, createRagSourceTagFilter, formatFullDocumentContext, formatRagContext, isFullTextHit, isWholeDocumentQuery, referencedDocuments, isTruncatedFullTextHit, sourcesFromHits, webSourcesFromToolResult, withoutDataChannel } from './rag/index.ts';
131
131
  export type { IndexingEmbedder, RagExtractors, RagSource, VectorIndex } from './rag/index.ts';
132
132
  export { attachTurnDocumentIds, groupAttachmentsByMessage } from './records/index.ts';
133
- export { CoreBlobServer } from './store/index.ts';
133
+ export { CoreBlobServer, parseBlobReferenceCoreKey } from './store/index.ts';
134
+ export type { MeshBlobKeys } from './store/index.ts';
@@ -582,4 +582,4 @@ export class Files extends EventEmitter {
582
582
  }
583
583
  export { MemoryVectorIndex, RAG_KNOWLEDGE_OFF_NOTICE, RAG_TRUNCATED_NOTICE, RAG_UNAVAILABLE_NOTICE, WEB_TOOLS, chooseRagNotice, citedByPhraseOverlap, createRagSourceTagFilter, formatFullDocumentContext, formatRagContext, isFullTextHit, isWholeDocumentQuery, referencedDocuments, isTruncatedFullTextHit, sourcesFromHits, webSourcesFromToolResult, withoutDataChannel } from "./rag/index.js";
584
584
  export { attachTurnDocumentIds, groupAttachmentsByMessage } from "./records/index.js";
585
- export { CoreBlobServer } from "./store/index.js";
585
+ export { CoreBlobServer, parseBlobReferenceCoreKey } from "./store/index.js";
@@ -4,6 +4,7 @@ import type Hyperblobs from 'hyperblobs';
4
4
  import { stringifyBlobId, writeBlob, type BlobHost } from './blob.ts';
5
5
  import { readBlobReference, readBlobReferenceBytes, downloadBlobReference } from './reference.ts';
6
6
  export { CoreBlobServer } from './server.ts';
7
+ export type { MeshBlobKeys, MeshForBlobCore } from './server.ts';
7
8
  export { compareBlobReferences, isInvalidBlobReferenceError, parseBlobReference, parseBlobReferenceCoreKey } from './reference.ts';
8
9
  export type { BlobReferenceReadOptions } from './reference.ts';
9
10
  export type { WriteProgress } from './blob.ts';
@@ -2,10 +2,11 @@ import type Corestore from 'corestore';
2
2
  import ReadyResource from 'ready-resource';
3
3
  import type { LinkableAttachment } from '../../attachment-link.ts';
4
4
  import type Hyperblobs from 'hyperblobs';
5
- export type CurrentMeshKeys = () => {
5
+ export type MeshBlobKeys = {
6
6
  blobs: Hyperblobs;
7
7
  encryptionKey: Buffer;
8
- } | null;
8
+ };
9
+ export type MeshForBlobCore = (coreKey: string | null) => MeshBlobKeys | null;
9
10
  export declare class CoreBlobServer extends ReadyResource {
10
11
  private readonly _store;
11
12
  private readonly _mesh;
@@ -13,11 +14,11 @@ export declare class CoreBlobServer extends ReadyResource {
13
14
  private readonly _probes;
14
15
  private readonly _readTimeoutMs;
15
16
  private _suspended;
16
- constructor(store: Corestore, mesh: CurrentMeshKeys, { readTimeoutMs }?: {
17
+ constructor(store: Corestore, mesh: MeshForBlobCore, { readTimeoutMs }?: {
17
18
  readTimeoutMs?: number | undefined;
18
19
  });
19
20
  get port(): number;
20
- link({ blobId, mimeType }: LinkableAttachment): string | null;
21
+ link({ blobId, mimeType }: LinkableAttachment, source?: MeshBlobKeys | null): string | null;
21
22
  suspend(): Promise<void>;
22
23
  resume(): Promise<void>;
23
24
  _open(): Promise<void>;