@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
@@ -20,16 +20,15 @@ export class CoreBlobServer extends ReadyResource {
20
20
  get port() {
21
21
  return this._server.port;
22
22
  }
23
- link({ blobId, mimeType }) {
23
+ link({ blobId, mimeType }, source = this._mesh(null)) {
24
24
  if (!this.opened || this.closing)
25
25
  return null;
26
- const current = this._mesh();
27
- if (!current)
26
+ if (!source)
28
27
  return null;
29
28
  const parsed = this._parse(blobId);
30
29
  if (!parsed || parsed.inline)
31
30
  return null;
32
- return this._server.getLink(parsed.coreKey ?? current.blobs.core.key.toString('hex'), {
31
+ return this._server.getLink(parsed.coreKey ?? source.blobs.core.key.toString('hex'), {
33
32
  blob: parsed.blobId,
34
33
  type: mimeType || 'application/octet-stream'
35
34
  });
@@ -65,7 +64,7 @@ export class CoreBlobServer extends ReadyResource {
65
64
  await this._store.close();
66
65
  }
67
66
  async _resolve(key, info) {
68
- const current = this._mesh();
67
+ const current = this._mesh(key.toString('hex'));
69
68
  if (!current || this.closing || this._suspended)
70
69
  return null;
71
70
  const keys = { encryptionKey: current.encryptionKey };
@@ -91,7 +90,12 @@ export class CoreBlobServer extends ReadyResource {
91
90
  if (!position || this.closing || this._suspended || Date.now() >= deadline)
92
91
  return null;
93
92
  const bytes = await core.get(position[0], { timeout: Math.max(1, deadline - Date.now()) });
94
- return bytes && this._mesh() === current && !this.closing && !this._suspended ? keys : null;
93
+ return bytes &&
94
+ this._mesh(key.toString('hex')) === current &&
95
+ !this.closing &&
96
+ !this._suspended
97
+ ? keys
98
+ : null;
95
99
  }
96
100
  catch {
97
101
  return null;
@@ -1,5 +1,5 @@
1
1
  import type { QvacDevice, QvacSeedDefaultsOperation } from '../../../spec/mesh/hyperschema/types.d.ts';
2
2
  import type { Mesh } from '../mesh.ts';
3
- export declare function buildDefaultSeed(device: QvacDevice, blindPeerKeys: ReadonlyArray<Buffer>): QvacSeedDefaultsOperation;
3
+ export declare function buildDefaultSeed(device: Pick<QvacDevice, 'id' | 'recommendedModelName'>, blindPeerKeys: ReadonlyArray<Buffer>): QvacSeedDefaultsOperation;
4
4
  export declare function isOwnRevokedRow(mesh: Mesh, device: QvacDevice): boolean;
5
5
  export declare function isOwnKickedRow(mesh: Mesh, device: QvacDevice): boolean;
@@ -3,7 +3,8 @@ import type { AssistantSkill } from '../../spec/hyperschema/types.d.ts';
3
3
  import type { openLocalStore } from './local/index.ts';
4
4
  import type { Mesh } from './mesh.ts';
5
5
  import type { SecretRequest } from './secret-handoff.ts';
6
- export declare const HELD_AGENTS_KEY = "skill-values.held-agents";
6
+ export declare const LEGACY_HELD_AGENTS_KEY = "skill-values.held-agents";
7
+ export declare function heldAgentsKey(meshKey: Buffer): string;
7
8
  export interface HostedAgentsOptions {
8
9
  readonly mesh: Mesh;
9
10
  readonly local: ReturnType<typeof openLocalStore>;
@@ -21,6 +22,7 @@ export declare class HostedAgents {
21
22
  private readonly _send;
22
23
  private readonly _onmoved;
23
24
  private readonly _log;
25
+ private readonly _heldKey;
24
26
  private readonly _lock;
25
27
  private _closed;
26
28
  private readonly _onDirty;
@@ -3,7 +3,10 @@ import ScopeLock from 'scope-lock';
3
3
  import { getAgent, listAgents } from "./agent.js";
4
4
  import { agentSkillValues } from "./skill-secrets.js";
5
5
  const SCOPE = ['p2p', 'skill-values'];
6
- export const HELD_AGENTS_KEY = 'skill-values.held-agents';
6
+ export const LEGACY_HELD_AGENTS_KEY = 'skill-values.held-agents';
7
+ export function heldAgentsKey(meshKey) {
8
+ return `${LEGACY_HELD_AGENTS_KEY}.${meshKey.toString('hex')}`;
9
+ }
7
10
  export class HostedAgents {
8
11
  _mesh;
9
12
  _local;
@@ -12,11 +15,13 @@ export class HostedAgents {
12
15
  _send;
13
16
  _onmoved;
14
17
  _log;
18
+ _heldKey;
15
19
  _lock = new ScopeLock({ debounce: true });
16
20
  _closed;
17
21
  _onDirty = () => this.kick();
18
22
  constructor(opts) {
19
23
  this._mesh = opts.mesh;
24
+ this._heldKey = heldAgentsKey(opts.mesh.key);
20
25
  this._local = opts.local;
21
26
  this._deviceId = opts.deviceId;
22
27
  this._catalog = opts.catalog;
@@ -74,7 +79,7 @@ export class HostedAgents {
74
79
  }
75
80
  }
76
81
  if (!sameIds(held, holding))
77
- await this._local.set(HELD_AGENTS_KEY, [...holding]);
82
+ await this._local.set(this._heldKey, [...holding]);
78
83
  }
79
84
  async _handOver(id, catalog) {
80
85
  const agent = await getAgent(this._mesh, id);
@@ -102,7 +107,8 @@ export class HostedAgents {
102
107
  return stored;
103
108
  }
104
109
  async _held() {
105
- const stored = await this._local.get(HELD_AGENTS_KEY);
110
+ const stored = (await this._local.get(this._heldKey)) ??
111
+ (await this._local.rekey(LEGACY_HELD_AGENTS_KEY, this._heldKey));
106
112
  const ids = new Set();
107
113
  if (Array.isArray(stored)) {
108
114
  for (const id of stored) {
@@ -8,7 +8,17 @@ export interface ExpectedDeviceProof {
8
8
  readonly memberId: Buffer;
9
9
  readonly deviceId: Buffer;
10
10
  }
11
+ export interface ExpectedMemberClaim {
12
+ readonly memberId: Buffer;
13
+ readonly deviceId: Buffer;
14
+ readonly attestation: Buffer;
15
+ }
11
16
  export declare function generateMnemonic(): Promise<string>;
12
17
  export declare function mintIdentity(mnemonic: string, devicePublicKey: Buffer): Promise<MintedIdentity>;
13
18
  export declare function attestDeviceProof(devicePublicKey: Buffer, parent: KeyPair, parentProof: Buffer): Promise<Buffer>;
14
19
  export declare function verifyDeviceProof(proof: Buffer, expected: ExpectedDeviceProof): Promise<boolean>;
20
+ export declare function claimAttestation(meshPublicKey: Buffer, deviceId: Buffer, writerKey: Buffer): Buffer;
21
+ export declare function deviceInviteToken(nonce: Buffer, deviceId: Buffer): Buffer;
22
+ export declare function attestMemberClaim(attestation: Buffer, deviceKeyPair: KeyPair, deviceProof: Buffer): Promise<Buffer>;
23
+ export declare function verifyMemberClaim(proof: Buffer, expected: ExpectedMemberClaim): Promise<boolean>;
24
+ export declare function bareDeviceProof(proof: Buffer): Buffer | null;
@@ -1,6 +1,9 @@
1
1
  import c from 'compact-encoding';
2
+ import crypto from 'hypercore-crypto';
2
3
  import { ProofEncoding } from 'keet-identity-key/lib/encoding.js';
3
4
  export const MAX_PROOF_BYTES = 1024;
5
+ const [CLAIM_NAMESPACE] = crypto.namespace('@qvac/core/member-claim', 1);
6
+ const [INVITE_NAMESPACE] = crypto.namespace('@qvac/core/device-invite', 1);
4
7
  let loaded = null;
5
8
  async function identityKey() {
6
9
  if (loaded === null)
@@ -43,3 +46,45 @@ export async function verifyDeviceProof(proof, expected) {
43
46
  return false;
44
47
  }
45
48
  }
49
+ export function claimAttestation(meshPublicKey, deviceId, writerKey) {
50
+ return crypto.hash([CLAIM_NAMESPACE, meshPublicKey, deviceId, writerKey]);
51
+ }
52
+ export function deviceInviteToken(nonce, deviceId) {
53
+ return crypto.hash([INVITE_NAMESPACE, nonce, deviceId]);
54
+ }
55
+ export async function attestMemberClaim(attestation, deviceKeyPair, deviceProof) {
56
+ return (await identityKey()).attestData(attestation, deviceKeyPair, deviceProof);
57
+ }
58
+ export async function verifyMemberClaim(proof, expected) {
59
+ if (proof.byteLength > MAX_PROOF_BYTES)
60
+ return false;
61
+ let decoded;
62
+ try {
63
+ decoded = c.decode(ProofEncoding, proof);
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ if (!decoded.data)
69
+ return false;
70
+ try {
71
+ const IdentityKey = await identityKey();
72
+ return !!IdentityKey.verify(proof, expected.attestation, {
73
+ expectedIdentity: expected.memberId,
74
+ expectedDevice: expected.deviceId
75
+ });
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ export function bareDeviceProof(proof) {
82
+ let decoded;
83
+ try {
84
+ decoded = c.decode(ProofEncoding, proof);
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ return c.encode(ProofEncoding, { ...decoded, data: null });
90
+ }
@@ -9,6 +9,9 @@ export interface MeshInvite {
9
9
  readonly fastForward: QvacAutobeeHead | null;
10
10
  readonly additionalNodes?: ReadonlyArray<MeshInviteNode>;
11
11
  readonly blindPeers?: ReadonlyArray<Buffer>;
12
+ readonly memberInvite?: boolean;
13
+ readonly memberId?: Buffer;
14
+ readonly inviteNonce?: Buffer;
12
15
  }
13
16
  export declare function encodeMeshInvite(invite: MeshInvite): string;
14
17
  export declare function decodeMeshInvite(raw: string): MeshInvite | null;
@@ -8,7 +8,10 @@ export function encodeMeshInvite(invite) {
8
8
  seed: invite.seed,
9
9
  fastForward: invite.fastForward,
10
10
  additionalNodes: [...(invite.additionalNodes ?? [])],
11
- blindPeers: [...(invite.blindPeers ?? [])]
11
+ blindPeers: [...(invite.blindPeers ?? [])],
12
+ memberInvite: invite.memberInvite ?? false,
13
+ memberId: invite.memberId ?? null,
14
+ inviteNonce: invite.inviteNonce ?? null
12
15
  };
13
16
  return INVITE_PREFIX + z32.encode(encodeStruct(INVITE_STRUCT, payload));
14
17
  }
@@ -31,6 +34,9 @@ export function decodeMeshInvite(raw) {
31
34
  host: node.host,
32
35
  port: node.port
33
36
  })),
34
- blindPeers: payload.blindPeers ?? []
37
+ blindPeers: payload.blindPeers ?? [],
38
+ memberInvite: payload.memberInvite ?? false,
39
+ memberId: payload.memberId ?? undefined,
40
+ inviteNonce: payload.inviteNonce ?? undefined
35
41
  };
36
42
  }
@@ -1,12 +1,11 @@
1
1
  import CorestoreStorage from 'hypercore-storage';
2
2
  import HyperDB from 'hyperdb';
3
- import type { LocalAppConfig, LocalCapabilityProfile, LocalChatNotify, LocalCustomModel, LocalIdentity, LocalMembership, LocalMeshDeparture, LocalModelDownload, LocalModelNotify } from '../../../spec/local/hyperschema/types.d.ts';
3
+ import type { LocalAppConfig, LocalCapabilityProfile, LocalChatNotify, LocalCustomModel, LocalIdentity, LocalMemberProof, LocalMeshDeparture, LocalMeshMembership, LocalModelDownload, LocalModelNotify } from '../../../spec/local/hyperschema/types.d.ts';
4
4
  import type { DeviceMetadata } from '../mesh.ts';
5
5
  export interface ResolvedSession {
6
6
  readonly seed: Buffer;
7
7
  readonly baseKey: Buffer | undefined;
8
8
  readonly writerSeed: string | undefined;
9
- readonly creator: boolean;
10
9
  }
11
10
  export declare function openLocalStore(storage: CorestoreStorage): LocalStore;
12
11
  declare class LocalStore {
@@ -20,6 +19,7 @@ declare class LocalStore {
20
19
  readonly key: string;
21
20
  readonly value: unknown;
22
21
  }>): Promise<void>;
22
+ rekey(fromKey: string, toKey: string): Promise<unknown>;
23
23
  deleteAll(keys: ReadonlyArray<string>): Promise<void>;
24
24
  getAppConfigRow(): Promise<LocalAppConfig | null>;
25
25
  updateAppConfigRow(mutate: (current: LocalAppConfig | null) => Omit<LocalAppConfig, 'id'>): Promise<LocalAppConfig>;
@@ -46,8 +46,8 @@ declare class LocalStore {
46
46
  renameDevice(publicKey: Buffer, name: string): Promise<void>;
47
47
  saveDeviceProfile(publicKey: Buffer, capabilityProfile: LocalCapabilityProfile, recommendedModelName: string, platform?: string): Promise<void>;
48
48
  readIdentity(): Promise<LocalIdentity | null>;
49
- readMembership(): Promise<LocalMembership | null>;
50
- recordMembership(link: Omit<LocalMembership, 'id'>): Promise<void>;
49
+ readMemberProof(meshKey: Buffer): Promise<LocalMemberProof | null>;
50
+ recordMemberProof(link: LocalMemberProof): Promise<void>;
51
51
  ensureIdentity(devicePublicKey: Buffer, createdAt: number): Promise<{
52
52
  identity: LocalIdentity;
53
53
  mnemonic: string | null;
@@ -57,13 +57,28 @@ declare class LocalStore {
57
57
  baseKey?: Buffer;
58
58
  new?: boolean;
59
59
  writerSeed?: string;
60
- creator?: boolean;
61
60
  }): Promise<ResolvedSession>;
62
61
  createCandidateSession(seed: Buffer, baseKey: Buffer): ResolvedSession;
63
- recordMesh(deviceId: Buffer, key: Buffer, seed: Buffer, creator: boolean, writerSeed: string | undefined): Promise<void>;
64
- recordDeparture(key: Buffer): Promise<void>;
62
+ private _activeMembership;
63
+ private _membership;
64
+ private _migrateLegacySession;
65
+ private _legacyMembership;
66
+ recordMesh(deviceId: Buffer, key: Buffer, session: ResolvedSession, { account }?: {
67
+ account?: boolean;
68
+ }): Promise<void>;
69
+ setActiveMesh(deviceId: Buffer, key: Buffer): Promise<void>;
70
+ recordDeparture(key: Buffer, opts: {
71
+ creator: boolean;
72
+ }): Promise<void>;
65
73
  departures(): Promise<LocalMeshDeparture[]>;
66
74
  deleteDeparture(key: Buffer): Promise<void>;
75
+ archiveMesh(key: Buffer): Promise<void>;
76
+ adoptHomeMesh(deviceId: Buffer, key: Buffer): Promise<void>;
77
+ private _pointersAt;
78
+ listMeshes(): Promise<LocalMeshMembership[]>;
79
+ listArchivedMeshes(): Promise<LocalMeshMembership[]>;
80
+ homeMesh(deviceId: Buffer): Promise<LocalMeshMembership | null>;
81
+ readMeshSession(key: Buffer): Promise<ResolvedSession | null>;
67
82
  watch(listener: () => void): void;
68
83
  unwatch(listener: () => void): void;
69
84
  close(): Promise<void>;
@@ -5,15 +5,18 @@ import ScopeLock from 'scope-lock';
5
5
  import { generateMnemonic, mintIdentity } from "../identity.js";
6
6
  import LocalDatabaseSpec from '../../../spec/local/hyperdb/index.js';
7
7
  const CONFIG = '@local/config';
8
- const MESH_SESSION = '@local/mesh-session';
8
+ const ACTIVE_MESH = '@local/active-mesh';
9
+ const MESH_MEMBERSHIP = '@local/mesh-membership';
9
10
  const MESH_HISTORY = '@local/mesh-history';
10
11
  const MESH_DEPARTURE = '@local/mesh-departure';
12
+ const MESH_SESSION = '@local/mesh-session';
11
13
  const DEVICE = '@local/device';
12
14
  const APP_CONFIG = '@local/app-config';
13
15
  const MODEL_DOWNLOAD = '@local/model-download';
14
16
  const CUSTOM_MODEL = '@local/custom-model';
15
17
  const IDENTITY = '@local/identity';
16
18
  const IDENTITY_ID = 'identity';
19
+ const MEMBER_PROOF = '@local/member-proof';
17
20
  const MEMBERSHIP = '@local/membership';
18
21
  const MEMBERSHIP_ID = 'membership';
19
22
  const CHAT_NOTIFY = '@local/chat-notify';
@@ -22,6 +25,13 @@ const APP_CONFIG_ID = 'default';
22
25
  function freshWriterSeed() {
23
26
  return `local-${crypto.randomBytes(8).toString('hex')}`;
24
27
  }
28
+ function sessionOf(row) {
29
+ return {
30
+ seed: row.seed,
31
+ baseKey: row.key ?? undefined,
32
+ writerSeed: row.writerSeed ?? undefined
33
+ };
34
+ }
25
35
  export function openLocalStore(storage) {
26
36
  const db = HyperDB.rocks(storage.rocks.columnFamily('assistant/local'), LocalDatabaseSpec);
27
37
  return new LocalStore(db);
@@ -60,6 +70,18 @@ class LocalStore {
60
70
  await tx.flush();
61
71
  });
62
72
  }
73
+ rekey(fromKey, toKey) {
74
+ return this._locked(async () => {
75
+ const row = await this._db.get(CONFIG, { key: fromKey });
76
+ if (!row)
77
+ return null;
78
+ const tx = this._db.transaction();
79
+ await tx.insert(CONFIG, { key: toKey, value: row.value });
80
+ await tx.delete(CONFIG, { key: fromKey });
81
+ await tx.flush();
82
+ return row.value;
83
+ });
84
+ }
63
85
  deleteAll(keys) {
64
86
  return this._locked(async () => {
65
87
  const tx = this._db.transaction();
@@ -248,16 +270,16 @@ class LocalStore {
248
270
  readIdentity() {
249
271
  return this._db.get(IDENTITY, { id: IDENTITY_ID });
250
272
  }
251
- readMembership() {
252
- return this._db.get(MEMBERSHIP, { id: MEMBERSHIP_ID });
273
+ readMemberProof(meshKey) {
274
+ return this._db.get(MEMBER_PROOF, { meshKey });
253
275
  }
254
- recordMembership(link) {
276
+ recordMemberProof(link) {
255
277
  return this._locked(async () => {
256
- const existing = await this._db.get(MEMBERSHIP, { id: MEMBERSHIP_ID });
278
+ const existing = await this._db.get(MEMBER_PROOF, { meshKey: link.meshKey });
257
279
  if (existing && existing.attestedAt >= link.attestedAt)
258
280
  return;
259
281
  const tx = this._db.transaction();
260
- await tx.insert(MEMBERSHIP, { id: MEMBERSHIP_ID, ...link });
282
+ await tx.insert(MEMBER_PROOF, link);
261
283
  await tx.flush();
262
284
  });
263
285
  }
@@ -280,88 +302,129 @@ class LocalStore {
280
302
  return { identity, mnemonic };
281
303
  });
282
304
  }
283
- resolveSession(deviceId, opts = {}) {
305
+ async resolveSession(deviceId, opts = {}) {
306
+ const current = await this._activeMembership(deviceId);
307
+ const sameSeed = Boolean(opts.seed && current?.seed.equals(opts.seed));
308
+ if (opts.seed && !sameSeed) {
309
+ return {
310
+ seed: opts.seed,
311
+ baseKey: opts.baseKey,
312
+ writerSeed: opts.writerSeed ?? freshWriterSeed()
313
+ };
314
+ }
315
+ if (current && !opts.new)
316
+ return sessionOf(current);
317
+ return {
318
+ seed: crypto.randomBytes(32),
319
+ baseKey: undefined,
320
+ writerSeed: undefined
321
+ };
322
+ }
323
+ createCandidateSession(seed, baseKey) {
324
+ return {
325
+ seed,
326
+ baseKey,
327
+ writerSeed: freshWriterSeed()
328
+ };
329
+ }
330
+ async _activeMembership(deviceId) {
331
+ const pointer = await this._db.get(ACTIVE_MESH, { deviceId });
332
+ if (!pointer)
333
+ return this._migrateLegacySession(deviceId);
334
+ return ((await this._membership(pointer.activeMeshKey)) ??
335
+ (await this._membership(pointer.homeMeshKey)));
336
+ }
337
+ async _membership(key) {
338
+ if (!key)
339
+ return null;
340
+ const row = await this._db.get(MESH_MEMBERSHIP, { key });
341
+ return row && !row.leftAt ? row : null;
342
+ }
343
+ _migrateLegacySession(deviceId) {
284
344
  return this._locked(async () => {
345
+ const legacy = await this._legacyMembership(deviceId);
346
+ if (!legacy)
347
+ return null;
348
+ const key = legacy.key;
349
+ if (!key)
350
+ return legacy;
285
351
  const tx = this._db.transaction();
286
- const session = await tx.get(MESH_SESSION, { deviceId });
287
- const sameSeed = Boolean(opts.seed && session?.meshSeed?.equals(opts.seed));
288
- if (opts.seed && !sameSeed) {
289
- await tx.insert(MESH_SESSION, {
290
- deviceId,
291
- meshSeed: opts.seed,
292
- meshKey: opts.baseKey ?? null,
293
- meshCreator: opts.creator ?? false
294
- });
295
- await tx.flush();
296
- return {
297
- seed: opts.seed,
298
- baseKey: opts.baseKey,
299
- writerSeed: opts.writerSeed ?? freshWriterSeed(),
300
- creator: opts.creator ?? false
301
- };
302
- }
303
- if (session?.meshSeed && !opts.new) {
304
- const baseKey = !session.meshCreator && session.meshKey ? session.meshKey : undefined;
305
- const history = await tx.findOne(MESH_HISTORY);
306
- await tx.close();
307
- return {
308
- seed: session.meshSeed,
309
- baseKey,
310
- writerSeed: history?.writerSeed ?? undefined,
311
- creator: session.meshCreator ?? false
312
- };
313
- }
314
- const seed = crypto.randomBytes(32);
315
- await tx.insert(MESH_SESSION, {
352
+ await tx.insert(MESH_MEMBERSHIP, { ...legacy, key });
353
+ await tx.insert(ACTIVE_MESH, {
316
354
  deviceId,
317
- meshSeed: seed,
318
- meshKey: null,
319
- meshCreator: true
355
+ activeMeshKey: key,
356
+ homeMeshKey: key
320
357
  });
358
+ const shipped = await tx.get(MEMBERSHIP, { id: MEMBERSHIP_ID });
359
+ if (shipped) {
360
+ const { memberId, proof, attestedAt } = shipped;
361
+ await tx.insert(MEMBER_PROOF, {
362
+ meshKey: key,
363
+ memberId,
364
+ proof,
365
+ attestedAt
366
+ });
367
+ }
321
368
  await tx.flush();
322
- return { seed, baseKey: undefined, writerSeed: undefined, creator: true };
369
+ return legacy;
323
370
  });
324
371
  }
325
- createCandidateSession(seed, baseKey) {
326
- return {
327
- seed,
328
- baseKey,
329
- writerSeed: freshWriterSeed(),
330
- creator: false
331
- };
372
+ async _legacyMembership(deviceId) {
373
+ const history = await this._db.findOne(MESH_HISTORY);
374
+ if (history) {
375
+ return { key: history.key, seed: history.seed, writerSeed: history.writerSeed };
376
+ }
377
+ const session = await this._db.get(MESH_SESSION, { deviceId });
378
+ if (!session?.meshSeed)
379
+ return null;
380
+ return { key: session.meshKey ?? null, seed: session.meshSeed, writerSeed: null };
332
381
  }
333
- recordMesh(deviceId, key, seed, creator, writerSeed) {
382
+ recordMesh(deviceId, key, session, { account = false } = {}) {
334
383
  return this._locked(async () => {
384
+ const existing = await this._db.get(MESH_MEMBERSHIP, { key });
385
+ const minted = account && !existing && session.baseKey === undefined;
386
+ const pointer = minted ? await this._db.get(ACTIVE_MESH, { deviceId }) : null;
335
387
  const tx = this._db.transaction();
336
- const current = await tx.findOne(MESH_HISTORY);
337
- if (current && !current.key.equals(key)) {
338
- await tx.delete(MESH_HISTORY, { key: current.key });
388
+ await tx.insert(MESH_MEMBERSHIP, {
389
+ key,
390
+ seed: session.seed,
391
+ writerSeed: session.writerSeed
392
+ });
393
+ if (minted) {
394
+ await tx.insert(ACTIVE_MESH, {
395
+ deviceId,
396
+ activeMeshKey: pointer?.activeMeshKey,
397
+ homeMeshKey: key
398
+ });
339
399
  }
340
- await tx.insert(MESH_HISTORY, { key, seed, creator, writerSeed });
341
- const session = await tx.get(MESH_SESSION, { deviceId });
342
- await tx.insert(MESH_SESSION, {
343
- ...session,
400
+ await tx.flush();
401
+ });
402
+ }
403
+ setActiveMesh(deviceId, key) {
404
+ return this._locked(async () => {
405
+ const pointer = await this._db.get(ACTIVE_MESH, { deviceId });
406
+ const tx = this._db.transaction();
407
+ await tx.insert(ACTIVE_MESH, {
344
408
  deviceId,
345
- meshSeed: seed,
346
- meshKey: key,
347
- meshCreator: creator
409
+ activeMeshKey: key,
410
+ homeMeshKey: pointer?.homeMeshKey
348
411
  });
349
412
  await tx.flush();
350
413
  });
351
414
  }
352
- recordDeparture(key) {
415
+ recordDeparture(key, opts) {
353
416
  return this._locked(async () => {
354
417
  const tx = this._db.transaction();
355
- const history = await tx.get(MESH_HISTORY, { key });
356
- if (!history) {
418
+ const row = await tx.get(MESH_MEMBERSHIP, { key });
419
+ if (!row) {
357
420
  await tx.close();
358
421
  return;
359
422
  }
360
423
  await tx.insert(MESH_DEPARTURE, {
361
- key: history.key,
362
- seed: history.seed,
363
- creator: history.creator,
364
- writerSeed: history.writerSeed
424
+ key: row.key,
425
+ seed: row.seed,
426
+ creator: opts.creator,
427
+ writerSeed: row.writerSeed
365
428
  });
366
429
  await tx.flush();
367
430
  });
@@ -379,6 +442,79 @@ class LocalStore {
379
442
  await tx.flush();
380
443
  });
381
444
  }
445
+ archiveMesh(key) {
446
+ return this._locked(async () => {
447
+ const existing = await this._db.get(MESH_MEMBERSHIP, { key });
448
+ const aimed = await this._pointersAt(key);
449
+ const tx = this._db.transaction();
450
+ if (existing) {
451
+ await tx.insert(MESH_MEMBERSHIP, { ...existing, leftAt: Date.now() });
452
+ }
453
+ for (const pointer of aimed)
454
+ await tx.insert(ACTIVE_MESH, pointer);
455
+ await tx.flush();
456
+ });
457
+ }
458
+ adoptHomeMesh(deviceId, key) {
459
+ return this._locked(async () => {
460
+ const departed = [];
461
+ for await (const row of this._db.find(MESH_MEMBERSHIP)) {
462
+ if (!row.key.equals(key) && !row.leftAt)
463
+ departed.push(row);
464
+ }
465
+ const pointer = await this._db.get(ACTIVE_MESH, { deviceId });
466
+ const leftAt = Date.now();
467
+ const tx = this._db.transaction();
468
+ for (const row of departed) {
469
+ await tx.insert(MESH_MEMBERSHIP, { ...row, leftAt });
470
+ }
471
+ await tx.insert(ACTIVE_MESH, {
472
+ deviceId,
473
+ activeMeshKey: pointer?.activeMeshKey,
474
+ homeMeshKey: key
475
+ });
476
+ await tx.flush();
477
+ });
478
+ }
479
+ async _pointersAt(key) {
480
+ const cleared = [];
481
+ for await (const pointer of this._db.find(ACTIVE_MESH)) {
482
+ const active = pointer.activeMeshKey?.equals(key);
483
+ const home = pointer.homeMeshKey?.equals(key);
484
+ if (!active && !home)
485
+ continue;
486
+ cleared.push({
487
+ deviceId: pointer.deviceId,
488
+ activeMeshKey: active ? null : pointer.activeMeshKey,
489
+ homeMeshKey: home ? null : pointer.homeMeshKey
490
+ });
491
+ }
492
+ return cleared;
493
+ }
494
+ async listMeshes() {
495
+ const rows = [];
496
+ for await (const row of this._db.find(MESH_MEMBERSHIP)) {
497
+ if (!row.leftAt)
498
+ rows.push(row);
499
+ }
500
+ return rows;
501
+ }
502
+ async listArchivedMeshes() {
503
+ const rows = [];
504
+ for await (const row of this._db.find(MESH_MEMBERSHIP)) {
505
+ if (row.leftAt)
506
+ rows.push(row);
507
+ }
508
+ return rows;
509
+ }
510
+ async homeMesh(deviceId) {
511
+ const pointer = await this._db.get(ACTIVE_MESH, { deviceId });
512
+ return this._membership(pointer?.homeMeshKey);
513
+ }
514
+ async readMeshSession(key) {
515
+ const row = await this._membership(key);
516
+ return row ? sessionOf(row) : null;
517
+ }
382
518
  watch(listener) {
383
519
  this._db.watch(listener);
384
520
  }
@@ -1,15 +1,21 @@
1
1
  import type { KeyPair } from 'hyperswarm';
2
2
  import type { Logger } from '../../index.ts';
3
3
  import type { QvacDevice } from '../../spec/mesh/hyperschema/types.d.ts';
4
+ import type { DeviceInvites } from './device-invites.ts';
4
5
  import type { Mesh } from './mesh.ts';
5
6
  export interface MembershipView {
6
7
  readonly members: number;
7
8
  readonly own: QvacDevice | null;
8
- readonly unattested: ReadonlyArray<Buffer>;
9
+ readonly unattested: ReadonlyArray<QvacDevice>;
9
10
  }
10
11
  export interface MembershipContext {
11
12
  readonly deviceKeyPair: KeyPair;
12
13
  readonly log: Logger | null;
13
14
  }
14
15
  export declare function membershipView(mesh: Mesh, deviceId: Buffer): Promise<MembershipView>;
15
- export declare function attestUnattestedDevices(mesh: Mesh, { deviceKeyPair, log }: MembershipContext): Promise<void>;
16
+ export declare function attestUnattestedDevices(mesh: Mesh, { deviceKeyPair, log }: MembershipContext, invites: DeviceInvites): Promise<void>;
17
+ export interface KnownMember {
18
+ readonly id: Buffer;
19
+ readonly proof: Buffer;
20
+ }
21
+ export declare function claimOwnMembership(mesh: Mesh, { deviceKeyPair, log }: MembershipContext, known: KnownMember): Promise<void>;