@qvac/core 0.6.6 → 0.7.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.
Files changed (123) hide show
  1. package/CHANGELOG.md +185 -1
  2. package/README.md +2 -0
  3. package/dist-lib/lib/api/app-config.d.ts +3 -1
  4. package/dist-lib/lib/api/app-config.js +15 -4
  5. package/dist-lib/lib/assistant/fake-models.d.ts +22 -0
  6. package/dist-lib/lib/assistant/fake-models.js +112 -0
  7. package/dist-lib/lib/assistant/harness.d.ts +10 -0
  8. package/dist-lib/lib/assistant/harness.js +26 -0
  9. package/dist-lib/lib/assistant/history.d.ts +5 -1
  10. package/dist-lib/lib/assistant/history.js +14 -2
  11. package/dist-lib/lib/assistant-tree.d.ts +4 -0
  12. package/dist-lib/lib/assistant-tree.js +45 -7
  13. package/dist-lib/lib/assistant.d.ts +16 -2
  14. package/dist-lib/lib/assistant.js +184 -44
  15. package/dist-lib/lib/constants.d.ts +6 -0
  16. package/dist-lib/lib/constants.js +6 -0
  17. package/dist-lib/lib/core/chat-activity.d.ts +1 -1
  18. package/dist-lib/lib/core/chat-activity.js +3 -0
  19. package/dist-lib/lib/core/collections.d.ts +1 -0
  20. package/dist-lib/lib/core/collections.js +1 -0
  21. package/dist-lib/lib/core/contract/compute.d.ts +1 -1
  22. package/dist-lib/lib/core/contract/compute.js +2 -1
  23. package/dist-lib/lib/core/contract/index.js +6 -1
  24. package/dist-lib/lib/core/contract/invites.d.ts +1 -11
  25. package/dist-lib/lib/core/contract/invites.js +3 -3
  26. package/dist-lib/lib/core/contract/mesh-seeds.d.ts +2 -0
  27. package/dist-lib/lib/core/contract/mesh-seeds.js +26 -0
  28. package/dist-lib/lib/core/contract/open-join.d.ts +2 -0
  29. package/dist-lib/lib/core/contract/open-join.js +57 -0
  30. package/dist-lib/lib/core/departures.d.ts +3 -0
  31. package/dist-lib/lib/core/departures.js +44 -1
  32. package/dist-lib/lib/core/fs-drives.js +9 -6
  33. package/dist-lib/lib/core/handoff-channel.d.ts +1 -0
  34. package/dist-lib/lib/core/handoff-channel.js +7 -2
  35. package/dist-lib/lib/core/harness-loan.d.ts +1 -0
  36. package/dist-lib/lib/core/harness-loan.js +7 -2
  37. package/dist-lib/lib/core/identity.d.ts +1 -1
  38. package/dist-lib/lib/core/identity.js +6 -4
  39. package/dist-lib/lib/core/invite.d.ts +2 -0
  40. package/dist-lib/lib/core/invite.js +6 -2
  41. package/dist-lib/lib/core/membership.d.ts +1 -12
  42. package/dist-lib/lib/core/membership.js +1 -94
  43. package/dist-lib/lib/core/mesh.d.ts +8 -13
  44. package/dist-lib/lib/core/mesh.js +41 -87
  45. package/dist-lib/lib/core/protocol-pairing.d.ts +11 -0
  46. package/dist-lib/lib/core/protocol-pairing.js +22 -0
  47. package/dist-lib/lib/core/sync/index.js +2 -16
  48. package/dist-lib/lib/core.d.ts +43 -49
  49. package/dist-lib/lib/core.js +451 -909
  50. package/dist-lib/lib/diagnostics.d.ts +7 -0
  51. package/dist-lib/lib/diagnostics.js +22 -0
  52. package/dist-lib/lib/doctor/checks.d.ts +15 -0
  53. package/dist-lib/lib/doctor/checks.js +269 -0
  54. package/dist-lib/lib/doctor/redact.d.ts +4 -0
  55. package/dist-lib/lib/doctor/redact.js +31 -0
  56. package/dist-lib/lib/doctor/render.d.ts +8 -0
  57. package/dist-lib/lib/doctor/render.js +83 -0
  58. package/dist-lib/lib/doctor/tree.d.ts +5 -0
  59. package/dist-lib/lib/doctor/tree.js +167 -0
  60. package/dist-lib/lib/downloads-allowed-pusher.d.ts +10 -0
  61. package/dist-lib/lib/downloads-allowed-pusher.js +37 -0
  62. package/dist-lib/lib/guards.d.ts +1 -0
  63. package/dist-lib/lib/guards.js +4 -0
  64. package/dist-lib/lib/inference-calls.js +1 -5
  65. package/dist-lib/lib/kv-cache-reclaim.d.ts +2 -1
  66. package/dist-lib/lib/kv-cache-reclaim.js +24 -0
  67. package/dist-lib/lib/mesh-scoped-engine.js +1 -0
  68. package/dist-lib/lib/model-download-status.d.ts +1 -1
  69. package/dist-lib/lib/model-download.d.ts +9 -1
  70. package/dist-lib/lib/model-download.js +48 -3
  71. package/dist-lib/lib/model-memory-cap.d.ts +29 -0
  72. package/dist-lib/lib/model-memory-cap.js +69 -0
  73. package/dist-lib/lib/models-watch.d.ts +1 -1
  74. package/dist-lib/lib/models-watch.js +4 -4
  75. package/dist-lib/lib/oauth/flow.js +1 -1
  76. package/dist-lib/lib/oauth/loopback.js +16 -2
  77. package/dist-lib/lib/oauth/redirect-types.d.ts +1 -0
  78. package/dist-lib/lib/run-replay.d.ts +26 -0
  79. package/dist-lib/lib/run-replay.js +107 -0
  80. package/dist-lib/schema/config.d.ts +1 -1
  81. package/dist-lib/schema/config.js +1 -1
  82. package/dist-lib/schema/content.js +9 -1
  83. package/dist-lib/schema/engine.js +30 -5
  84. package/dist-lib/schema/local.js +3 -2
  85. package/dist-lib/schema/qvac.js +18 -1
  86. package/dist-lib/spec/bind.js +3 -0
  87. package/dist-lib/spec/calls.js +1 -0
  88. package/dist-lib/spec/capabilities.d.ts +2 -0
  89. package/dist-lib/spec/config/hyperconf/index.js +1 -1
  90. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  91. package/dist-lib/spec/hrpc/index.js +15 -3
  92. package/dist-lib/spec/hrpc/messages.js +646 -557
  93. package/dist-lib/spec/hyperschema/index.js +646 -557
  94. package/dist-lib/spec/hyperschema/schema.json +80 -0
  95. package/dist-lib/spec/hyperschema/types.d.ts +20 -3
  96. package/dist-lib/spec/local/hyperdb/messages.js +22 -10
  97. package/dist-lib/spec/local/hyperschema/index.js +16 -7
  98. package/dist-lib/spec/local/hyperschema/schema.json +10 -1
  99. package/dist-lib/spec/local/hyperschema/types.d.ts +3 -2
  100. package/dist-lib/spec/mesh/hyperdb/db.json +16 -1
  101. package/dist-lib/spec/mesh/hyperdb/index.js +71 -2
  102. package/dist-lib/spec/mesh/hyperdb/messages.js +477 -240
  103. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +13 -1
  104. package/dist-lib/spec/mesh/hyperdispatch/index.js +35 -1
  105. package/dist-lib/spec/mesh/hyperdispatch/messages.js +180 -7
  106. package/dist-lib/spec/mesh/hyperschema/index.js +180 -7
  107. package/dist-lib/spec/mesh/hyperschema/schema.json +98 -1
  108. package/dist-lib/spec/mesh/hyperschema/types.d.ts +26 -2
  109. package/package.json +9 -17
  110. package/tui/README.md +7 -1
  111. package/tui/app.mjs +245 -11
  112. package/tui/boot.mjs +1 -0
  113. package/tui/index.mjs +1 -0
  114. package/tui/lib/render.mjs +25 -1
  115. package/worker/assistant-sidecar.mjs +5 -2
  116. package/dist-lib/lib/core/device-invites.d.ts +0 -11
  117. package/dist-lib/lib/core/device-invites.js +0 -63
  118. package/dist-lib/lib/core/grant-expiry.d.ts +0 -11
  119. package/dist-lib/lib/core/grant-expiry.js +0 -66
  120. package/dist-lib/lib/core/mesh-seed-handoff.d.ts +0 -27
  121. package/dist-lib/lib/core/mesh-seed-handoff.js +0 -53
  122. package/dist-lib/lib/oauth/loopback.stub.d.ts +0 -3
  123. package/dist-lib/lib/oauth/loopback.stub.js +0 -6
