@941design/marmot 0.0.0-stage → 0.2.0-alpha.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.
- package/CHANGELOG.md +739 -0
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/account/admin.d.ts +72 -0
- package/dist/account/admin.js +209 -0
- package/dist/account/device-deps.d.ts +379 -0
- package/dist/account/device-deps.js +36 -0
- package/dist/account/device-lineage.d.ts +199 -0
- package/dist/account/device-lineage.js +390 -0
- package/dist/account/device-registry.d.ts +93 -0
- package/dist/account/device-registry.js +1290 -0
- package/dist/account/device-rotation.d.ts +61 -0
- package/dist/account/device-rotation.js +827 -0
- package/dist/account/enrolment.d.ts +339 -0
- package/dist/account/enrolment.js +1247 -0
- package/dist/account/identity-proof.d.ts +79 -0
- package/dist/account/identity-proof.js +264 -0
- package/dist/account/index.d.ts +17 -0
- package/dist/account/index.js +16 -0
- package/dist/account/restore-rotation.d.ts +21 -0
- package/dist/account/restore-rotation.js +22 -0
- package/dist/account/same-account-authorization.d.ts +86 -0
- package/dist/account/same-account-authorization.js +180 -0
- package/dist/account/teardown.d.ts +190 -0
- package/dist/account/teardown.js +878 -0
- package/dist/client/admission-cleanup.d.ts +197 -0
- package/dist/client/admission-cleanup.js +635 -0
- package/dist/client/adoption-proof.d.ts +39 -0
- package/dist/client/adoption-proof.js +102 -0
- package/dist/client/before-create-group.d.ts +18 -0
- package/dist/client/before-create-group.js +65 -0
- package/dist/client/before-publish-hooks.d.ts +121 -0
- package/dist/client/before-publish-hooks.js +182 -0
- package/dist/client/client-config.d.ts +42 -0
- package/dist/client/client-config.js +13 -0
- package/dist/client/commit-redrive.d.ts +92 -0
- package/dist/client/commit-redrive.js +274 -0
- package/dist/client/component-update.d.ts +43 -0
- package/dist/client/component-update.js +53 -0
- package/dist/client/confirm-hooks.d.ts +55 -0
- package/dist/client/confirm-hooks.js +74 -0
- package/dist/client/create-client.d.ts +1126 -0
- package/dist/client/create-client.js +1232 -0
- package/dist/client/group-availability.d.ts +182 -0
- package/dist/client/group-availability.js +301 -0
- package/dist/client/group-disband.d.ts +28 -0
- package/dist/client/group-disband.js +64 -0
- package/dist/client/group-history.d.ts +461 -0
- package/dist/client/group-history.js +1365 -0
- package/dist/client/group-profile.d.ts +31 -0
- package/dist/client/group-profile.js +62 -0
- package/dist/client/group-records.d.ts +522 -0
- package/dist/client/group-records.js +1117 -0
- package/dist/client/group-removal.d.ts +36 -0
- package/dist/client/group-removal.js +127 -0
- package/dist/client/group-remove-member.d.ts +49 -0
- package/dist/client/group-remove-member.js +163 -0
- package/dist/client/group-runtime.d.ts +415 -0
- package/dist/client/group-runtime.js +2811 -0
- package/dist/client/group-snapshot.d.ts +104 -0
- package/dist/client/group-snapshot.js +474 -0
- package/dist/client/history-pages.d.ts +107 -0
- package/dist/client/history-pages.js +194 -0
- package/dist/client/inbox-send.d.ts +19 -0
- package/dist/client/inbox-send.js +71 -0
- package/dist/client/index.d.ts +24 -0
- package/dist/client/index.js +13 -0
- package/dist/client/ingest.d.ts +82 -0
- package/dist/client/ingest.js +1584 -0
- package/dist/client/invitation-outcomes.d.ts +50 -0
- package/dist/client/invitation-outcomes.js +135 -0
- package/dist/client/lifecycle-events.d.ts +63 -0
- package/dist/client/lifecycle-events.js +35 -0
- package/dist/client/opaque-candidates.d.ts +82 -0
- package/dist/client/opaque-candidates.js +170 -0
- package/dist/client/own-change-outbox.d.ts +66 -0
- package/dist/client/own-change-outbox.js +158 -0
- package/dist/client/pending-leaf.d.ts +116 -0
- package/dist/client/pending-leaf.js +378 -0
- package/dist/client/permissions.d.ts +9 -0
- package/dist/client/permissions.js +12 -0
- package/dist/client/pipeline.d.ts +583 -0
- package/dist/client/pipeline.js +3666 -0
- package/dist/client/reentrancy-guard.d.ts +102 -0
- package/dist/client/reentrancy-guard.js +159 -0
- package/dist/client/rekey.d.ts +58 -0
- package/dist/client/rekey.js +149 -0
- package/dist/client/transport-policy.d.ts +181 -0
- package/dist/client/transport-policy.js +214 -0
- package/dist/history/admission-lineage.d.ts +186 -0
- package/dist/history/admission-lineage.js +589 -0
- package/dist/history/equivocation.d.ts +55 -0
- package/dist/history/equivocation.js +113 -0
- package/dist/history/fencing.d.ts +66 -0
- package/dist/history/fencing.js +121 -0
- package/dist/history/hex.d.ts +3 -0
- package/dist/history/hex.js +10 -0
- package/dist/history/index.d.ts +74 -0
- package/dist/history/index.js +32 -0
- package/dist/history/notifications.d.ts +270 -0
- package/dist/history/notifications.js +264 -0
- package/dist/history/ordering-key.d.ts +24 -0
- package/dist/history/ordering-key.js +101 -0
- package/dist/history/own-change-fork.d.ts +112 -0
- package/dist/history/own-change-fork.js +196 -0
- package/dist/history/own-change.d.ts +118 -0
- package/dist/history/own-change.js +146 -0
- package/dist/history/policy.d.ts +48 -0
- package/dist/history/policy.js +52 -0
- package/dist/history/retained-window.d.ts +215 -0
- package/dist/history/retained-window.js +565 -0
- package/dist/inbox/demux.d.ts +90 -0
- package/dist/inbox/demux.js +78 -0
- package/dist/inbox/handler-registry.d.ts +42 -0
- package/dist/inbox/handler-registry.js +37 -0
- package/dist/inbox/index.d.ts +11 -0
- package/dist/inbox/index.js +10 -0
- package/dist/inbox/seen-set.d.ts +82 -0
- package/dist/inbox/seen-set.js +202 -0
- package/dist/inbox/subscription.d.ts +236 -0
- package/dist/inbox/subscription.js +644 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/invitations/competing-welcome.d.ts +223 -0
- package/dist/invitations/competing-welcome.js +128 -0
- package/dist/invitations/decline.d.ts +67 -0
- package/dist/invitations/decline.js +149 -0
- package/dist/invitations/delivery-evidence.d.ts +288 -0
- package/dist/invitations/delivery-evidence.js +766 -0
- package/dist/invitations/expect-welcome.d.ts +66 -0
- package/dist/invitations/expect-welcome.js +138 -0
- package/dist/invitations/index.d.ts +18 -0
- package/dist/invitations/index.js +18 -0
- package/dist/invitations/invitation-outcome.d.ts +110 -0
- package/dist/invitations/invitation-outcome.js +210 -0
- package/dist/invitations/invite.d.ts +358 -0
- package/dist/invitations/invite.js +1102 -0
- package/dist/invitations/offers.d.ts +79 -0
- package/dist/invitations/offers.js +115 -0
- package/dist/invitations/on-proposal.d.ts +47 -0
- package/dist/invitations/on-proposal.js +40 -0
- package/dist/invitations/pending-proposal-policy.d.ts +52 -0
- package/dist/invitations/pending-proposal-policy.js +139 -0
- package/dist/invitations/proposal-deadline.d.ts +133 -0
- package/dist/invitations/proposal-deadline.js +164 -0
- package/dist/invitations/relay-planes.d.ts +43 -0
- package/dist/invitations/relay-planes.js +70 -0
- package/dist/invitations/welcome-processor.d.ts +272 -0
- package/dist/invitations/welcome-processor.js +1241 -0
- package/dist/key-packages/device-key.d.ts +131 -0
- package/dist/key-packages/device-key.js +272 -0
- package/dist/key-packages/device-rotation-records.d.ts +83 -0
- package/dist/key-packages/device-rotation-records.js +173 -0
- package/dist/key-packages/group-refs.d.ts +40 -0
- package/dist/key-packages/group-refs.js +79 -0
- package/dist/key-packages/index.d.ts +18 -0
- package/dist/key-packages/index.js +18 -0
- package/dist/key-packages/key-package-ref.d.ts +16 -0
- package/dist/key-packages/key-package-ref.js +21 -0
- package/dist/key-packages/observation-stream.d.ts +4 -0
- package/dist/key-packages/observation-stream.js +120 -0
- package/dist/key-packages/offer-rumor.d.ts +26 -0
- package/dist/key-packages/offer-rumor.js +69 -0
- package/dist/key-packages/publisher.d.ts +174 -0
- package/dist/key-packages/publisher.js +1247 -0
- package/dist/key-packages/select-key-package.d.ts +24 -0
- package/dist/key-packages/select-key-package.js +90 -0
- package/dist/key-packages/slot-manager.d.ts +167 -0
- package/dist/key-packages/slot-manager.js +327 -0
- package/dist/key-packages/validate-key-package-event.d.ts +3 -0
- package/dist/key-packages/validate-key-package-event.js +49 -0
- package/dist/media/cache.d.ts +14 -0
- package/dist/media/cache.js +10 -0
- package/dist/media/index.d.ts +52 -0
- package/dist/media/index.js +71 -0
- package/dist/mls.d.ts +15 -0
- package/dist/mls.js +15 -0
- package/dist/shared/account-pubkey.d.ts +4 -0
- package/dist/shared/account-pubkey.js +10 -0
- package/dist/shared/errors.d.ts +28 -0
- package/dist/shared/errors.js +96 -0
- package/dist/shared/hex.d.ts +4 -0
- package/dist/shared/hex.js +13 -0
- package/dist/shared/index.d.ts +14 -0
- package/dist/shared/index.js +14 -0
- package/dist/shared/kinds.d.ts +8 -0
- package/dist/shared/kinds.js +28 -0
- package/dist/shared/publish-classification.d.ts +26 -0
- package/dist/shared/publish-classification.js +31 -0
- package/dist/storage/envelope.d.ts +39 -0
- package/dist/storage/envelope.js +201 -0
- package/dist/storage/index.d.ts +237 -0
- package/dist/storage/index.js +491 -0
- package/dist/storage/indexeddb/idb-types.d.ts +68 -0
- package/dist/storage/indexeddb/idb-types.js +1 -0
- package/dist/storage/indexeddb/index.d.ts +17 -0
- package/dist/storage/indexeddb/index.js +141 -0
- package/dist/storage/lease.d.ts +54 -0
- package/dist/storage/lease.js +168 -0
- package/dist/storage/memory/deterministic-signer.d.ts +27 -0
- package/dist/storage/memory/deterministic-signer.js +65 -0
- package/dist/storage/memory/index.d.ts +32 -0
- package/dist/storage/memory/index.js +87 -0
- package/dist/storage/memory/lock-manager.d.ts +8 -0
- package/dist/storage/memory/lock-manager.js +71 -0
- package/package.json +66 -3
|
@@ -0,0 +1,1247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Same-account enrolment (S8; ADR-003 Decision 3, AC-DEV-5, -6, -9, -11,
|
|
3
|
+
* -13): a new device of an account asks an online sibling to add it to
|
|
4
|
+
* groups, over the account's own inbox.
|
|
5
|
+
*
|
|
6
|
+
* Request (the new device, {@link requestEnrolment}): one fresh KeyPackage
|
|
7
|
+
* per requested group (S4 `keyPackages.create`, so the private halves live in
|
|
8
|
+
* the durable slot records the Welcome processor looks keys up in), one
|
|
9
|
+
* `expectWelcome` manifest per group — `(group, KeyPackageRef, sponsor = the
|
|
10
|
+
* account itself)`, deadline = the request's expiry — and then ONE
|
|
11
|
+
* `RUMOR_KINDS.ENROLMENT_REQUEST` rumor `{ sessionId, expiresAt, label,
|
|
12
|
+
* groups: [{ groupId, keyPackageEvent }] }`, gift-wrapped to the account and
|
|
13
|
+
* published to the account's inbox relays only (AC-DEV-13). The request id is
|
|
14
|
+
* that rumor's id. Manifests and the outbound record (with the wrap, once
|
|
15
|
+
* sealed) are durable before anything is published; an unpublished request
|
|
16
|
+
* is re-published by later inbox passes until it expires.
|
|
17
|
+
*
|
|
18
|
+
* Arrival (every sibling, {@link handleEnrolmentRumor} — the native handler
|
|
19
|
+
* S7's demux runs on the inbox queue): the author must be the account itself
|
|
20
|
+
* (seal-authenticated); the device's own requests are ignored; a request past
|
|
21
|
+
* its `expiresAt`, or whose id this client has recorded before (a replay under
|
|
22
|
+
* a fresh wrap, or after the seen-set evicted the first), produces no prompt;
|
|
23
|
+
* a session id may send several distinct requests, but beyond
|
|
24
|
+
* `promptRateLimit` prompted requests within a minute the rest are recorded as
|
|
25
|
+
* dropped — silently: no prompt, no event (AC-DEV-5). A request that passes is
|
|
26
|
+
* recorded `pending` together with the wrap's seen mark, and only then is its
|
|
27
|
+
* prompt emitted ({@link EnrolmentPrompt}, AC-DEV-9).
|
|
28
|
+
*
|
|
29
|
+
* Approval ({@link approveEnrolment}, the application's answer to a prompt):
|
|
30
|
+
* one durable approval record — every requested group's manifest
|
|
31
|
+
* `(group, KeyPackageRef, sponsor)` and a per-group outcome (AC-DEV-6) — is
|
|
32
|
+
* written before any commit; then, group by group, S5's durable invite of the
|
|
33
|
+
* requested KeyPackage (one Add per group, committed by this leaf even when it
|
|
34
|
+
* is not an admin — the same-account seams; its Welcome goes to the account's
|
|
35
|
+
* inbox relays). Each group's outcome is read back from the group itself —
|
|
36
|
+
* the device's leaf present → `enrolled`; an own commit still pending → wait;
|
|
37
|
+
* otherwise retried, and given up (`failed`) after {@link MAX_GROUP_ATTEMPTS}
|
|
38
|
+
* attempts — so a crash, a lost race or a commit that went terminal resolve
|
|
39
|
+
* the same way on the next pass. Once every group is terminal, the record
|
|
40
|
+
* turns `approved`, the device's label is bound to its leaf key in the
|
|
41
|
+
* registry, and — through `ctx.lifecycle.afterCommit`, after that transaction
|
|
42
|
+
* committed — `enrolmentApproved` fires (AC-INBOX-6). An approval notice
|
|
43
|
+
* rumor then tells the siblings, whose prompts for that request are closed.
|
|
44
|
+
*
|
|
45
|
+
* "Top up" (AC-DEV-11) is the same flow with the old device as the sibling:
|
|
46
|
+
* whichever sibling approves, the new leaf enters at the Welcome's epoch and
|
|
47
|
+
* holds no secret of an earlier one.
|
|
48
|
+
*/
|
|
49
|
+
import { getEventHash } from '@941design/nostr-events/event';
|
|
50
|
+
import { wrap as giftWrap } from '@941design/nostr-events/gift-wrap';
|
|
51
|
+
import { getKeyPackage } from '@941design/marmot-engine/core';
|
|
52
|
+
import { maintenanceFailureReason } from '../inbox/index.js';
|
|
53
|
+
import { recordManifest, resolveInboxRelays, validateManifest } from '../invitations/index.js';
|
|
54
|
+
import { computeKeyPackageRefHex, readDeviceSigningKey, recordKeyPackageGroupRef, validateKeyPackageEvent } from '../key-packages/index.js';
|
|
55
|
+
import { classifyPublish, isMarmotError, MarmotError, RUMOR_KINDS } from '../shared/index.js';
|
|
56
|
+
import { DEVICE_REGISTRY_ARTIFACT, forgetDepartureTime, MAX_MAINTENANCE_FAILURES, tombstoneDepartureTime } from './device-deps.js';
|
|
57
|
+
import { loadDeviceLineage, persistSuccessionEdges, viewSuccessionEdges } from './device-lineage.js';
|
|
58
|
+
import { MAX_LEAVES_PER_ACCOUNT } from './same-account-authorization.js';
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// Constants
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
const ARTIFACT = 'enrolmentSessions';
|
|
63
|
+
/** Default `promptRateLimit`: prompted requests per session id per minute. */
|
|
64
|
+
export const DEFAULT_PROMPT_RATE_LIMIT = 3;
|
|
65
|
+
export const PROMPT_RATE_WINDOW_MS = 60_000;
|
|
66
|
+
export const DEFAULT_ENROLMENT_EXPIRY_MINUTES = 10;
|
|
67
|
+
export const MAX_ENROLMENT_EXPIRY_MINUTES = 24 * 60;
|
|
68
|
+
/** Most groups one request may name. */
|
|
69
|
+
export const MAX_ENROLMENT_GROUPS = 32;
|
|
70
|
+
/** Commit attempts per group before an approval gives that group up (`failed`). */
|
|
71
|
+
export const MAX_GROUP_ATTEMPTS = 3;
|
|
72
|
+
/** Records are kept this long past their request's expiry (replay detection needs them until then). */
|
|
73
|
+
const RETAIN_PAST_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
|
74
|
+
const MAX_LABEL_LENGTH = 128;
|
|
75
|
+
const MAX_SESSION_ID_LENGTH = 128;
|
|
76
|
+
const HEX = /^[0-9a-f]+$/;
|
|
77
|
+
function hexBytes(bytes) {
|
|
78
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
79
|
+
}
|
|
80
|
+
function randomHex(bytes) {
|
|
81
|
+
const out = new Uint8Array(bytes);
|
|
82
|
+
globalThis.crypto.getRandomValues(out);
|
|
83
|
+
return hexBytes(out);
|
|
84
|
+
}
|
|
85
|
+
function invalid(operation, message, reason, details = {}) {
|
|
86
|
+
return new MarmotError('invalid-options', `devices.${operation}: ${message}`, { details: { reason, ...details } });
|
|
87
|
+
}
|
|
88
|
+
/** Builds the enrolment-request rumor (unsigned, per NIP-59; its id is the request id). */
|
|
89
|
+
export function encodeEnrolmentRequestRumor(opts) {
|
|
90
|
+
const content = JSON.stringify({
|
|
91
|
+
v: 1,
|
|
92
|
+
type: 'request',
|
|
93
|
+
sessionId: opts.sessionId,
|
|
94
|
+
expiresAt: opts.expiresAt,
|
|
95
|
+
label: opts.label,
|
|
96
|
+
groups: opts.groups.map((g) => ({ groupId: g.groupId, keyPackageEvent: g.keyPackageEvent })),
|
|
97
|
+
});
|
|
98
|
+
const unsigned = { pubkey: opts.pubkey, kind: RUMOR_KINDS.ENROLMENT_REQUEST, created_at: opts.createdAt, tags: [], content };
|
|
99
|
+
return { ...unsigned, id: getEventHash(unsigned) };
|
|
100
|
+
}
|
|
101
|
+
/** Builds the approval-notice rumor a sibling sends once it approved `requestId`. */
|
|
102
|
+
export function encodeEnrolmentApprovalRumor(opts) {
|
|
103
|
+
const content = JSON.stringify({ v: 1, type: 'approved', requestId: opts.requestId, leafKey: opts.leafKey, groups: [...opts.groups] });
|
|
104
|
+
const unsigned = { pubkey: opts.pubkey, kind: RUMOR_KINDS.ENROLMENT_REQUEST, created_at: opts.createdAt, tags: [], content };
|
|
105
|
+
return { ...unsigned, id: getEventHash(unsigned) };
|
|
106
|
+
}
|
|
107
|
+
function isEventShape(value) {
|
|
108
|
+
if (typeof value !== 'object' || value === null)
|
|
109
|
+
return false;
|
|
110
|
+
const e = value;
|
|
111
|
+
return (typeof e['id'] === 'string' &&
|
|
112
|
+
typeof e['pubkey'] === 'string' &&
|
|
113
|
+
typeof e['kind'] === 'number' &&
|
|
114
|
+
typeof e['created_at'] === 'number' &&
|
|
115
|
+
typeof e['sig'] === 'string' &&
|
|
116
|
+
typeof e['content'] === 'string' &&
|
|
117
|
+
Array.isArray(e['tags']));
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Parses an enrolment rumor. Never throws: anything malformed — a wrong kind,
|
|
121
|
+
* bad JSON or fields, a KeyPackage event that is not a valid kind-30443 event
|
|
122
|
+
* of the rumor's own author, two groups named twice, KeyPackages carrying
|
|
123
|
+
* different leaf keys — yields `undefined`.
|
|
124
|
+
*/
|
|
125
|
+
export function decodeEnrolmentRumor(rumor) {
|
|
126
|
+
if (rumor.kind !== RUMOR_KINDS.ENROLMENT_REQUEST)
|
|
127
|
+
return undefined;
|
|
128
|
+
let parsed;
|
|
129
|
+
try {
|
|
130
|
+
parsed = JSON.parse(rumor.content);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
136
|
+
return undefined;
|
|
137
|
+
const p = parsed;
|
|
138
|
+
if (p['v'] !== 1)
|
|
139
|
+
return undefined;
|
|
140
|
+
if (p['type'] === 'approved') {
|
|
141
|
+
const { requestId, leafKey, groups } = p;
|
|
142
|
+
if (typeof requestId !== 'string' || !HEX.test(requestId) || typeof leafKey !== 'string' || !HEX.test(leafKey))
|
|
143
|
+
return undefined;
|
|
144
|
+
if (!Array.isArray(groups) || !groups.every((g) => typeof g === 'string'))
|
|
145
|
+
return undefined;
|
|
146
|
+
return { type: 'approved', requestId, leafKey, groups: groups };
|
|
147
|
+
}
|
|
148
|
+
if (p['type'] !== 'request')
|
|
149
|
+
return undefined;
|
|
150
|
+
const { sessionId, expiresAt, label, groups } = p;
|
|
151
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > MAX_SESSION_ID_LENGTH)
|
|
152
|
+
return undefined;
|
|
153
|
+
if (typeof expiresAt !== 'number' || !Number.isSafeInteger(expiresAt) || expiresAt <= 0)
|
|
154
|
+
return undefined;
|
|
155
|
+
if (typeof label !== 'string' || label.length > MAX_LABEL_LENGTH)
|
|
156
|
+
return undefined;
|
|
157
|
+
if (!Array.isArray(groups) || groups.length === 0 || groups.length > MAX_ENROLMENT_GROUPS)
|
|
158
|
+
return undefined;
|
|
159
|
+
const entries = [];
|
|
160
|
+
const seen = new Set();
|
|
161
|
+
let leafKey;
|
|
162
|
+
for (const raw of groups) {
|
|
163
|
+
if (typeof raw !== 'object' || raw === null)
|
|
164
|
+
return undefined;
|
|
165
|
+
const { groupId, keyPackageEvent } = raw;
|
|
166
|
+
if (typeof groupId !== 'string' || !HEX.test(groupId) || seen.has(groupId))
|
|
167
|
+
return undefined;
|
|
168
|
+
if (!isEventShape(keyPackageEvent) || keyPackageEvent.pubkey !== rumor.pubkey)
|
|
169
|
+
return undefined;
|
|
170
|
+
const keyPackage = validateKeyPackageEvent(keyPackageEvent);
|
|
171
|
+
if (keyPackage === undefined)
|
|
172
|
+
return undefined;
|
|
173
|
+
const key = hexBytes(keyPackage.leafNode.signaturePublicKey);
|
|
174
|
+
if (leafKey !== undefined && key !== leafKey)
|
|
175
|
+
return undefined;
|
|
176
|
+
leafKey = key;
|
|
177
|
+
seen.add(groupId);
|
|
178
|
+
// NIP-01 fields only (verification tags the object it checked with a symbol).
|
|
179
|
+
const { id, pubkey, created_at, kind, tags, content, sig } = keyPackageEvent;
|
|
180
|
+
entries.push({ groupId, keyPackageEvent: { id, pubkey, created_at, kind, tags: tags.map((t) => [...t]), content, sig } });
|
|
181
|
+
}
|
|
182
|
+
return { type: 'request', sessionId, expiresAt, label, groups: entries, leafKey: leafKey };
|
|
183
|
+
}
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
// Gift-wrap size budget (X1)
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
/**
|
|
188
|
+
* NIP-44 v2's plaintext limit (nostr-tools `nip44`: 1..65535 bytes, UTF-8).
|
|
189
|
+
* A NIP-59 gift wrap encrypts TWICE: the rumor JSON into the seal's content,
|
|
190
|
+
* then the seal event's JSON into the wrap's content. So the rumor must fit
|
|
191
|
+
* 65535 bytes itself AND the seal JSON it produces must:
|
|
192
|
+
*
|
|
193
|
+
* seal JSON = SEAL_JSON_OVERHEAD + base64(1 version + 32 nonce + 2 length
|
|
194
|
+
* + padded(rumor bytes) + 32 MAC)
|
|
195
|
+
*
|
|
196
|
+
* with NIP-44's padding (`calcPaddedLen`: 32 up to 32 bytes, else chunks of
|
|
197
|
+
* nextPow2/8, at least 32). That bounds the rumor JSON at 40 960 bytes (five
|
|
198
|
+
* 8 KiB chunks: 1 + 32 + 2 + 40 960 + 32 = 41 027 bytes → 54 704 base64 chars
|
|
199
|
+
* + overhead; six chunks, 49 152 bytes, would need 65 628 base64 chars).
|
|
200
|
+
*/
|
|
201
|
+
export const NIP44_MAX_PLAINTEXT_BYTES = 65_535;
|
|
202
|
+
function nip44PaddedLength(length) {
|
|
203
|
+
if (length <= 32)
|
|
204
|
+
return 32;
|
|
205
|
+
const nextPower = 2 ** (Math.floor(Math.log2(length - 1)) + 1);
|
|
206
|
+
const chunk = nextPower <= 256 ? 32 : nextPower / 8;
|
|
207
|
+
return chunk * (Math.floor((length - 1) / chunk) + 1);
|
|
208
|
+
}
|
|
209
|
+
/** Base64 characters of a NIP-44 v2 payload for a `plaintextBytes`-byte plaintext. */
|
|
210
|
+
export function nip44PayloadLength(plaintextBytes) {
|
|
211
|
+
return 4 * Math.ceil((1 + 32 + 2 + nip44PaddedLength(plaintextBytes) + 32) / 3);
|
|
212
|
+
}
|
|
213
|
+
/** The seal event's JSON (gift-wrap/index.ts: `JSON.stringify(seal)`) without its content: widest values of every field. */
|
|
214
|
+
const SEAL_JSON_OVERHEAD = JSON.stringify({
|
|
215
|
+
kind: 13,
|
|
216
|
+
created_at: 9_999_999_999,
|
|
217
|
+
tags: [['p', '0'.repeat(64)]],
|
|
218
|
+
content: '',
|
|
219
|
+
pubkey: '0'.repeat(64),
|
|
220
|
+
id: '0'.repeat(64),
|
|
221
|
+
sig: '0'.repeat(128),
|
|
222
|
+
}).length;
|
|
223
|
+
/** Whether a rumor whose JSON is `rumorBytes` bytes fits both NIP-44 layers of a gift wrap. */
|
|
224
|
+
export function fitsGiftWrap(rumorBytes) {
|
|
225
|
+
return rumorBytes <= NIP44_MAX_PLAINTEXT_BYTES && SEAL_JSON_OVERHEAD + nip44PayloadLength(rumorBytes) <= NIP44_MAX_PLAINTEXT_BYTES;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Default relay event-size budget for a gift wrap this client publishes (`ClientOptions.maxGiftWrapBytes`):
|
|
229
|
+
* 64 KiB of event JSON, a common relay cap (and FakeRelay's frame bound). A request inside both NIP-44 bounds
|
|
230
|
+
* can still produce a ~74 KB wrap that such relays refuse — persisted and retried until it expires, never
|
|
231
|
+
* delivered — so it is refused up front instead.
|
|
232
|
+
*/
|
|
233
|
+
export const DEFAULT_MAX_GIFT_WRAP_BYTES = 65_536;
|
|
234
|
+
/** The wrap event's JSON (gift-wrap/index.ts: one `p` tag, no extra wrap tags) without its content: widest values of every field. */
|
|
235
|
+
const WRAP_JSON_OVERHEAD = JSON.stringify({
|
|
236
|
+
kind: 1059,
|
|
237
|
+
created_at: 9_999_999_999,
|
|
238
|
+
tags: [['p', '0'.repeat(64)]],
|
|
239
|
+
content: '',
|
|
240
|
+
pubkey: '0'.repeat(64),
|
|
241
|
+
id: '0'.repeat(64),
|
|
242
|
+
sig: '0'.repeat(128),
|
|
243
|
+
}).length;
|
|
244
|
+
/**
|
|
245
|
+
* Upper bound on the event-JSON bytes of the gift wrap carrying a `rumorBytes`-byte rumor: the wrap's content
|
|
246
|
+
* is the NIP-44 payload of the seal's JSON (ASCII: base64 content, hex fields), itself carrying the rumor's payload.
|
|
247
|
+
*/
|
|
248
|
+
export function giftWrapBytes(rumorBytes) {
|
|
249
|
+
return WRAP_JSON_OVERHEAD + nip44PayloadLength(SEAL_JSON_OVERHEAD + nip44PayloadLength(rumorBytes));
|
|
250
|
+
}
|
|
251
|
+
function rumorBytes(rumor) {
|
|
252
|
+
return new TextEncoder().encode(JSON.stringify(rumor)).length;
|
|
253
|
+
}
|
|
254
|
+
function assertWrappable(rumor, operation, maxGiftWrapBytes) {
|
|
255
|
+
const bytes = rumorBytes(rumor);
|
|
256
|
+
if (!fitsGiftWrap(bytes)) {
|
|
257
|
+
throw invalid(operation, `the request (${bytes} bytes as a rumor) exceeds what one gift wrap can carry; request fewer groups at a time`, 'request-too-large', { rumorBytes: bytes });
|
|
258
|
+
}
|
|
259
|
+
const wrapBytes = giftWrapBytes(bytes);
|
|
260
|
+
if (wrapBytes <= maxGiftWrapBytes)
|
|
261
|
+
return;
|
|
262
|
+
throw invalid(operation, `the request's gift wrap (${wrapBytes} bytes) exceeds the relay event-size budget of ${maxGiftWrapBytes} bytes (options.maxGiftWrapBytes); request fewer groups at a time`, 'request-too-large', { rumorBytes: bytes, wrapBytes, maxGiftWrapBytes });
|
|
263
|
+
}
|
|
264
|
+
/** Upper bound on the base64 content of a KeyPackage event this client mints (measured ~650; the proof and components included). */
|
|
265
|
+
const KEYPACKAGE_CONTENT_BOUND = 1_024;
|
|
266
|
+
/**
|
|
267
|
+
* An upper-bound stand-in for a KeyPackage event this client will mint, naming
|
|
268
|
+
* `relays`: every field at its widest (the engine's tag set — `d`, protocol
|
|
269
|
+
* version, `i`, cipher suite, extensions, proposals, app components — with
|
|
270
|
+
* more entries than it emits), content at {@link KEYPACKAGE_CONTENT_BOUND}.
|
|
271
|
+
*/
|
|
272
|
+
function keyPackageEventBound(pubkey, relays) {
|
|
273
|
+
const code = '0xffff';
|
|
274
|
+
return {
|
|
275
|
+
id: '0'.repeat(64),
|
|
276
|
+
pubkey,
|
|
277
|
+
created_at: 9_999_999_999,
|
|
278
|
+
kind: 30443,
|
|
279
|
+
tags: [
|
|
280
|
+
['d', '0'.repeat(64)],
|
|
281
|
+
['mls_protocol_version', '1.0'],
|
|
282
|
+
['i', '0'.repeat(64)],
|
|
283
|
+
['mls_ciphersuite', code],
|
|
284
|
+
['mls_extensions', ...Array(8).fill(code)],
|
|
285
|
+
['mls_proposals', ...Array(8).fill(code)],
|
|
286
|
+
['app_components', ...Array(16).fill(code)],
|
|
287
|
+
['relays', ...relays],
|
|
288
|
+
],
|
|
289
|
+
content: 'A'.repeat(KEYPACKAGE_CONTENT_BOUND),
|
|
290
|
+
sig: '0'.repeat(128),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
const inKey = (requestId) => `in:${requestId}`;
|
|
294
|
+
const outKey = (requestId) => `out:${requestId}`;
|
|
295
|
+
const approvedKey = (requestId) => `approved:${requestId}`;
|
|
296
|
+
function malformed(key) {
|
|
297
|
+
return new MarmotError('store-failed', `enrolmentSessions/${key}: malformed record`, { details: { key, malformed: true } });
|
|
298
|
+
}
|
|
299
|
+
async function readInbound(view, requestId) {
|
|
300
|
+
const raw = await view.get(inKey(requestId));
|
|
301
|
+
if (raw === undefined)
|
|
302
|
+
return undefined;
|
|
303
|
+
const r = raw;
|
|
304
|
+
if (r.v !== 1 || r.requestId !== requestId || typeof r.status !== 'string' || !Array.isArray(r.groups))
|
|
305
|
+
throw malformed(inKey(requestId));
|
|
306
|
+
return r;
|
|
307
|
+
}
|
|
308
|
+
async function writeInbound(view, record) {
|
|
309
|
+
await view.put(inKey(record.requestId), record);
|
|
310
|
+
}
|
|
311
|
+
async function readOutbound(view, requestId) {
|
|
312
|
+
const raw = await view.get(outKey(requestId));
|
|
313
|
+
if (raw === undefined)
|
|
314
|
+
return undefined;
|
|
315
|
+
const r = raw;
|
|
316
|
+
if (r.v !== 1 || r.requestId !== requestId || typeof r.rumor !== 'object')
|
|
317
|
+
throw malformed(outKey(requestId));
|
|
318
|
+
return r;
|
|
319
|
+
}
|
|
320
|
+
/** Drops records whose request expired more than a day ago (replays of them are rejected as expired anyway). */
|
|
321
|
+
async function prune(view, nowMs) {
|
|
322
|
+
for (const key of await view.keys()) {
|
|
323
|
+
const raw = (await view.get(key));
|
|
324
|
+
if (raw === undefined)
|
|
325
|
+
continue;
|
|
326
|
+
if (key.startsWith('approved:')) {
|
|
327
|
+
if (typeof raw.receivedAt === 'number' && raw.receivedAt + RETAIN_PAST_EXPIRY_MS * 2 < nowMs)
|
|
328
|
+
await view.delete(key);
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (raw.status === 'approving')
|
|
332
|
+
continue;
|
|
333
|
+
if (typeof raw.expiresAt === 'number' && raw.expiresAt * 1000 + RETAIN_PAST_EXPIRY_MS < nowMs)
|
|
334
|
+
await view.delete(key);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
// ---------------------------------------------------------------------------
|
|
338
|
+
// Prompts
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
function remainingGroups(record) {
|
|
341
|
+
const approved = new Set(record.approvedGroups ?? []);
|
|
342
|
+
return record.groups.map((g) => g.groupId).filter((g) => !approved.has(g));
|
|
343
|
+
}
|
|
344
|
+
function promptOf(record, nowMs) {
|
|
345
|
+
return Object.freeze({
|
|
346
|
+
requestId: record.requestId,
|
|
347
|
+
sessionId: record.sessionId,
|
|
348
|
+
label: record.label,
|
|
349
|
+
ageSeconds: Math.max(0, Math.floor(nowMs / 1000) - record.createdAt),
|
|
350
|
+
relays: Object.freeze([...record.relays]),
|
|
351
|
+
// What is left to decide: groups no sibling's approval notice has covered yet.
|
|
352
|
+
groupIds: Object.freeze(remainingGroups(record)),
|
|
353
|
+
expiresAt: record.expiresAt,
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/** Every request still awaiting this user's decision (prompted, unexpired, not approved anywhere yet), oldest first. */
|
|
357
|
+
export async function pendingEnrolments(deps) {
|
|
358
|
+
const nowMs = deps.clock.now();
|
|
359
|
+
const records = await deps.transaction(async (tx) => {
|
|
360
|
+
const view = tx.artifact(ARTIFACT);
|
|
361
|
+
const out = [];
|
|
362
|
+
for (const key of await view.keys()) {
|
|
363
|
+
if (!key.startsWith('in:'))
|
|
364
|
+
continue;
|
|
365
|
+
const record = await readInbound(view, key.slice(3));
|
|
366
|
+
if (record?.status === 'pending' && record.expiresAt * 1000 > nowMs)
|
|
367
|
+
out.push(record);
|
|
368
|
+
}
|
|
369
|
+
return out;
|
|
370
|
+
});
|
|
371
|
+
return Object.freeze(records.sort((a, b) => a.receivedAt - b.receivedAt || (a.requestId < b.requestId ? -1 : 1)).map((r) => promptOf(r, nowMs)));
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* The `RUMOR_KINDS.ENROLMENT_REQUEST` native handler (runs on the inbox
|
|
375
|
+
* queue; S7 demux slot). Never waits on a group operation.
|
|
376
|
+
*/
|
|
377
|
+
export async function handleEnrolmentRumor(deps, registry, rumor, ctx) {
|
|
378
|
+
const self = await deps.signer.getPublicKey();
|
|
379
|
+
// The seal proved `rumor.pubkey` wrote it: only the account itself enrols its devices.
|
|
380
|
+
if (rumor.pubkey !== self)
|
|
381
|
+
return { kind: 'rejected', reason: 'not-same-account' };
|
|
382
|
+
const decoded = decodeEnrolmentRumor(rumor);
|
|
383
|
+
if (decoded === undefined)
|
|
384
|
+
return { kind: 'rejected', reason: 'malformed-enrolment' };
|
|
385
|
+
const nowMs = deps.clock.now();
|
|
386
|
+
if (decoded.type === 'approved') {
|
|
387
|
+
// A sibling approved (part of) a request: the groups it reports are covered; the prompt closes here once
|
|
388
|
+
// every requested group is — a sibling holding only some of them leaves the rest to the others (C2).
|
|
389
|
+
// The device's label (from the request, if this client saw it) is bound.
|
|
390
|
+
await deps.transaction(async (tx) => {
|
|
391
|
+
const view = tx.artifact(ARTIFACT);
|
|
392
|
+
const current = await readInbound(view, decoded.requestId);
|
|
393
|
+
if (current === undefined) {
|
|
394
|
+
const marker = (await view.get(approvedKey(decoded.requestId)));
|
|
395
|
+
const groups = [...new Set([...(marker?.groups ?? []), ...decoded.groups])];
|
|
396
|
+
await view.put(approvedKey(decoded.requestId), { requestId: decoded.requestId, receivedAt: nowMs, groups });
|
|
397
|
+
}
|
|
398
|
+
else {
|
|
399
|
+
const approvedGroups = [...new Set([...(current.approvedGroups ?? []), ...decoded.groups])];
|
|
400
|
+
const next = { ...current, approvedGroups };
|
|
401
|
+
const covered = remainingGroups(next).length === 0;
|
|
402
|
+
await writeInbound(view, covered && (current.status === 'pending' || current.status === 'dropped') ? { ...next, status: 'closed' } : next);
|
|
403
|
+
// The notice names the key the device joined with; the request named the key its KeyPackages carried — one device
|
|
404
|
+
// when its lineage links them (it may have rotated in between).
|
|
405
|
+
if (current.leafKey === decoded.leafKey || (await loadDeviceLineage(tx.artifact(DEVICE_REGISTRY_ARTIFACT))).sameDevice(current.leafKey, decoded.leafKey)) {
|
|
406
|
+
await registry.bindLabel(tx, current.leafKey, current.label, nowMs);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
await ctx.markSeen(tx);
|
|
410
|
+
});
|
|
411
|
+
return { kind: 'recorded', rumorKind: rumor.kind, id: decoded.requestId };
|
|
412
|
+
}
|
|
413
|
+
const requestId = rumor.id;
|
|
414
|
+
const outcome = await deps.transaction(async (tx) => {
|
|
415
|
+
const view = tx.artifact(ARTIFACT);
|
|
416
|
+
await prune(view, nowMs);
|
|
417
|
+
let result;
|
|
418
|
+
// Groups siblings' approval notices (arrived before the request itself) already cover.
|
|
419
|
+
const approvedEarly = [...(((await view.get(approvedKey(requestId)))?.groups) ?? [])];
|
|
420
|
+
if ((await readOutbound(view, requestId)) !== undefined) {
|
|
421
|
+
result = { reason: 'own-request' };
|
|
422
|
+
}
|
|
423
|
+
else if ((await readInbound(view, requestId)) !== undefined) {
|
|
424
|
+
result = { reason: 'replayed' };
|
|
425
|
+
}
|
|
426
|
+
else if (decoded.groups.every((g) => approvedEarly.includes(g.groupId))) {
|
|
427
|
+
result = { reason: 'already-approved' };
|
|
428
|
+
}
|
|
429
|
+
else if (decoded.expiresAt * 1000 <= nowMs) {
|
|
430
|
+
result = { reason: 'expired' };
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
// AC-DEV-5: distinct requests of this session prompted within the last minute.
|
|
434
|
+
let recent = 0;
|
|
435
|
+
for (const key of await view.keys()) {
|
|
436
|
+
if (!key.startsWith('in:'))
|
|
437
|
+
continue;
|
|
438
|
+
const other = await readInbound(view, key.slice(3));
|
|
439
|
+
if (other !== undefined && other.sessionId === decoded.sessionId && other.status !== 'dropped' && other.receivedAt > nowMs - PROMPT_RATE_WINDOW_MS)
|
|
440
|
+
recent++;
|
|
441
|
+
}
|
|
442
|
+
const record = {
|
|
443
|
+
v: 1,
|
|
444
|
+
requestId,
|
|
445
|
+
sessionId: decoded.sessionId,
|
|
446
|
+
label: decoded.label,
|
|
447
|
+
createdAt: rumor.created_at,
|
|
448
|
+
expiresAt: decoded.expiresAt,
|
|
449
|
+
receivedAt: nowMs,
|
|
450
|
+
relays: [...ctx.relays],
|
|
451
|
+
leafKey: decoded.leafKey,
|
|
452
|
+
groups: decoded.groups,
|
|
453
|
+
status: recent >= deps.promptRateLimit ? 'dropped' : 'pending',
|
|
454
|
+
...(approvedEarly.length === 0 ? {} : { approvedGroups: approvedEarly }),
|
|
455
|
+
};
|
|
456
|
+
// A dropped request is still recorded: a later copy of it is a replay, never a prompt.
|
|
457
|
+
await writeInbound(view, record);
|
|
458
|
+
result = record.status === 'dropped' ? { reason: 'rate-limited' } : { prompt: record };
|
|
459
|
+
}
|
|
460
|
+
await ctx.markSeen(tx);
|
|
461
|
+
return result;
|
|
462
|
+
});
|
|
463
|
+
if ('reason' in outcome)
|
|
464
|
+
return { kind: 'rejected', reason: outcome.reason };
|
|
465
|
+
// After the record committed: the prompt of a request this client holds durably.
|
|
466
|
+
deps.onPrompt(promptOf(outcome.prompt, nowMs));
|
|
467
|
+
return { kind: 'recorded', rumorKind: rumor.kind, id: requestId };
|
|
468
|
+
}
|
|
469
|
+
function validateRequestOptions(raw) {
|
|
470
|
+
if (typeof raw !== 'object' || raw === null)
|
|
471
|
+
throw invalid('requestEnrolment', 'options must be an object', 'invalid-options');
|
|
472
|
+
const { label, groupIds, sessionId, expiresInMinutes } = raw;
|
|
473
|
+
if (typeof label !== 'string' || label.length === 0 || label.length > MAX_LABEL_LENGTH)
|
|
474
|
+
throw invalid('requestEnrolment', `label must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`, 'invalid-label');
|
|
475
|
+
if (!Array.isArray(groupIds) || groupIds.length === 0 || groupIds.length > MAX_ENROLMENT_GROUPS || !groupIds.every((g) => typeof g === 'string' && HEX.test(g))) {
|
|
476
|
+
throw invalid('requestEnrolment', `groupIds must be 1..${MAX_ENROLMENT_GROUPS} lower-case hex group ids`, 'invalid-groups');
|
|
477
|
+
}
|
|
478
|
+
if (new Set(groupIds).size !== groupIds.length)
|
|
479
|
+
throw invalid('requestEnrolment', 'groupIds must be distinct', 'invalid-groups');
|
|
480
|
+
if (sessionId !== undefined && (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > MAX_SESSION_ID_LENGTH)) {
|
|
481
|
+
throw invalid('requestEnrolment', `sessionId must be a non-empty string of at most ${MAX_SESSION_ID_LENGTH} characters`, 'invalid-session');
|
|
482
|
+
}
|
|
483
|
+
const minutes = expiresInMinutes ?? DEFAULT_ENROLMENT_EXPIRY_MINUTES;
|
|
484
|
+
if (typeof minutes !== 'number' || !Number.isInteger(minutes) || minutes < 1 || minutes > MAX_ENROLMENT_EXPIRY_MINUTES) {
|
|
485
|
+
throw invalid('requestEnrolment', `expiresInMinutes must be an integer in 1..${MAX_ENROLMENT_EXPIRY_MINUTES}`, 'invalid-expiry');
|
|
486
|
+
}
|
|
487
|
+
return { label, groupIds: groupIds, sessionId: sessionId, expiresInMinutes: minutes };
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Seals (if not yet) and publishes an outbound request's wrap to the
|
|
491
|
+
* account's inbox relays. `sent` once a relay accepted it; `pending`
|
|
492
|
+
* otherwise (the record keeps the wrap; later inbox passes re-publish it).
|
|
493
|
+
*/
|
|
494
|
+
async function publishOutbound(deps, requestId) {
|
|
495
|
+
const self = await deps.signer.getPublicKey();
|
|
496
|
+
let record = await deps.transaction((tx) => readOutbound(tx.artifact(ARTIFACT), requestId));
|
|
497
|
+
if (record === undefined || record.status !== 'pending')
|
|
498
|
+
return record?.status === 'sent' ? 'sent' : 'gone';
|
|
499
|
+
if (record.expiresAt * 1000 <= deps.clock.now())
|
|
500
|
+
return 'gone';
|
|
501
|
+
if (record.wrap === undefined) {
|
|
502
|
+
// Sealed outside any transaction (a remote signer may wait on its user); a wrap stored meanwhile wins.
|
|
503
|
+
const fresh = await giftWrap({ senderSigner: deps.signer, recipientPubkey: self, rumor: record.rumor });
|
|
504
|
+
record = await deps.transaction(async (tx) => {
|
|
505
|
+
const view = tx.artifact(ARTIFACT);
|
|
506
|
+
const current = await readOutbound(view, requestId);
|
|
507
|
+
if (current === undefined || current.wrap !== undefined)
|
|
508
|
+
return current;
|
|
509
|
+
const next = { ...current, wrap: fresh };
|
|
510
|
+
await view.put(outKey(requestId), next);
|
|
511
|
+
return next;
|
|
512
|
+
});
|
|
513
|
+
if (record === undefined)
|
|
514
|
+
return 'gone';
|
|
515
|
+
}
|
|
516
|
+
const wrap = record.wrap;
|
|
517
|
+
const resolution = await resolveInboxRelays(deps, self);
|
|
518
|
+
if (resolution.kind !== 'relays')
|
|
519
|
+
return 'pending';
|
|
520
|
+
let accepted = false;
|
|
521
|
+
try {
|
|
522
|
+
accepted = classifyPublish(resolution.relays, await deps.transport.publish([...resolution.relays], wrap)).outcome === 'accepted';
|
|
523
|
+
}
|
|
524
|
+
catch {
|
|
525
|
+
accepted = false; // a thrown network error is transient
|
|
526
|
+
}
|
|
527
|
+
if (!accepted)
|
|
528
|
+
return 'pending';
|
|
529
|
+
await deps.transaction(async (tx) => {
|
|
530
|
+
const view = tx.artifact(ARTIFACT);
|
|
531
|
+
const current = await readOutbound(view, requestId);
|
|
532
|
+
if (current?.wrap?.id !== wrap.id || current.status === 'sent')
|
|
533
|
+
return;
|
|
534
|
+
await view.put(outKey(requestId), { ...current, status: 'sent' });
|
|
535
|
+
});
|
|
536
|
+
return 'sent';
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* `devices.requestEnrolment(options)` on the new device. Resolves once the
|
|
540
|
+
* request reached a relay; rejects `publish-failed` (retryable — it is
|
|
541
|
+
* re-published by the device service's background retry and later inbox
|
|
542
|
+
* passes until it expires) when none accepted it.
|
|
543
|
+
*/
|
|
544
|
+
export async function requestEnrolment(deps, rawOptions) {
|
|
545
|
+
const options = validateRequestOptions(rawOptions);
|
|
546
|
+
const self = await deps.signer.getPublicKey();
|
|
547
|
+
const sessionId = options.sessionId ?? randomHex(16);
|
|
548
|
+
// X1: before anything is minted, published or stored — a request the gift wrap cannot carry is refused, sized
|
|
549
|
+
// with an upper-bound KeyPackage event per group (the relays its KeyPackages will name included).
|
|
550
|
+
const relays = await deps.keyPackageRelays();
|
|
551
|
+
const nowS = Math.floor(deps.clock.now() / 1000);
|
|
552
|
+
assertWrappable(encodeEnrolmentRequestRumor({
|
|
553
|
+
pubkey: self,
|
|
554
|
+
createdAt: nowS,
|
|
555
|
+
sessionId,
|
|
556
|
+
expiresAt: nowS + options.expiresInMinutes * 60,
|
|
557
|
+
label: options.label,
|
|
558
|
+
groups: options.groupIds.map((groupId) => ({ groupId, keyPackageEvent: keyPackageEventBound(self, relays) })),
|
|
559
|
+
}), 'requestEnrolment', deps.maxGiftWrapBytes ?? DEFAULT_MAX_GIFT_WRAP_BYTES);
|
|
560
|
+
// One fresh KeyPackage per group (a consumed init_key cannot serve a second group), through S4's lifecycle.
|
|
561
|
+
const groups = [];
|
|
562
|
+
for (const groupId of options.groupIds)
|
|
563
|
+
groups.push({ groupId, keyPackageEvent: await deps.createKeyPackage() });
|
|
564
|
+
const nowMs = deps.clock.now();
|
|
565
|
+
const createdAt = Math.floor(nowMs / 1000);
|
|
566
|
+
const expiresAt = createdAt + options.expiresInMinutes * 60;
|
|
567
|
+
const rumor = encodeEnrolmentRequestRumor({ pubkey: self, createdAt, sessionId, expiresAt, label: options.label, groups });
|
|
568
|
+
// Backstop with the real KeyPackages, before anything is stored (the bound above makes this unreachable in practice).
|
|
569
|
+
assertWrappable(rumor, 'requestEnrolment', deps.maxGiftWrapBytes ?? DEFAULT_MAX_GIFT_WRAP_BYTES);
|
|
570
|
+
const requestId = rumor.id;
|
|
571
|
+
const manifests = [];
|
|
572
|
+
for (const { groupId, keyPackageEvent } of groups) {
|
|
573
|
+
const keyPackageRef = await computeKeyPackageRefHex(getKeyPackage(keyPackageEvent));
|
|
574
|
+
manifests.push({ ...validateManifest({ groupId, keyPackageRef, sponsorAccount: self, deadline: expiresAt * 1000 }, nowMs), recordedAt: nowMs });
|
|
575
|
+
}
|
|
576
|
+
// ONE transaction, before anything is published: the outbound record (the only thing a background pass
|
|
577
|
+
// publishes, and how this device recognises its own request) and one manifest per group — only Welcomes of
|
|
578
|
+
// these groups, for these KeyPackages, from the account itself are joined (AC-DEV-6). A request is never
|
|
579
|
+
// publishable without its manifests. Written directly (S6's `recordManifest`, not `expectWelcome`): the
|
|
580
|
+
// KeyPackages were minted just now, so no Welcome for them can be pending, and `expectWelcome`'s wait for
|
|
581
|
+
// the inbox queue would make this step non-atomic.
|
|
582
|
+
await deps.transaction(async (tx) => {
|
|
583
|
+
for (const manifest of manifests)
|
|
584
|
+
await recordManifest(tx, manifest);
|
|
585
|
+
// S9 (AC-ADMIN-7): each KeyPackage is minted for its group — the group's `destroy()` publishes kind-5 for it.
|
|
586
|
+
for (const { groupId, keyPackageEvent } of groups)
|
|
587
|
+
await recordKeyPackageGroupRef(tx, { ref: keyPackageEvent.id, groupId, at: nowMs });
|
|
588
|
+
const record = { v: 1, requestId, sessionId, expiresAt, rumor, status: 'pending' };
|
|
589
|
+
await tx.artifact(ARTIFACT).put(outKey(requestId), record);
|
|
590
|
+
});
|
|
591
|
+
const sent = await publishOutbound(deps, requestId);
|
|
592
|
+
if (sent !== 'sent') {
|
|
593
|
+
throw new MarmotError('publish-failed', `devices.requestEnrolment: no inbox relay accepted request ${requestId}; it is re-published by later inbox passes until it expires`, {
|
|
594
|
+
details: { requestId, retryable: true },
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
return Object.freeze({ requestId, sessionId, expiresAt });
|
|
598
|
+
}
|
|
599
|
+
function outcomeOf(record) {
|
|
600
|
+
const perGroupOutcome = {};
|
|
601
|
+
for (const g of record.approval ?? record.groups.map((e) => ({ groupId: e.groupId, outcome: 'pending' })))
|
|
602
|
+
perGroupOutcome[g.groupId] = g.outcome;
|
|
603
|
+
return Object.freeze({
|
|
604
|
+
requestId: record.requestId,
|
|
605
|
+
leafKey: record.leafKey,
|
|
606
|
+
perGroupOutcome: Object.freeze(perGroupOutcome),
|
|
607
|
+
settled: Object.values(perGroupOutcome).every((o) => o !== 'pending'),
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
/** Re-reads the record and applies `change` when it is still `approving` (identity check inside the transaction). */
|
|
611
|
+
async function updateApproval(deps, requestId, change) {
|
|
612
|
+
return deps.transaction(async (tx) => {
|
|
613
|
+
const view = tx.artifact(ARTIFACT);
|
|
614
|
+
const current = await readInbound(view, requestId);
|
|
615
|
+
if (current?.status !== 'approving')
|
|
616
|
+
return current;
|
|
617
|
+
const next = change(current);
|
|
618
|
+
if (next === undefined)
|
|
619
|
+
return current;
|
|
620
|
+
await writeInbound(view, next);
|
|
621
|
+
return next;
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
function withGroup(record, groupId, patch) {
|
|
625
|
+
return { ...record, approval: (record.approval ?? []).map((g) => (g.groupId === groupId ? { ...g, ...patch } : g)) };
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* The device lineage an enrolment re-check compares by (epic marmot-device-key-rotation, AC-ENR-1): the registry's
|
|
629
|
+
* recorded links united with the canonical-path successions `snapshot` reports, so the comparison does not depend on
|
|
630
|
+
* whether a notification or the catch-up feed already wrote the link.
|
|
631
|
+
*/
|
|
632
|
+
async function enrolmentLineage(deps, snapshot, deviceKey, edges) {
|
|
633
|
+
const extra = edges ?? (await viewSuccessionEdges(deps.signer, [snapshot]));
|
|
634
|
+
// The live keys (held in the group, the own key, the device asked about) keep two installations that share an origin key
|
|
635
|
+
// apart (a contested component): the device is then its directed ancestry, never a sibling's live key.
|
|
636
|
+
const own = await readDeviceSigningKey((fn) => deps.transaction(fn));
|
|
637
|
+
const live = new Set([...(snapshot?.accountLeaves ?? []).map((l) => l.leafKey), ...(own === undefined ? [] : [own.leafKey]), ...(deviceKey === undefined ? [] : [deviceKey])]);
|
|
638
|
+
return deps.transaction(async (tx) => {
|
|
639
|
+
const view = tx.artifact(DEVICE_REGISTRY_ARTIFACT);
|
|
640
|
+
// The asked device's own forward heads count as live too (it may have rotated on and left the group, so none of its end
|
|
641
|
+
// keys is held): otherwise a sibling's single live head would not make the component contested.
|
|
642
|
+
if (deviceKey !== undefined)
|
|
643
|
+
for (const head of (await loadDeviceLineage(view, extra)).headsOf(deviceKey))
|
|
644
|
+
live.add(head);
|
|
645
|
+
return loadDeviceLineage(view, extra, live);
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* The key(s) an enrolment re-check hands the group port for the approval's device (AC-RM-3): the device's chain (the
|
|
650
|
+
* registry's recorded links united with `snapshot`'s successions), as the plain key when the device has only that one
|
|
651
|
+
* (single-key calls are unchanged) and as the set otherwise.
|
|
652
|
+
*/
|
|
653
|
+
async function deviceKeys(deps, snapshot, leafKey, edges) {
|
|
654
|
+
const chain = (await enrolmentLineage(deps, snapshot, leafKey, edges)).keysOf(leafKey);
|
|
655
|
+
return chain.length <= 1 ? leafKey : [...new Set([leafKey, ...chain])];
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* The group's own-account leaf that is the approval's device: the leaf carrying `leafKey` itself, else (a device that
|
|
659
|
+
* rotated since the request named its key) the leaf carrying another key of the same lineage. The registry is read
|
|
660
|
+
* only when no leaf carries `leafKey`.
|
|
661
|
+
*/
|
|
662
|
+
async function deviceLeaf(deps, snapshot, leafKey) {
|
|
663
|
+
const exact = snapshot.accountLeaves.find((l) => l.leafKey === leafKey);
|
|
664
|
+
if (exact !== undefined || snapshot.accountLeaves.length === 0)
|
|
665
|
+
return exact;
|
|
666
|
+
const lineage = await enrolmentLineage(deps, snapshot, leafKey);
|
|
667
|
+
return snapshot.accountLeaves.find((l) => lineage.sameDevice(l.leafKey, leafKey));
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* AC-RECHK-2/3: whether the approval's device has a departure NEWER than the approval — its registry tombstone or
|
|
671
|
+
* its `forget:<leafKey>` record, each judged on its OWN time (`tombstoneDepartureTime` / `forgetDepartureTime`),
|
|
672
|
+
* never merged into one value: a stale tombstone must not mask a newer, still-live forget record of the same leaf.
|
|
673
|
+
* A departure no newer than the approval (a forget that settled before the device re-enrolled with the same leaf
|
|
674
|
+
* key) does not count: this approval's finalize supersedes it. A record without `approvedAt` (written before the
|
|
675
|
+
* field existed) reads as the oldest possible approval, so any departure counts (never silently loosened).
|
|
676
|
+
*/
|
|
677
|
+
async function departedAfterApproval(tx, record, viewEdges = [], now = () => 0) {
|
|
678
|
+
const { times, approvedAt } = await departureTimes(tx, record, viewEdges, now);
|
|
679
|
+
return times.some((t) => t > approvedAt);
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* AC-RECHK-1/2: whether the approval's device has a departure record NO newer than the approval — a tombstone or
|
|
683
|
+
* forget record this approval's finalize supersedes — each record judged on its own time, like
|
|
684
|
+
* {@link departedAfterApproval}.
|
|
685
|
+
*/
|
|
686
|
+
async function hasSupersedableDeparture(tx, record, viewEdges = [], now = () => 0) {
|
|
687
|
+
const { times, approvedAt } = await departureTimes(tx, record, viewEdges, now);
|
|
688
|
+
return times.some((t) => t <= approvedAt);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Every departure time recorded for the approval's device, each judged on its own (never merged): the tombstone of the
|
|
692
|
+
* head entry and the forget record of every key of the device's lineage (a forget may have been started under an
|
|
693
|
+
* earlier key and the tombstone follows the head). A device that never rotated has the one pair it always had.
|
|
694
|
+
*/
|
|
695
|
+
async function departureTimes(tx, record, viewEdges, now) {
|
|
696
|
+
const registry = tx.artifact(DEVICE_REGISTRY_ARTIFACT);
|
|
697
|
+
// What the group's view showed is persisted first: the departure is located by the registry's lineage (one source).
|
|
698
|
+
await persistSuccessionEdges(tx, viewEdges, now);
|
|
699
|
+
const lineage = await loadDeviceLineage(registry);
|
|
700
|
+
const head = lineage.deviceHeadOf(record.leafKey);
|
|
701
|
+
const times = [];
|
|
702
|
+
const entry = (await registry.get(head));
|
|
703
|
+
const tombstoneTime = tombstoneDepartureTime(entry?.tombstone);
|
|
704
|
+
if (tombstoneTime !== undefined)
|
|
705
|
+
times.push(tombstoneTime);
|
|
706
|
+
for (const key of lineage.keysOf(head)) {
|
|
707
|
+
const forget = (await registry.get(`forget:${key}`));
|
|
708
|
+
const forgetTime = forgetDepartureTime(forget);
|
|
709
|
+
if (forgetTime !== undefined)
|
|
710
|
+
times.push(forgetTime);
|
|
711
|
+
}
|
|
712
|
+
return { times, approvedAt: record.approvedAt ?? 0 };
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* S10 (V1 revisable settlement): reopens `groupId` of `requestId`'s approval
|
|
716
|
+
* once its recorded `enrolled` outcome is contradicted by a rewind — the
|
|
717
|
+
* settled Add is no longer on the tree. The group returns to `outcome:
|
|
718
|
+
* 'pending', inflight: true` so the next drive counts the lost Add as one
|
|
719
|
+
* attempt, exactly like {@link driveApproval}'s existing C4 branch ("an
|
|
720
|
+
* attempt issued earlier settled without adding the device"), and an
|
|
721
|
+
* `approved` record returns to `approving` so re-finalizing emits
|
|
722
|
+
* `enrolmentApproved` again (the first one was a false success). A no-op when
|
|
723
|
+
* the record or the group's outcome no longer matches (already reopened, or
|
|
724
|
+
* settled some other way) — re-reads inside its own transaction, like
|
|
725
|
+
* {@link updateApproval}.
|
|
726
|
+
*/
|
|
727
|
+
async function reopenApprovalGroup(deps, requestId, groupId, viewEdges = []) {
|
|
728
|
+
return deps.transaction(async (tx) => {
|
|
729
|
+
const view = tx.artifact(ARTIFACT);
|
|
730
|
+
const current = await readInbound(view, requestId);
|
|
731
|
+
if (current === undefined || (current.status !== 'approving' && current.status !== 'approved'))
|
|
732
|
+
return false;
|
|
733
|
+
const group = (current.approval ?? []).find((g) => g.groupId === groupId);
|
|
734
|
+
if (group === undefined || group.outcome !== 'enrolled')
|
|
735
|
+
return false;
|
|
736
|
+
// S20 round 2 / S4 AC-RECHK-2: never for a device whose departure is NEWER than this approval — a rewind's
|
|
737
|
+
// withdrawn-leaf evidence can be older than a real departure, and re-adding over that would resurrect it
|
|
738
|
+
// (AC-INV-4). A departure no newer than the approval (devices.forget(leaf) settled, then the SAME device
|
|
739
|
+
// re-enrolled with the same unrotated leaf key, and THIS approval is for that re-enrolment) no longer
|
|
740
|
+
// describes the device sitting behind this approval: time-compare instead of refusing unconditionally.
|
|
741
|
+
if (await departedAfterApproval(tx, current, viewEdges, () => deps.clock.now()))
|
|
742
|
+
return false;
|
|
743
|
+
const approval = (current.approval ?? []).map((g) => (g.groupId === groupId ? { ...g, outcome: 'pending', inflight: true, reopened: true } : g));
|
|
744
|
+
await writeInbound(view, { ...current, status: 'approving', approval });
|
|
745
|
+
return true;
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* S10 (V1 revisable settlement): `DeviceGroupPort.onRewind`'s handler for
|
|
750
|
+
* enrolment approvals, called after `groupId` rewound off a branch it had
|
|
751
|
+
* applied. Every inbound approval whose status is `approving` or `approved`
|
|
752
|
+
* and whose recorded outcome for `groupId` was `enrolled` is re-checked
|
|
753
|
+
* against one fresh snapshot; a leaf the rewind withdrew is reopened
|
|
754
|
+
* ({@link reopenApprovalGroup}). See {@link RewindReopenResult}.
|
|
755
|
+
*/
|
|
756
|
+
export async function reopenApprovalsAfterRewind(deps, groupId, passWithdrawnLeaves) {
|
|
757
|
+
const snapshot = await deps.groups.snapshot(groupId);
|
|
758
|
+
if (snapshot === undefined)
|
|
759
|
+
return 'clear'; // no longer held: nothing here to reconsider
|
|
760
|
+
if (snapshot.syncing || snapshot.ownCommitPending)
|
|
761
|
+
return 'blocked';
|
|
762
|
+
// S20 follow-up (VQ-S20-P14): the withdrawn-leaf evidence is the marker as of THIS snapshot's tree (read on the
|
|
763
|
+
// group's queue with it), not the one the pass read before: transitions in between (a re-add, then an ordinary
|
|
764
|
+
// Remove) prune the stored evidence, and a stale copy would reopen — and re-add — a device that left. A snapshot
|
|
765
|
+
// from a port without the field keeps the pass's copy; no marker any more: another pass concluded it.
|
|
766
|
+
if ('recheck' in snapshot && snapshot.recheck === undefined)
|
|
767
|
+
return 'clear';
|
|
768
|
+
const withdrawnLeaves = 'recheck' in snapshot ? snapshot.recheck.withdrawnLeaves : passWithdrawnLeaves;
|
|
769
|
+
const candidates = await deps.transaction(async (tx) => {
|
|
770
|
+
const view = tx.artifact(ARTIFACT);
|
|
771
|
+
const out = [];
|
|
772
|
+
for (const key of await view.keys()) {
|
|
773
|
+
if (!key.startsWith('in:'))
|
|
774
|
+
continue;
|
|
775
|
+
const record = await readInbound(view, key.slice(3));
|
|
776
|
+
if (record === undefined || (record.status !== 'approving' && record.status !== 'approved'))
|
|
777
|
+
continue;
|
|
778
|
+
if ((record.approval ?? []).some((g) => g.groupId === groupId && g.outcome === 'enrolled'))
|
|
779
|
+
out.push({ requestId: record.requestId, leafKey: record.leafKey });
|
|
780
|
+
}
|
|
781
|
+
return out;
|
|
782
|
+
});
|
|
783
|
+
let reopened = false;
|
|
784
|
+
for (const { requestId, leafKey } of candidates) {
|
|
785
|
+
if ((await deviceLeaf(deps, snapshot, leafKey)) !== undefined)
|
|
786
|
+
continue; // still there (under this key or a successor): no contradiction
|
|
787
|
+
// S20: absent now is not enough — reopen only an Add a rewind WITHDREW (the leaf was on an abandoned state and
|
|
788
|
+
// on no state of the new canonical path). A leaf gone now because it LEFT on the canonical path (a self-forget, a
|
|
789
|
+
// Remove) must not be re-added: that would resurrect a departed device (AC-INV-4). The evidence is the marker's,
|
|
790
|
+
// decided when the rewind was persisted — re-deriving it now fails once the horizon pruned the abandoned states
|
|
791
|
+
// (a long catch-up after the rewind). A pre-S20 marker carries none: re-derived from the window, best effort.
|
|
792
|
+
if (withdrawnLeaves !== undefined) {
|
|
793
|
+
// The evidence is judged by the Add's OWN key (the request's): a withdrawn successor key (a rotation on an abandoned
|
|
794
|
+
// branch) says nothing about whether the Add stands, and a device that left canonically must not be re-added.
|
|
795
|
+
if (!withdrawnLeaves.includes(leafKey))
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
else {
|
|
799
|
+
const branches = await deps.groups.leafOnBranches?.(groupId, await deviceKeys(deps, snapshot, leafKey));
|
|
800
|
+
if (branches !== undefined && (branches.canonical || !branches.abandoned))
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
if (await reopenApprovalGroup(deps, requestId, groupId, await viewSuccessionEdges(deps.signer, [snapshot])))
|
|
804
|
+
reopened = true;
|
|
805
|
+
}
|
|
806
|
+
return reopened ? 'reopened' : 'clear';
|
|
807
|
+
}
|
|
808
|
+
/** A commit the pipeline dropped because every relay of the group refused it, or it exhausted its publish attempts. */
|
|
809
|
+
export function isRefusedCommit(error) {
|
|
810
|
+
if (!isMarmotError(error, 'send-rejected'))
|
|
811
|
+
return false;
|
|
812
|
+
const reason = error.details?.reason;
|
|
813
|
+
return reason === 'publish-refused' || reason === 'max-attempts';
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* `inviteIntent`'s AC-RECHK-1 refusal reason (client/pipeline.ts `MarmotError('invalid-options', ..., { details:
|
|
817
|
+
* { reason } })`) — exported so pipeline.ts throws the exact same literal `classifyGroupActFailure` pins below,
|
|
818
|
+
* rather than two independently-typed string literals that could silently drift apart.
|
|
819
|
+
*/
|
|
820
|
+
export const REOPENED_LEAF_STILL_CANONICAL = 'reopened-leaf-still-canonical';
|
|
821
|
+
export function classifyGroupActFailure(error) {
|
|
822
|
+
// AC-RECHK-1: pinned explicitly, independent of the blanket invalid-options branch below — retrying
|
|
823
|
+
// a reopened re-drive that `inviteIntent` refused because the leaf is still canonically present cannot help;
|
|
824
|
+
// the group's own accepted history does not change by trying again. Checked first so this specific
|
|
825
|
+
// classification is never accidentally altered by changes to the generic invalid-options rule.
|
|
826
|
+
if (isMarmotError(error, 'invalid-options') && error.details?.reason === REOPENED_LEAF_STILL_CANONICAL)
|
|
827
|
+
return 'permanent';
|
|
828
|
+
if (isMarmotError(error, 'invalid-options') || isRefusedCommit(error))
|
|
829
|
+
return 'permanent';
|
|
830
|
+
if (isMarmotError(error, 'commit-pending') || isMarmotError(error, 'confirm-blocked'))
|
|
831
|
+
return 'transient';
|
|
832
|
+
return maintenanceFailureReason(error) === undefined ? 'transient' : 'counted';
|
|
833
|
+
}
|
|
834
|
+
/** Errors after which a device intent stops (the next client or pass resumes it). */
|
|
835
|
+
export function stopsDeviceIntent(error) {
|
|
836
|
+
return isMarmotError(error, 'disposed') || isMarmotError(error, 'no-lease') || isMarmotError(error, 'reentrant');
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* One pass over an approval's pending groups; returns the outcome as stored
|
|
840
|
+
* afterwards. Group state decides each outcome, never the call that tried:
|
|
841
|
+
* a lost race, a crash or a terminal commit all read back the same way.
|
|
842
|
+
*/
|
|
843
|
+
async function driveApproval(deps, requestId) {
|
|
844
|
+
let record = await deps.transaction((tx) => readInbound(tx.artifact(ARTIFACT), requestId));
|
|
845
|
+
// A given-up approval has no pending group left (Y1): only its finalization remains.
|
|
846
|
+
if (record?.status !== 'approving' || record.gaveUp !== undefined)
|
|
847
|
+
return record;
|
|
848
|
+
for (const group of record.approval ?? []) {
|
|
849
|
+
if (group.outcome !== 'pending')
|
|
850
|
+
continue;
|
|
851
|
+
if (deps.isDisposed())
|
|
852
|
+
throw new MarmotError('disposed', 'devices.approveEnrolment: client has been disposed');
|
|
853
|
+
const entry = record.groups.find((g) => g.groupId === group.groupId);
|
|
854
|
+
const snapshot = await deps.groups.snapshot(group.groupId);
|
|
855
|
+
const snapshotEdges = await viewSuccessionEdges(deps.signer, [snapshot]);
|
|
856
|
+
let attempts = group.attempts;
|
|
857
|
+
let outcome;
|
|
858
|
+
if (snapshot === undefined || !snapshot.member)
|
|
859
|
+
outcome = 'not-a-member';
|
|
860
|
+
// A competing commit may still replace what the tree shows now (two siblings approving at once).
|
|
861
|
+
else if (snapshot.syncing)
|
|
862
|
+
outcome = 'wait';
|
|
863
|
+
else if ((await deviceLeaf(deps, snapshot, record.leafKey)) !== undefined)
|
|
864
|
+
outcome = 'enrolled';
|
|
865
|
+
// An issued commit still in the pipeline (being retried, or its confirmation blocked): its fate decides.
|
|
866
|
+
else if (snapshot.ownCommitPending)
|
|
867
|
+
outcome = 'wait';
|
|
868
|
+
else if (snapshot.accountLeaves.length >= MAX_LEAVES_PER_ACCOUNT)
|
|
869
|
+
outcome = 'limit-reached';
|
|
870
|
+
else
|
|
871
|
+
outcome = 'act';
|
|
872
|
+
// AC-RECHK-2/3: a departure newer than this approval (a `devices.forget` started after it — settled, or still
|
|
873
|
+
// `forgetting`) is a later decision than the approval: no Add re-admits the device, whether this group was
|
|
874
|
+
// reopened or never settled (it was waiting out a convergence window when the forget ran). The group concludes
|
|
875
|
+
// without an Add and finalize keeps the newer departure. A departure no newer than the approval (the device
|
|
876
|
+
// forgotten, then re-enrolled with the same leaf key) does not stop the Add: finalize supersedes it. Read here,
|
|
877
|
+
// on the device queue that also runs every forget, so no forget can start between this read and the Add.
|
|
878
|
+
if (outcome === 'act' && (await deps.transaction((tx) => departedAfterApproval(tx, record, snapshotEdges, () => deps.clock.now()))))
|
|
879
|
+
outcome = 'failed';
|
|
880
|
+
// An earlier attempt was issued and its fate was not observed: its Add may have landed — and a sibling may
|
|
881
|
+
// have removed the leaf again before any pass saw it. Such a retry is checked like a reopened re-drive
|
|
882
|
+
// (AC-RECHK-1, below), never a fresh unchecked Add.
|
|
883
|
+
const mayHaveLanded = group.inflight === true || group.retried === true;
|
|
884
|
+
if (outcome === 'act' && group.inflight === true) {
|
|
885
|
+
// C4: an attempt issued earlier has settled (nothing pending, nothing syncing) without adding the device —
|
|
886
|
+
// its commit went terminal after the call returned, or lost convergence. It counts, exactly once.
|
|
887
|
+
attempts += 1;
|
|
888
|
+
record = await updateApproval(deps, requestId, (r) => withGroup(r, group.groupId, { attempts, inflight: false, retried: true }));
|
|
889
|
+
if (record?.status !== 'approving')
|
|
890
|
+
return record;
|
|
891
|
+
}
|
|
892
|
+
if (outcome === 'act' && attempts >= MAX_GROUP_ATTEMPTS)
|
|
893
|
+
outcome = 'failed';
|
|
894
|
+
if (outcome === 'act') {
|
|
895
|
+
// AC-RECHK-1/2: an Add built over a departure this approval's finalize supersedes (a forget started before
|
|
896
|
+
// the approval, whose Remove may have landed after it) advances the group's epoch bound to the tip it is
|
|
897
|
+
// built on, so a reopened re-drive is never refused over that superseded forget's Remove or the states before
|
|
898
|
+
// it; a departure landing after this Add still refuses. A reopened re-drive, or a retry of an attempt that
|
|
899
|
+
// may have landed, never advances it (the bound of the Add it re-drives stands — advancing it past a sibling's
|
|
900
|
+
// Remove of that landed Add would void the check). The tip is read outside any store transaction.
|
|
901
|
+
let advanced;
|
|
902
|
+
if (group.reopened !== true && !mayHaveLanded && (await deps.transaction((tx) => hasSupersedableDeparture(tx, record, snapshotEdges, () => deps.clock.now())))) {
|
|
903
|
+
const tip = await deps.groups.groupEpoch(group.groupId);
|
|
904
|
+
if (tip !== undefined)
|
|
905
|
+
advanced = { approvalEpoch: tip };
|
|
906
|
+
}
|
|
907
|
+
// The device's key set for a checked Add (AC-RM-3), read BEFORE the attempt is recorded and outside the group act's
|
|
908
|
+
// `try`: a store or signer failure here is the pass's, never classified as a failed group act.
|
|
909
|
+
const checkedKeys = group.reopened === true || mayHaveLanded ? await deviceKeys(deps, snapshot, record.leafKey, snapshotEdges) : undefined;
|
|
910
|
+
// Persisted before the commit is issued: whatever becomes of it — now or asynchronously — is counted once.
|
|
911
|
+
record = await updateApproval(deps, requestId, (r) => withGroup(r, group.groupId, { inflight: true, ...advanced }));
|
|
912
|
+
if (record?.status !== 'approving')
|
|
913
|
+
return record;
|
|
914
|
+
const current = (record.approval ?? []).find((g) => g.groupId === group.groupId);
|
|
915
|
+
let failure;
|
|
916
|
+
try {
|
|
917
|
+
// S4 AC-RECHK-1: a reopened group's re-drive, and the retry of an attempt that may have landed, carry the
|
|
918
|
+
// leaf key (and the recorded approval epoch) through — a first Add never pays for the extra rewind-window
|
|
919
|
+
// walk inviteIntent does when this is set.
|
|
920
|
+
await deps.groups.addDevice(group.groupId, entry.keyPackageEvent, checkedKeys, checkedKeys === undefined ? undefined : current?.approvalEpoch, 'approval');
|
|
921
|
+
}
|
|
922
|
+
catch (error) {
|
|
923
|
+
if (stopsDeviceIntent(error))
|
|
924
|
+
throw error;
|
|
925
|
+
failure = classifyGroupActFailure(error);
|
|
926
|
+
}
|
|
927
|
+
const after = await deps.groups.snapshot(group.groupId);
|
|
928
|
+
if (after === undefined || !after.member)
|
|
929
|
+
outcome = 'not-a-member';
|
|
930
|
+
else if (after.syncing || after.ownCommitPending)
|
|
931
|
+
outcome = 'wait';
|
|
932
|
+
else if ((await deviceLeaf(deps, after, record.leafKey)) !== undefined)
|
|
933
|
+
outcome = 'enrolled';
|
|
934
|
+
else if (failure === 'permanent')
|
|
935
|
+
outcome = 'failed';
|
|
936
|
+
else if (failure === 'transient') {
|
|
937
|
+
// Refused before any commit existed (a signer timeout, the group busy): not an attempt.
|
|
938
|
+
record = await updateApproval(deps, requestId, (r) => withGroup(r, group.groupId, { inflight: false }));
|
|
939
|
+
if (record?.status !== 'approving')
|
|
940
|
+
return record;
|
|
941
|
+
outcome = 'wait';
|
|
942
|
+
}
|
|
943
|
+
else {
|
|
944
|
+
// The attempt ran and the device is still not in the group (a lost race, a commit that went terminal): counted.
|
|
945
|
+
attempts += 1;
|
|
946
|
+
record = await updateApproval(deps, requestId, (r) => withGroup(r, group.groupId, { attempts, inflight: false }));
|
|
947
|
+
if (record?.status !== 'approving')
|
|
948
|
+
return record;
|
|
949
|
+
outcome = attempts >= MAX_GROUP_ATTEMPTS ? 'failed' : 'wait';
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
if (outcome === 'wait')
|
|
953
|
+
continue;
|
|
954
|
+
const settled = outcome;
|
|
955
|
+
record = await updateApproval(deps, requestId, (r) => withGroup(r, group.groupId, { outcome: settled, inflight: false }));
|
|
956
|
+
if (record?.status !== 'approving')
|
|
957
|
+
return record;
|
|
958
|
+
}
|
|
959
|
+
return record;
|
|
960
|
+
}
|
|
961
|
+
/** Thrown inside the finalizing transaction when another path finalized first: nothing to emit. */
|
|
962
|
+
class AlreadyFinal extends Error {
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* Finalizes a settled approval: `approved`, the label bound to the device's
|
|
966
|
+
* leaf key, then `enrolmentApproved` after that transaction committed — only
|
|
967
|
+
* when the device holds a leaf of at least one requested group.
|
|
968
|
+
*/
|
|
969
|
+
async function finalizeApproval(deps, registry, requestId) {
|
|
970
|
+
const self = await deps.signer.getPublicKey();
|
|
971
|
+
const probe = await deps.transaction((tx) => readInbound(tx.artifact(ARTIFACT), requestId));
|
|
972
|
+
if (probe?.status !== 'approving')
|
|
973
|
+
return false;
|
|
974
|
+
// S10 (V1 revisable settlement): re-derive every `enrolled` group from a fresh snapshot before finalizing —
|
|
975
|
+
// a rewind since the drive pass that settled it may have withdrawn the Add. `syncing` / `ownCommitPending`
|
|
976
|
+
// defers the whole finalize to a later pass; a leaf no longer on the tree reopens the group (instead of
|
|
977
|
+
// finalizing a false success) and likewise defers.
|
|
978
|
+
// What the views showed of the device's lineage is persisted in the finalizing transaction before the label and the
|
|
979
|
+
// departure records are located by it.
|
|
980
|
+
const viewEdges = [];
|
|
981
|
+
for (const g of probe.approval ?? []) {
|
|
982
|
+
if (g.outcome !== 'enrolled')
|
|
983
|
+
continue;
|
|
984
|
+
const snapshot = await deps.groups.snapshot(g.groupId);
|
|
985
|
+
if (snapshot === undefined || !snapshot.member)
|
|
986
|
+
continue; // no longer held: nothing here to contradict
|
|
987
|
+
if (snapshot.syncing || snapshot.ownCommitPending)
|
|
988
|
+
return false;
|
|
989
|
+
const reported = await viewSuccessionEdges(deps.signer, [snapshot]);
|
|
990
|
+
viewEdges.push(...reported);
|
|
991
|
+
if ((await deviceLeaf(deps, snapshot, probe.leafKey)) === undefined) {
|
|
992
|
+
await reopenApprovalGroup(deps, requestId, g.groupId, reported);
|
|
993
|
+
return false;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
const enrolled = (probe.approval ?? []).filter((g) => g.outcome === 'enrolled').map((g) => g.groupId).sort();
|
|
997
|
+
// The new leaf's index in the first enrolled group (by group id): the payload names one leaf (AC-INBOX-6).
|
|
998
|
+
let leafIndex = -1;
|
|
999
|
+
// The key the device actually joined with (AC-ENR-3): the leaf's own, which a rotation since the request may have changed.
|
|
1000
|
+
let joinedKey = probe.leafKey;
|
|
1001
|
+
for (const groupId of enrolled) {
|
|
1002
|
+
const view = await deps.groups.snapshot(groupId);
|
|
1003
|
+
const leaf = view === undefined ? undefined : await deviceLeaf(deps, view, probe.leafKey);
|
|
1004
|
+
if (view !== undefined)
|
|
1005
|
+
viewEdges.push(...(await viewSuccessionEdges(deps.signer, [view])));
|
|
1006
|
+
if (leaf !== undefined) {
|
|
1007
|
+
leafIndex = leaf.leafIndex;
|
|
1008
|
+
joinedKey = leaf.leafKey;
|
|
1009
|
+
break;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
const commit = () => deps.transaction(async (tx) => {
|
|
1013
|
+
const view = tx.artifact(ARTIFACT);
|
|
1014
|
+
const current = await readInbound(view, requestId);
|
|
1015
|
+
if (current?.status !== 'approving' || (current.approval ?? []).some((g) => g.outcome === 'pending'))
|
|
1016
|
+
throw new AlreadyFinal();
|
|
1017
|
+
const next = { ...current, status: 'approved' };
|
|
1018
|
+
await writeInbound(view, next);
|
|
1019
|
+
if (enrolled.length > 0) {
|
|
1020
|
+
await persistSuccessionEdges(tx, viewEdges, () => deps.clock.now());
|
|
1021
|
+
await registry.bindLabel(tx, current.leafKey, current.label, deps.clock.now());
|
|
1022
|
+
// S4 AC-RECHK-2: the device is an active member again — a no-op when the leaf carries no departure
|
|
1023
|
+
// record, or only one newer than this approval (the overwhelmingly common case: an ordinary,
|
|
1024
|
+
// never-departed Add carries neither).
|
|
1025
|
+
await registry.supersedeDeparture(tx, current.leafKey, current.approvedAt ?? 0);
|
|
1026
|
+
}
|
|
1027
|
+
return next;
|
|
1028
|
+
});
|
|
1029
|
+
try {
|
|
1030
|
+
if (enrolled.length === 0)
|
|
1031
|
+
await commit();
|
|
1032
|
+
else
|
|
1033
|
+
await deps.lifecycle.afterCommit('enrolmentApproved', commit, () => ({ account: self, leafIndex, leafKey: joinedKey, groups: enrolled }));
|
|
1034
|
+
}
|
|
1035
|
+
catch (error) {
|
|
1036
|
+
if (error instanceof AlreadyFinal)
|
|
1037
|
+
return false;
|
|
1038
|
+
throw error;
|
|
1039
|
+
}
|
|
1040
|
+
if (enrolled.length > 0)
|
|
1041
|
+
await sendApprovalNotice(deps, requestId, probe.leafKey, enrolled);
|
|
1042
|
+
return true;
|
|
1043
|
+
}
|
|
1044
|
+
/** Best effort: tells the siblings (the account's own inbox) that `requestId` is approved, so their prompts close. */
|
|
1045
|
+
async function sendApprovalNotice(deps, requestId, leafKey, groups) {
|
|
1046
|
+
try {
|
|
1047
|
+
const self = await deps.signer.getPublicKey();
|
|
1048
|
+
const rumor = encodeEnrolmentApprovalRumor({ pubkey: self, createdAt: Math.floor(deps.clock.now() / 1000), requestId, leafKey, groups });
|
|
1049
|
+
const wrap = await giftWrap({ senderSigner: deps.signer, recipientPubkey: self, rumor });
|
|
1050
|
+
const resolution = await resolveInboxRelays(deps, self);
|
|
1051
|
+
if (resolution.kind === 'relays')
|
|
1052
|
+
await deps.transport.publish([...resolution.relays], wrap);
|
|
1053
|
+
}
|
|
1054
|
+
catch {
|
|
1055
|
+
// Advisory only: a sibling that misses it finds the device already enrolled if it approves too.
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* `devices.approveEnrolment(requestId)`: starts (or continues) the approval
|
|
1060
|
+
* and runs one pass over its groups. Resolves with the outcome as stored —
|
|
1061
|
+
* groups still `pending` are settled by later passes (their commits are the
|
|
1062
|
+
* pipeline's durable intents).
|
|
1063
|
+
*
|
|
1064
|
+
* Call it from application (UI) code, not from inside an inbox handler or
|
|
1065
|
+
* `onApplicationRumor`: those run in an account-scope consumer frame, which
|
|
1066
|
+
* the approval's `group.invite` inherits and rejects `reentrant` (ADR-013).
|
|
1067
|
+
*/
|
|
1068
|
+
export async function approveEnrolment(deps, registry, requestId) {
|
|
1069
|
+
if (typeof requestId !== 'string' || !HEX.test(requestId))
|
|
1070
|
+
throw invalid('approveEnrolment', 'requestId must be a lower-case hex request id', 'invalid-request-id');
|
|
1071
|
+
const self = await deps.signer.getPublicKey();
|
|
1072
|
+
// AC-RECHK-1: each requested group's tip epoch, read BEFORE the transaction below (a group
|
|
1073
|
+
// op — `deps.groups.groupEpoch` — is never made from inside a store transaction; device-registry.ts's own
|
|
1074
|
+
// module doc states the rule this mirrors). A group not (yet) held reads `undefined`; its record then carries
|
|
1075
|
+
// no `approvalEpoch`, falling back to the whole window, unbounded (the original, conservative behaviour).
|
|
1076
|
+
const probed = await deps.transaction((tx) => readInbound(tx.artifact(ARTIFACT), requestId));
|
|
1077
|
+
const epochs = new Map();
|
|
1078
|
+
if (probed?.status === 'pending') {
|
|
1079
|
+
for (const g of probed.groups) {
|
|
1080
|
+
const epoch = await deps.groups.groupEpoch(g.groupId);
|
|
1081
|
+
if (epoch !== undefined)
|
|
1082
|
+
epochs.set(g.groupId, epoch);
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
const started = await deps.transaction(async (tx) => {
|
|
1086
|
+
const view = tx.artifact(ARTIFACT);
|
|
1087
|
+
const current = await readInbound(view, requestId);
|
|
1088
|
+
// A dropped request was never prompted: it does not exist as far as the user is concerned.
|
|
1089
|
+
if (current === undefined || current.status === 'dropped')
|
|
1090
|
+
throw invalid('approveEnrolment', `no enrolment request ${requestId}`, 'not-found', { requestId });
|
|
1091
|
+
if (current.status !== 'pending')
|
|
1092
|
+
return current;
|
|
1093
|
+
if (current.expiresAt * 1000 <= deps.clock.now())
|
|
1094
|
+
throw invalid('approveEnrolment', `enrolment request ${requestId} has expired`, 'expired', { requestId });
|
|
1095
|
+
// AC-DEV-6: one manifest per requested group, recorded before any commit.
|
|
1096
|
+
const approval = [];
|
|
1097
|
+
for (const g of current.groups) {
|
|
1098
|
+
const approvalEpoch = epochs.get(g.groupId);
|
|
1099
|
+
approval.push({
|
|
1100
|
+
groupId: g.groupId,
|
|
1101
|
+
keyPackageRef: await computeKeyPackageRefHex(getKeyPackage(g.keyPackageEvent)),
|
|
1102
|
+
sponsorAccount: self,
|
|
1103
|
+
outcome: 'pending',
|
|
1104
|
+
attempts: 0,
|
|
1105
|
+
...(approvalEpoch === undefined ? {} : { approvalEpoch }),
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
const next = { ...current, status: 'approving', approval, approvedAt: deps.clock.now() };
|
|
1109
|
+
await writeInbound(view, next);
|
|
1110
|
+
return next;
|
|
1111
|
+
});
|
|
1112
|
+
if (started.status === 'closed')
|
|
1113
|
+
throw invalid('approveEnrolment', `enrolment request ${requestId} was already approved by another device`, 'already-approved', { requestId });
|
|
1114
|
+
if (started.status !== 'approving')
|
|
1115
|
+
return outcomeOf(started);
|
|
1116
|
+
const driven = await driveApproval(deps, requestId);
|
|
1117
|
+
if (driven !== undefined && driven.status === 'approving' && outcomeOf(driven).settled)
|
|
1118
|
+
await finalizeApproval(deps, registry, requestId);
|
|
1119
|
+
const final = await deps.transaction((tx) => readInbound(tx.artifact(ARTIFACT), requestId));
|
|
1120
|
+
return outcomeOf(final ?? driven ?? started);
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Background continuation (every inbox pass, and a timer while anything is
|
|
1124
|
+
* pending): every `approving` approval gets one more pass, and every unsent
|
|
1125
|
+
* own request is re-published. Resolves `true` while work is left.
|
|
1126
|
+
*/
|
|
1127
|
+
export async function resumeEnrolments(deps, registry) {
|
|
1128
|
+
const { approving, unsent } = await deps.transaction(async (tx) => {
|
|
1129
|
+
const view = tx.artifact(ARTIFACT);
|
|
1130
|
+
const a = [];
|
|
1131
|
+
const u = [];
|
|
1132
|
+
for (const key of await view.keys()) {
|
|
1133
|
+
if (key.startsWith('in:')) {
|
|
1134
|
+
const record = await readInbound(view, key.slice(3));
|
|
1135
|
+
// A given-up approval is not driven again, but still finalized (Y1) while it has not been.
|
|
1136
|
+
if (record?.status === 'approving')
|
|
1137
|
+
a.push(record.requestId);
|
|
1138
|
+
}
|
|
1139
|
+
else if (key.startsWith('out:')) {
|
|
1140
|
+
const record = await readOutbound(view, key.slice(4));
|
|
1141
|
+
if (record?.status === 'pending' && record.expiresAt * 1000 > deps.clock.now())
|
|
1142
|
+
u.push(record.requestId);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
return { approving: a, unsent: u };
|
|
1146
|
+
});
|
|
1147
|
+
let left = false;
|
|
1148
|
+
for (const requestId of approving) {
|
|
1149
|
+
try {
|
|
1150
|
+
const driven = await driveApproval(deps, requestId);
|
|
1151
|
+
// A deferred finalize (a group still syncing, a vanished leaf reopened) is work left: the timer retries it.
|
|
1152
|
+
if (driven?.status === 'approving' && outcomeOf(driven).settled) {
|
|
1153
|
+
if (!(await finalizeApproval(deps, registry, requestId)))
|
|
1154
|
+
left = true;
|
|
1155
|
+
}
|
|
1156
|
+
else if (driven?.status === 'approving')
|
|
1157
|
+
left = true;
|
|
1158
|
+
}
|
|
1159
|
+
catch (error) {
|
|
1160
|
+
if (stopsDeviceIntent(error))
|
|
1161
|
+
throw error;
|
|
1162
|
+
// W1: a pass that keeps failing (a snapshot, a record read) is counted like S6's maintenance. Y1: the
|
|
1163
|
+
// pass that gives it up finalizes it for the groups the device did join (a failure there: the next pass).
|
|
1164
|
+
if (!(await countFailure(deps, inKey(requestId), error, 'enrolment-approval', requestId)))
|
|
1165
|
+
left = true;
|
|
1166
|
+
else if (!(await finalizeApproval(deps, registry, requestId).catch(() => false)))
|
|
1167
|
+
left = true;
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
for (const requestId of unsent) {
|
|
1171
|
+
try {
|
|
1172
|
+
if ((await publishOutbound(deps, requestId)) === 'pending')
|
|
1173
|
+
left = true;
|
|
1174
|
+
}
|
|
1175
|
+
catch (error) {
|
|
1176
|
+
if (stopsDeviceIntent(error))
|
|
1177
|
+
throw error;
|
|
1178
|
+
// W1: a signer refusing to seal the request is asked at most MAX_MAINTENANCE_FAILURES times.
|
|
1179
|
+
if (!(await countFailure(deps, outKey(requestId), error, 'enrolment-request', requestId)))
|
|
1180
|
+
left = true;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
return left;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Counts one failed pass over the record at `key` (inbound approvals: `driverFailures` / `gaveUp`; outbound
|
|
1187
|
+
* requests: `failures` / status `failed`). A transient cause is not counted. `true` when this was the
|
|
1188
|
+
* {@link MAX_MAINTENANCE_FAILURES}th: the work is given up and `maintenanceFailed` fires after the write.
|
|
1189
|
+
*/
|
|
1190
|
+
async function countFailure(deps, key, error, kind, id) {
|
|
1191
|
+
const reason = maintenanceFailureReason(error);
|
|
1192
|
+
if (reason === undefined)
|
|
1193
|
+
return false;
|
|
1194
|
+
let enrolledGroups;
|
|
1195
|
+
const gaveUp = await deps.transaction(async (tx) => {
|
|
1196
|
+
const view = tx.artifact(ARTIFACT);
|
|
1197
|
+
const raw = (await view.get(key));
|
|
1198
|
+
if (raw === undefined)
|
|
1199
|
+
return false;
|
|
1200
|
+
if (key.startsWith('out:')) {
|
|
1201
|
+
if (raw['status'] !== 'pending')
|
|
1202
|
+
return false;
|
|
1203
|
+
const failures = (raw['failures'] ?? 0) + 1;
|
|
1204
|
+
const failed = failures >= MAX_MAINTENANCE_FAILURES;
|
|
1205
|
+
await view.put(key, { ...raw, failures, ...(failed ? { status: 'failed' } : {}) });
|
|
1206
|
+
return failed;
|
|
1207
|
+
}
|
|
1208
|
+
if (raw['status'] !== 'approving' || raw['gaveUp'] !== undefined)
|
|
1209
|
+
return false;
|
|
1210
|
+
const driverFailures = (raw['driverFailures'] ?? 0) + 1;
|
|
1211
|
+
if (driverFailures < MAX_MAINTENANCE_FAILURES) {
|
|
1212
|
+
await view.put(key, { ...raw, driverFailures });
|
|
1213
|
+
return false;
|
|
1214
|
+
}
|
|
1215
|
+
// Y1: given up — every group still pending is settled `failed` in this same write, so the approval can be
|
|
1216
|
+
// finalized for the groups the device did join.
|
|
1217
|
+
const record = raw;
|
|
1218
|
+
const approval = (record.approval ?? []).map((g) => (g.outcome === 'pending' ? { ...g, outcome: 'failed', inflight: false } : g));
|
|
1219
|
+
await writeInbound(view, { ...record, driverFailures, gaveUp: reason, approval });
|
|
1220
|
+
enrolledGroups = approval.filter((g) => g.outcome === 'enrolled').map((g) => g.groupId).sort();
|
|
1221
|
+
return true;
|
|
1222
|
+
});
|
|
1223
|
+
if (gaveUp)
|
|
1224
|
+
deps.onMaintenanceFailed({ invitationId: id, kind, reason, ...(enrolledGroups === undefined ? {} : { groups: enrolledGroups }) });
|
|
1225
|
+
return gaveUp;
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* The KeyPackage events of every request this client recorded for any key of `leafKey`'s lineage (a forget deletes
|
|
1229
|
+
* them); `chain` names further keys known to belong to the device (a forget's chain, which may include successions
|
|
1230
|
+
* only a group's view showed).
|
|
1231
|
+
*/
|
|
1232
|
+
export async function requestedKeyPackages(deps, leafKey, chain = []) {
|
|
1233
|
+
return deps.transaction(async (tx) => {
|
|
1234
|
+
const lineage = await loadDeviceLineage(tx.artifact(DEVICE_REGISTRY_ARTIFACT));
|
|
1235
|
+
const keys = new Set([...lineage.keysOf(leafKey), ...chain]);
|
|
1236
|
+
const view = tx.artifact(ARTIFACT);
|
|
1237
|
+
const out = [];
|
|
1238
|
+
for (const key of await view.keys()) {
|
|
1239
|
+
if (!key.startsWith('in:'))
|
|
1240
|
+
continue;
|
|
1241
|
+
const record = await readInbound(view, key.slice(3));
|
|
1242
|
+
if (record !== undefined && keys.has(record.leafKey))
|
|
1243
|
+
out.push(...record.groups.map((g) => g.keyPackageEvent));
|
|
1244
|
+
}
|
|
1245
|
+
return out;
|
|
1246
|
+
});
|
|
1247
|
+
}
|