@@ -24,7 +24,7 @@ async function kickedFromOutside(tx, device, memberId) {
24
24
  const kickerMember = kicker.memberId ?? kicker.claimedMemberId;
25
25
  return !kickerMember || !b4a.equals(kickerMember, memberId);
26
26
  }
27
- export async function memberStanding(tx, memberId, grant) {
27
+ async function memberStanding(tx, memberId, grant) {
28
28
  if (await removedSinceMint(tx, memberId, grant))
29
29
  return 'removed';
30
30
  for await (const device of tx.find(DEVICES)) {
@@ -37,7 +37,7 @@ export async function memberStanding(tx, memberId, grant) {
37
37
  }
38
38
  return null;
39
39
  }
40
- export async function inviteStanding(tx, { device, memberId, grant, compute = false }) {
40
+ async function inviteStanding(tx, { device, memberId, grant, compute = false }) {
41
41
  const standing = await memberStanding(tx, memberId, grant);
42
42
  if (standing !== 'present') {
43
43
  return standing;
@@ -50,7 +50,7 @@ export async function inviteStanding(tx, { device, memberId, grant, compute = fa
50
50
  }
51
51
  return (await removedBy(tx, device)) === 'own-member' ? 'present' : null;
52
52
  }
53
- export async function belongsToAnotherMember(tx, device, memberId) {
53
+ async function belongsToAnotherMember(tx, device, memberId) {
54
54
  if (!device?.memberId || b4a.equals(device.memberId, memberId))
55
55
  return false;
56
56
  return !device.revoked || (await removedBy(tx, device)) === 'another-member';
@@ -0,0 +1,2 @@
1
+ import type { Router } from '../../../spec/mesh/hyperdispatch/index.js';
2
+ export declare function registerMeshSeedRoutes(router: Router): void;
@@ -0,0 +1,26 @@
1
+ import { liveDeviceForWriter, trackActivity } from './activity.js';
2
+ import b4a from 'b4a';
3
+ import { MESH_SEEDS } from '../collections.js';
4
+ import { meshKind } from './mesh-kind.js';
5
+ export function registerMeshSeedRoutes(router) {
6
+ router.add('@qvac/put-mesh-seed', trackActivity(async ({ meshKey, seed }, { tx, node, log }) => {
7
+ const ids = { meshKey: b4a.toHex(meshKey).slice(0, 8) };
8
+ if ((await meshKind(tx)) === 'shared') {
9
+ log?.warn('contract', 'put-mesh-seed dropped: seeds live in the account alone', ids);
10
+ return;
11
+ }
12
+ const author = await liveDeviceForWriter(tx, node.key);
13
+ if (!author?.memberId) {
14
+ log?.warn('contract', 'put-mesh-seed dropped: the author speaks for no member here', ids);
15
+ return;
16
+ }
17
+ const held = await tx.get(MESH_SEEDS, { meshKey });
18
+ if (held && b4a.equals(held.seed, seed)) {
19
+ log?.debug('contract', 'put-mesh-seed dropped: the account already holds it', ids);
20
+ return;
21
+ }
22
+ const row = { meshKey, seed };
23
+ await tx.insert(MESH_SEEDS, row);
24
+ return row;
25
+ }));
26
+ }
@@ -0,0 +1,2 @@
1
+ import type { Router } from '../../../spec/mesh/hyperdispatch/index.js';
2
+ export declare function registerOpenJoinRoutes(router: Router): void;
@@ -0,0 +1,57 @@
1
+ import crypto from 'hypercore-crypto';
2
+ import { trackActivity } from './activity.js';
3
+ import { linkMember, provenMember } from './members.js';
4
+ import { admitDevice } from './writers.js';
5
+ import b4a from 'b4a';
6
+ import { DEVICES } from '../collections.js';
7
+ export function registerOpenJoinRoutes(router) {
8
+ router.add('@qvac/open-join', trackActivity(async (payload, context) => {
9
+ const { node, host, meshPublicKey, log } = context;
10
+ let valid = false;
11
+ try {
12
+ valid = crypto.verify(node.key, payload.signature, meshPublicKey);
13
+ }
14
+ catch {
15
+ valid = false;
16
+ }
17
+ if (!valid) {
18
+ log?.warn('contract', 'open-join dropped: invalid writer-claim signature');
19
+ return;
20
+ }
21
+ const id = payload.deviceId;
22
+ if (!id) {
23
+ return;
24
+ }
25
+ const admission = await admitDevice(context, payload.device, {
26
+ id,
27
+ writerKey: node.key,
28
+ claim: { deviceSignature: payload.deviceSignature }
29
+ });
30
+ if (admission !== 'admitted') {
31
+ return;
32
+ }
33
+ await host.addWriter(node.key);
34
+ await linkClaimedMember(payload, context, id);
35
+ return payload.device;
36
+ }));
37
+ }
38
+ async function linkClaimedMember({ member, memberClaim }, { tx, node, meshPublicKey, log }, deviceId) {
39
+ if (!member || !memberClaim)
40
+ return;
41
+ const proof = await provenMember(meshPublicKey, {
42
+ deviceId,
43
+ writerKey: node.key,
44
+ memberId: member.id,
45
+ claim: memberClaim
46
+ });
47
+ if (!proof) {
48
+ log?.warn('contract', 'open-join: the member claim does not bind this writer', {
49
+ device: b4a.toHex(deviceId).slice(0, 16)
50
+ });
51
+ return;
52
+ }
53
+ const admitted = await tx.get(DEVICES, { id: deviceId });
54
+ if (admitted) {
55
+ await linkMember(tx, admitted, { member, proof });
56
+ }
57
+ }
@@ -11,6 +11,7 @@ interface DepartureRows {
11
11
  export interface PendingDeparturesOptions {
12
12
  swarm: Hyperswarm;
13
13
  isPooled: (key: Buffer) => boolean;
14
+ deviceId: () => Buffer | null;
14
15
  logger?: Logger | null;
15
16
  blindPeerKeys?: ReadonlyArray<Buffer>;
16
17
  blindPeeringOpts?: BlindPeeringOpts;
@@ -25,6 +26,7 @@ export declare class PendingDepartures {
25
26
  private readonly _blindPeeringOpts;
26
27
  private readonly _wakeup;
27
28
  private readonly _isPooled;
29
+ private readonly _deviceId;
28
30
  private readonly _active;
29
31
  private readonly _parked;
30
32
  private readonly _lock;
@@ -33,6 +35,7 @@ export declare class PendingDepartures {
33
35
  flush(): void;
34
36
  private _flush;
35
37
  private _deliver;
38
+ private _announce;
36
39
  park(key: Buffer): Promise<void>;
37
40
  unpark(key: Buffer): void;
38
41
  drop(key: Buffer): Promise<void>;
@@ -11,6 +11,7 @@ export class PendingDepartures {
11
11
  _blindPeeringOpts;
12
12
  _wakeup;
13
13
  _isPooled;
14
+ _deviceId;
14
15
  _active = new Map();
15
16
  _parked = new Set();
16
17
  _lock = new ScopeLock();
@@ -20,6 +21,7 @@ export class PendingDepartures {
20
21
  this._local = local;
21
22
  this._swarm = opts.swarm;
22
23
  this._isPooled = opts.isPooled;
24
+ this._deviceId = opts.deviceId;
23
25
  this._log = opts.logger ?? null;
24
26
  this._blindPeerKeys = opts.blindPeerKeys ?? [];
25
27
  this._blindPeeringOpts = opts.blindPeeringOpts;
@@ -45,6 +47,7 @@ export class PendingDepartures {
45
47
  seed: row.seed,
46
48
  key: row.creator ? null : row.key,
47
49
  writerSeed: row.writerSeed ?? undefined,
50
+ deviceId: this._deviceId() ?? undefined,
48
51
  logger: this._log,
49
52
  blindPeerKeys: this._blindPeerKeys,
50
53
  blindPeeringOpts: this._blindPeeringOpts,
@@ -70,7 +73,8 @@ export class PendingDepartures {
70
73
  this._swarm.join(mesh.discoveryKey, { server: true, client: true });
71
74
  mesh.startBlindPeering(this._swarm.dht);
72
75
  this._log?.info(scope, 'reopened a departed mesh to deliver its removal');
73
- if (!(await waitForDelivery(mesh))) {
76
+ const announced = await this._announce(mesh);
77
+ if (announced === 'closed' || (announced === 'sent' && !(await waitForDelivery(mesh)))) {
74
78
  return;
75
79
  }
76
80
  await this._local.deleteDeparture(row.key);
@@ -81,6 +85,23 @@ export class PendingDepartures {
81
85
  await mesh.close().catch(noop);
82
86
  }
83
87
  }
88
+ async _announce(mesh) {
89
+ if (mesh.localLength === 0)
90
+ return 'moot';
91
+ const deviceId = this._deviceId();
92
+ if (!deviceId || (await mesh.checkResumedRevocation())) {
93
+ return 'sent';
94
+ }
95
+ if (!(await admitted(mesh))) {
96
+ return mesh.closing ? 'closed' : 'moot';
97
+ }
98
+ await mesh.dispatch('remove-writer', {
99
+ writerKey: mesh.localWriterKey,
100
+ deviceId,
101
+ revokedAt: Date.now()
102
+ });
103
+ return 'sent';
104
+ }
84
105
  async park(key) {
85
106
  const hex = b4a.toHex(key);
86
107
  await this._lock.lock();
@@ -121,6 +142,28 @@ export class PendingDepartures {
121
142
  }));
122
143
  }
123
144
  }
145
+ async function admitted(mesh) {
146
+ if (mesh.writable)
147
+ return true;
148
+ if (await mesh.ownWriterRefused())
149
+ return false;
150
+ return new Promise((resolve) => {
151
+ const settle = (ok) => {
152
+ mesh.autobee.off('writable', onWritable);
153
+ mesh.syncActivity.unwatch(check);
154
+ mesh.off('close', onClose);
155
+ resolve(ok);
156
+ };
157
+ const onWritable = () => settle(true);
158
+ const onClose = () => settle(false);
159
+ const check = () => {
160
+ void mesh.ownWriterRefused().then((refused) => refused && settle(false), noop);
161
+ };
162
+ mesh.autobee.on('writable', onWritable);
163
+ mesh.syncActivity.watch(check);
164
+ mesh.on('close', onClose);
165
+ });
166
+ }
124
167
  function waitForDelivery(mesh) {
125
168
  const local = mesh.autobee.local;
126
169
  let uploaded = 0;
@@ -21,7 +21,7 @@ async function openDrive(store, swarm, key) {
21
21
  const topic = swarm.join(drive.discoveryKey, { server: false, client: true });
22
22
  const donePeering = drive.findingPeers();
23
23
  topic.flushed().then(donePeering, donePeering);
24
- return drive;
24
+ return { drive, writable: drive.writable, topic };
25
25
  }
26
26
  export function createFsDriveHost(store, opts) {
27
27
  const namespaced = store.namespace(NAMESPACE);
@@ -36,13 +36,13 @@ export function createFsDriveHost(store, opts) {
36
36
  return cached;
37
37
  }
38
38
  const opening = withDeadline((async () => {
39
- const drive = await openDrive(namespaced, opts.swarm, key);
40
- const blobs = await drive.getBlobs();
41
- peering.addCoreBackground(drive.core, { keys: opts.blindPeerKeys });
39
+ const held = await openDrive(namespaced, opts.swarm, key);
40
+ const blobs = await held.drive.getBlobs();
41
+ peering.addCoreBackground(held.drive.core, { keys: opts.blindPeerKeys });
42
42
  if (blobs) {
43
43
  peering.addCoreBackground(blobs.core, { keys: opts.blindPeerKeys });
44
44
  }
45
- return { drive, writable: drive.writable };
45
+ return held;
46
46
  })(), DRIVE_OPEN_TIMEOUT_MS);
47
47
  drives.set(key, opening);
48
48
  opening.catch(() => drives.delete(key));
@@ -53,7 +53,10 @@ export function createFsDriveHost(store, opts) {
53
53
  drives.clear();
54
54
  await Promise.all(settled
55
55
  .filter((result) => result.status === 'fulfilled')
56
- .map((result) => result.value.drive.close()));
56
+ .map(async ({ value: { drive, topic } }) => {
57
+ await topic.destroy();
58
+ await drive.close();
59
+ }));
57
60
  await peering.close();
58
61
  }
59
62
  return { acquire, close };
@@ -35,6 +35,7 @@ export declare class HandoffChannel<Req, Res, Ack extends {
35
35
  private readonly _peers;
36
36
  private readonly _waiters;
37
37
  private _nextId;
38
+ private readonly _pairing;
38
39
  constructor(opts: HandoffChannelOptions<Req, Res, Ack>);
39
40
  addStream(stream: HandoffStream): void;
40
41
  send(hostDeviceId: Uint8Array, request: Req, kind?: number): Promise<Res>;
@@ -1,6 +1,6 @@
1
1
  import b4a from 'b4a';
2
- import Protomux, {} from 'protomux';
3
2
  import { errorMessage } from '../guards.js';
3
+ import { createProtocolPairing } from './protocol-pairing.js';
4
4
  export const HOST_UNREACHABLE = 'the device hosting this agent is not connected';
5
5
  export const HOST_SILENT = 'the device hosting this agent did not answer';
6
6
  export const ACK_TIMEOUT_MS = 60_000;
@@ -10,19 +10,23 @@ export class HandoffChannel {
10
10
  _peers;
11
11
  _waiters;
12
12
  _nextId;
13
+ _pairing;
13
14
  constructor(opts) {
14
15
  this._opts = opts;
15
16
  this._ackTimeoutMs = opts.ackTimeoutMs ?? ACK_TIMEOUT_MS;
16
17
  this._peers = new Map();
17
18
  this._waiters = new Map();
18
19
  this._nextId = 0;
20
+ this._pairing = createProtocolPairing(opts.protocol);
19
21
  }
20
22
  addStream(stream) {
21
23
  const deviceId = b4a.toHex(stream.remotePublicKey);
22
24
  if (this._peers.has(deviceId)) {
23
25
  return;
24
26
  }
25
- const channel = Protomux.from(stream.noiseStream).createChannel({
27
+ const channel = this._pairing
28
+ .mux(stream, () => this.addStream(stream))
29
+ .createChannel({
26
30
  protocol: this._opts.protocol,
27
31
  onclose: () => {
28
32
  if (channel) {
@@ -69,6 +73,7 @@ export class HandoffChannel {
69
73
  return promise;
70
74
  }
71
75
  destroy() {
76
+ this._pairing.destroy();
72
77
  for (const peer of this._peers.values()) {
73
78
  peer.channel.close();
74
79
  }
@@ -16,6 +16,7 @@ export declare class HarnessLoan {
16
16
  private readonly _opts;
17
17
  private readonly _peers;
18
18
  private _nextId;
19
+ private readonly _pairing;
19
20
  constructor(opts: HarnessLoanOptions);
20
21
  addStream(stream: LoanStream): void;
21
22
  borrow(deviceId: string): Duplex;
@@ -1,7 +1,7 @@
1
1
  import b4a from 'b4a';
2
2
  import { raw, uint } from 'compact-encoding';
3
- import Protomux, {} from 'protomux';
4
3
  import { Duplex } from 'streamx';
4
+ import { createProtocolPairing } from './protocol-pairing.js';
5
5
  const PROTOCOL = 'qvac/harness-loan';
6
6
  function noop() { }
7
7
  export const LOAN_UNREACHABLE = 'the device lending its model is not connected';
@@ -57,17 +57,21 @@ export class HarnessLoan {
57
57
  _opts;
58
58
  _peers;
59
59
  _nextId;
60
+ _pairing;
60
61
  constructor(opts) {
61
62
  this._opts = opts;
62
63
  this._peers = new Map();
63
64
  this._nextId = 1;
65
+ this._pairing = createProtocolPairing(PROTOCOL);
64
66
  }
65
67
  addStream(stream) {
66
68
  const deviceId = b4a.toHex(stream.remotePublicKey);
67
69
  if (this._peers.has(deviceId)) {
68
70
  return;
69
71
  }
70
- const channel = Protomux.from(stream.noiseStream).createChannel({
72
+ const channel = this._pairing
73
+ .mux(stream, () => this.addStream(stream))
74
+ .createChannel({
71
75
  protocol: PROTOCOL,
72
76
  onclose: () => this._drop(deviceId)
73
77
  });
@@ -122,6 +126,7 @@ export class HarnessLoan {
122
126
  }
123
127
  }
124
128
  destroy() {
129
+ this._pairing.destroy();
125
130
  for (const [deviceId, peer] of [...this._peers]) {
126
131
  try {
127
132
  peer.channel.close();
@@ -18,9 +18,9 @@ export declare function generateMnemonic(): Promise<string>;
18
18
  export declare function openIdentity(mnemonic: string): Promise<IdentityKey>;
19
19
  export declare function mintIdentity(mnemonic: string, devicePublicKey: Buffer): Promise<MintedIdentity>;
20
20
  export declare function attestDeviceProof(devicePublicKey: Buffer, parent: KeyPair, parentProof: Buffer): Promise<Buffer>;
21
+ export declare function delegationFits(proof: Buffer, delegate: KeyPair): Promise<boolean>;
21
22
  export declare function verifyDeviceProof(proof: Buffer, expected: ExpectedDeviceProof): Promise<boolean>;
22
23
  export declare function claimAttestation(meshPublicKey: Buffer, deviceId: Buffer, writerKey: Buffer): Buffer;
23
- export declare function deviceInviteToken(nonce: Buffer, deviceId: Buffer): Buffer;
24
24
  export declare function attestMemberClaim(attestation: Buffer, deviceKeyPair: KeyPair, deviceProof: Buffer): Promise<Buffer>;
25
25
  export declare function verifyMemberClaim(proof: Buffer, expected: ExpectedMemberClaim): Promise<boolean>;
26
26
  export declare function verifyRecoveryClaim(proof: Buffer, expected: ExpectedMemberClaim): Promise<boolean>;
@@ -3,7 +3,6 @@ import crypto from 'hypercore-crypto';
3
3
  import { ProofEncoding } from 'keet-identity-key/lib/encoding.js';
4
4
  export const MAX_PROOF_BYTES = 1024;
5
5
  const [CLAIM_NAMESPACE] = crypto.namespace('@qvac/core/member-claim', 1);
6
- const [INVITE_NAMESPACE] = crypto.namespace('@qvac/core/device-invite', 1);
7
6
  let loaded = null;
8
7
  async function identityKey() {
9
8
  if (loaded === null) {
@@ -26,6 +25,12 @@ export async function attestDeviceProof(devicePublicKey, parent, parentProof) {
26
25
  throw new Error('attestDeviceProof needs the parent proof');
27
26
  return (await identityKey()).attestDevice(devicePublicKey, parent, parentProof);
28
27
  }
28
+ export async function delegationFits(proof, delegate) {
29
+ const device = crypto.keyPair();
30
+ const extended = await attestDeviceProof(device.publicKey, delegate, proof);
31
+ const claim = await attestMemberClaim(crypto.randomBytes(32), device, extended);
32
+ return claim.byteLength <= MAX_PROOF_BYTES;
33
+ }
29
34
  export async function verifyDeviceProof(proof, expected) {
30
35
  if (proof.byteLength > MAX_PROOF_BYTES)
31
36
  return false;
@@ -53,9 +58,6 @@ export async function verifyDeviceProof(proof, expected) {
53
58
  export function claimAttestation(meshPublicKey, deviceId, writerKey) {
54
59
  return crypto.hash([CLAIM_NAMESPACE, meshPublicKey, deviceId, writerKey]);
55
60
  }
56
- export function deviceInviteToken(nonce, deviceId) {
57
- return crypto.hash([INVITE_NAMESPACE, nonce, deviceId]);
58
- }
59
61
  export async function attestMemberClaim(attestation, deviceKeyPair, deviceProof) {
60
62
  return (await identityKey()).attestData(attestation, deviceKeyPair, deviceProof);
61
63
  }
@@ -16,6 +16,8 @@ export interface MeshInvite {
16
16
  readonly compute?: boolean;
17
17
  readonly recovery?: RecoveryProof;
18
18
  readonly inviterName?: string;
19
+ readonly deviceSeed?: Buffer;
20
+ readonly deviceProof?: Buffer;
19
21
  }
20
22
  export declare function encodeMeshInvite(invite: MeshInvite): string;
21
23
  export declare function decodeMeshInvite(raw: string): MeshInvite | null;
@@ -13,7 +13,9 @@ export function encodeMeshInvite(invite) {
13
13
  memberId: invite.memberId ?? null,
14
14
  inviteNonce: invite.inviteNonce ?? null,
15
15
  compute: invite.compute ?? false,
16
- inviterName: invite.inviterName ?? null
16
+ inviterName: invite.inviterName ?? null,
17
+ deviceSeed: invite.deviceSeed ?? null,
18
+ deviceProof: invite.deviceProof ?? null
17
19
  };
18
20
  return INVITE_PREFIX + z32.encode(encodeStruct(INVITE_STRUCT, payload));
19
21
  }
@@ -42,6 +44,8 @@ export function decodeMeshInvite(raw) {
42
44
  memberId: payload.memberId ?? undefined,
43
45
  inviteNonce: payload.inviteNonce ?? undefined,
44
46
  compute: payload.compute ?? false,
45
- inviterName: payload.inviterName ?? undefined
47
+ inviterName: payload.inviterName ?? undefined,
48
+ deviceSeed: payload.deviceSeed ?? undefined,
49
+ deviceProof: payload.deviceProof ?? undefined
46
50
  };
47
51
  }
@@ -2,9 +2,7 @@ import type { KeyPair } from 'hyperswarm';
2
2
  import type { Logger } from '../../index.ts';
3
3
  import type { LocalIdentity } from '../../spec/local/hyperschema/types.d.ts';
4
4
  import type { QvacDevice } from '../../spec/mesh/hyperschema/types.d.ts';
5
- import type { DeviceInvites } from './device-invites.ts';
6
- import { type Mesh } from './mesh.ts';
7
- import type { MeshAdmissionRequest } from './mesh-seed-handoff.ts';
5
+ import type { Mesh } from './mesh.ts';
8
6
  export interface MembershipView {
9
7
  readonly members: number;
10
8
  readonly own: QvacDevice | null;
@@ -15,14 +13,6 @@ export interface MembershipContext {
15
13
  readonly log: Logger | null;
16
14
  }
17
15
  export declare function membershipView(mesh: Mesh, deviceId: Buffer): Promise<MembershipView>;
18
- export declare function attestUnattestedDevices(mesh: Mesh, { deviceKeyPair, log }: MembershipContext, invites: DeviceInvites): Promise<void>;
19
- interface AdmitInvitedDeviceOptions {
20
- readonly invites: DeviceInvites;
21
- readonly deviceId: Buffer;
22
- readonly request: MeshAdmissionRequest;
23
- }
24
- export declare function admitInvitedDevice(mesh: Mesh, { deviceKeyPair, log }: MembershipContext, { invites, deviceId, request }: AdmitInvitedDeviceOptions): Promise<boolean>;
25
- export declare function sealAccount(mesh: Mesh, { deviceKeyPair, log }: MembershipContext): Promise<void>;
26
16
  export interface KnownMember {
27
17
  readonly id: Buffer;
28
18
  readonly name: string;
@@ -37,4 +27,3 @@ export interface RenameFoundedMemberOptions {
37
27
  readonly adopt: (name: string, namedAt: number) => Promise<unknown>;
38
28
  }
39
29
  export declare function renameFoundedMember(mesh: Mesh, { deviceKeyPair, log }: MembershipContext, { identity, adopt }: RenameFoundedMemberOptions): Promise<void>;
40
- export {};
@@ -1,10 +1,7 @@
1
1
  import b4a from 'b4a';
2
- import { CAPABILITY_PROFILES } from '../../schema/qvac.js';
3
- import { verifyMemberWriterClaim, verifyWriterClaim } from './device-attestation.js';
4
2
  import { attestDeviceProof, attestMemberClaim, claimAttestation } from './identity.js';
5
- import { claimableDevice } from './mesh.js';
6
3
  import { meshKind } from './contract/mesh-kind.js';
7
- import { DEVICES, MEMBERS, MESH_KINDS } from './collections.js';
4
+ import { DEVICES, MEMBERS } from './collections.js';
8
5
  export async function membershipView(mesh, deviceId) {
9
6
  const snap = mesh.view.snapshot();
10
7
  try {
@@ -28,93 +25,6 @@ export async function membershipView(mesh, deviceId) {
28
25
  await snap.close();
29
26
  }
30
27
  }
31
- export async function attestUnattestedDevices(mesh, { deviceKeyPair, log }, invites) {
32
- const { own, unattested } = await membershipView(mesh, deviceKeyPair.publicKey);
33
- if (!own?.memberId || !own.memberProof || unattested.length === 0) {
34
- return;
35
- }
36
- const ours = own.memberId;
37
- const adoptable = [];
38
- for (const device of unattested) {
39
- if (!device.claimedMemberId || !b4a.equals(device.claimedMemberId, ours)) {
40
- continue;
41
- }
42
- if (await invites.redeem(device.inviteToken, device.id)) {
43
- adoptable.push(device);
44
- }
45
- }
46
- if (adoptable.length === 0) {
47
- return;
48
- }
49
- const now = Date.now();
50
- const batch = mesh.batch();
51
- for (const device of adoptable) {
52
- batch.dispatch('attest-member-device', {
53
- deviceId: device.id,
54
- memberId: ours,
55
- proof: await attestDeviceProof(device.id, deviceKeyPair, own.memberProof),
56
- attestedAt: now
57
- });
58
- }
59
- await batch.flush();
60
- log?.info(['p2p', 'mesh'], 'every device that asked for our member is attested', {
61
- attested: adoptable.length
62
- });
63
- }
64
- export async function admitInvitedDevice(mesh, { deviceKeyPair, log }, { invites, deviceId, request }) {
65
- const own = await mesh.view.get(DEVICES, { id: deviceKeyPair.publicKey });
66
- if (!own?.memberId || !own.memberProof || own.revoked) {
67
- return false;
68
- }
69
- const { writerKey, name, recommendedModelName } = request;
70
- if (!writerKey) {
71
- return false;
72
- }
73
- const joinedAt = request.joinedAt ?? 0;
74
- const claim = { meshPublicKey: mesh.publicKey, deviceId, writerKey, joinedAt };
75
- if (!verifyWriterClaim(request.deviceSignature, claim) ||
76
- !verifyMemberWriterClaim(request.memberSignature, { ...claim, memberId: own.memberId })) {
77
- log?.warn(['p2p', 'mesh'], 'device invite refused: the asker did not sign its claim');
78
- return false;
79
- }
80
- const { capabilityProfile } = request;
81
- if (!name || !recommendedModelName || !isCapabilityProfile(capabilityProfile)) {
82
- log?.warn(['p2p', 'mesh'], 'device invite refused: the asker sent no usable profile');
83
- return false;
84
- }
85
- if (!(await invites.redeem(request.inviteToken, deviceId))) {
86
- log?.warn(['p2p', 'mesh'], 'device invite refused: not one of ours for this device');
87
- return false;
88
- }
89
- await mesh.dispatch('vouched-join', {
90
- signature: mesh.sign(writerKey),
91
- deviceId,
92
- device: claimableDevice({
93
- id: deviceId,
94
- joinedAt,
95
- name,
96
- capabilityProfile,
97
- recommendedModelName
98
- }),
99
- deviceSignature: request.deviceSignature,
100
- writerKey,
101
- memberProof: await attestDeviceProof(deviceId, deviceKeyPair, own.memberProof),
102
- memberSignature: request.memberSignature
103
- });
104
- log?.info(['p2p', 'mesh'], 'the device that redeemed our invite is admitted');
105
- return true;
106
- }
107
- export async function sealAccount(mesh, { deviceKeyPair, log }) {
108
- const own = await mesh.view.get(DEVICES, { id: deviceKeyPair.publicKey });
109
- if (!own?.memberId) {
110
- return;
111
- }
112
- if (await mesh.view.get(MESH_KINDS, { id: 'mesh' })) {
113
- return;
114
- }
115
- await mesh.dispatch('mint-mesh-kind', { id: 'mesh', kind: 'account' });
116
- log?.info(['p2p', 'mesh'], 'the account is sealed against a bare join');
117
- }
118
28
  export async function claimOwnMembership(mesh, { deviceKeyPair, log }, known) {
119
29
  const deviceId = deviceKeyPair.publicKey;
120
30
  const own = await mesh.view.get(DEVICES, { id: deviceId });
@@ -163,6 +73,3 @@ export async function renameFoundedMember(mesh, { deviceKeyPair, log }, { identi
163
73
  });
164
74
  log?.info('membership', 'the member this device founded carries its user name');
165
75
  }
166
- function isCapabilityProfile(value) {
167
- return !!value && CAPABILITY_PROFILES.includes(value);
168
- }
@@ -41,6 +41,7 @@ export interface MeshOptions {
41
41
  attachmentUrl?: AttachmentUrl | null;
42
42
  fileIndex?: MeshFileIndex | null;
43
43
  }
44
+ export declare const MESH_JOINING = "This mesh is still joining: it accepts writes once it is joined";
44
45
  export declare function meshPublicKeyFromSeed(seed: Buffer): Buffer;
45
46
  export declare function isOurTrustedWriter(snap: HyperDB, writerKey: Buffer, ourMemberId: Buffer | null): Promise<boolean>;
46
47
  export type BirthRow = {
@@ -56,17 +57,9 @@ export interface OurMembership {
56
57
  readonly proof: Buffer;
57
58
  readonly attestedAt: number;
58
59
  }
59
- export interface BirthClaim {
60
- readonly memberId?: Buffer;
61
- readonly inviteNonce?: Buffer | null;
62
- }
63
60
  interface BirthOptions {
64
61
  readonly member?: BirthMember;
65
- readonly claim?: BirthClaim;
66
62
  readonly sharing?: boolean;
67
- readonly grantSecret?: Buffer;
68
- readonly recovery?: RecoveryProof;
69
- readonly vouched?: boolean;
70
63
  }
71
64
  export interface RecoveryProof {
72
65
  readonly memberId: Buffer;
@@ -116,8 +109,8 @@ export declare class Mesh extends ReadyResource {
116
109
  private _name;
117
110
  private _membership;
118
111
  private readonly _deviceId;
119
- private readonly _grantExpiry;
120
112
  private _admitted;
113
+ private _birth;
121
114
  private _autobee;
122
115
  private _blobs;
123
116
  private _syncActivity;
@@ -142,9 +135,6 @@ export declare class Mesh extends ReadyResource {
142
135
  get name(): QvacMeshName | null;
143
136
  refreshName(): Promise<void>;
144
137
  setName(name: string): Promise<void>;
145
- refreshGrantExpiry(): Promise<void>;
146
- bornKind(): Promise<string | null | undefined>;
147
- waitForGenesis(timeout: number): Promise<string | null | undefined>;
148
138
  sign(message: Buffer): Buffer;
149
139
  attestDevice(deviceId: Buffer): DeviceAttestation;
150
140
  constructor(store: Corestore, opts?: MeshOptions);
@@ -160,9 +150,12 @@ export declare class Mesh extends ReadyResource {
160
150
  get minted(): boolean;
161
151
  get writable(): boolean;
162
152
  get localLength(): number;
153
+ get joining(): boolean;
163
154
  dispatch(name: string, payload: unknown, opts?: AppendOptions): Promise<void>;
164
155
  batch(): MeshBatch;
165
- appendBirthOp(identity: Buffer | KeyPair, device?: DeviceMetadata, { member, claim, sharing, grantSecret, recovery, vouched }?: BirthOptions): Promise<void>;
156
+ appendBirthOp(identity: Buffer | KeyPair, device?: DeviceMetadata, opts?: BirthOptions | (() => Promise<BirthOptions>)): Promise<void>;
157
+ private _settleBirth;
158
+ private _appendBirthOp;
166
159
  get interrupted(): unknown;
167
160
  throwIfInterrupted(): void;
168
161
  waitForWritable(timeout?: number): Promise<void>;
@@ -190,10 +183,12 @@ export interface MeshDispatcher {
190
183
  }
191
184
  export interface MeshBatchOptions {
192
185
  readonly compute?: boolean;
186
+ readonly joined?: boolean;
193
187
  }
194
188
  export declare class MeshBatch {
195
189
  private readonly _autobee;
196
190
  private readonly _compute;
191
+ private readonly _joined;
197
192
  private _ops;
198
193
  constructor(autobee: Autobee<MeshView>, opts?: MeshBatchOptions);
199
194
  get size(): number;