@941design/marmot 0.0.0-stage → 0.2.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +709 -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 +127 -0
- package/dist/account/teardown.js +856 -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 +180 -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 +68 -0
- package/dist/client/commit-redrive.js +221 -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 +50 -0
- package/dist/client/confirm-hooks.js +59 -0
- package/dist/client/create-client.d.ts +1022 -0
- package/dist/client/create-client.js +1125 -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 +435 -0
- package/dist/client/group-history.js +1295 -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 +485 -0
- package/dist/client/group-records.js +1034 -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 +388 -0
- package/dist/client/group-runtime.js +2701 -0
- package/dist/client/group-snapshot.d.ts +98 -0
- package/dist/client/group-snapshot.js +453 -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 +21 -0
- package/dist/client/index.js +13 -0
- package/dist/client/ingest.d.ts +82 -0
- package/dist/client/ingest.js +1550 -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 +81 -0
- package/dist/client/opaque-candidates.js +169 -0
- package/dist/client/own-change-outbox.d.ts +66 -0
- package/dist/client/own-change-outbox.js +156 -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 +554 -0
- package/dist/client/pipeline.js +3545 -0
- package/dist/client/reentrancy-guard.d.ts +96 -0
- package/dist/client/reentrancy-guard.js +153 -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/equivocation.d.ts +55 -0
- package/dist/history/equivocation.js +113 -0
- package/dist/history/fencing.d.ts +25 -0
- package/dist/history/fencing.js +61 -0
- package/dist/history/hex.d.ts +3 -0
- package/dist/history/hex.js +10 -0
- package/dist/history/index.d.ts +73 -0
- package/dist/history/index.js +31 -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 +106 -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 +61 -0
- package/dist/invitations/decline.js +143 -0
- package/dist/invitations/expect-welcome.d.ts +66 -0
- package/dist/invitations/expect-welcome.js +138 -0
- package/dist/invitations/index.d.ts +16 -0
- package/dist/invitations/index.js +16 -0
- package/dist/invitations/invite.d.ts +303 -0
- package/dist/invitations/invite.js +966 -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 +253 -0
- package/dist/invitations/welcome-processor.js +1180 -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 +21 -0
- package/dist/shared/errors.js +85 -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 +227 -0
- package/dist/storage/index.js +459 -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 +41 -0
- package/dist/storage/lease.js +117 -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,827 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `client.devices.rotateKey()` — the durable multi-group device-key rotation (epic marmot-device-key-rotation, S7;
|
|
3
|
+
* Design Decisions 3, 5, 6, 8 and 10).
|
|
4
|
+
*
|
|
5
|
+
* A rotation is driven like `devices.forget`: ONE account transaction (`prepareDeviceKeyRotation`, S4) flips
|
|
6
|
+
* `deviceRegistry/self` to a fresh key, records the `rotation:<id>` intent with the whole held-group list, writes the
|
|
7
|
+
* `rotated:` links and re-binds the registry entry; everything after it is reconciliation of "every member group's own
|
|
8
|
+
* leaf carries `self`'s key", which tolerates a crash anywhere (a group still on an older key keeps working):
|
|
9
|
+
*
|
|
10
|
+
* - per group, a pass reads the group back (`DeviceGroupView.ownLeaf.leafKey === target`), issues
|
|
11
|
+
* `DeviceGroupPort.rekey` for a group that still needs it (the pipeline records and drives the `rekey` self-update)
|
|
12
|
+
* and settles the group `rekeyed` / `satisfied` / `removed` / `timed-out` / `cancelled`; the state decides each
|
|
13
|
+
* outcome, never the call that tried. An attempt that ran and left the key unchanged is counted, at most
|
|
14
|
+
* {@link MAX_GROUP_ATTEMPTS} of them (the forget's `inflight` rule: counted exactly once, when it settled with the
|
|
15
|
+
* key still old); a group that is fenced when its attempt starts is `timed-out` at once;
|
|
16
|
+
* - KeyPackages follow the key (`retireKeyPackagesSignedWith`, replacement first, kind-5 after): a slot whose relay
|
|
17
|
+
* refuses even the idempotent re-publish is `relay-unreachable` and does not hold the rotation back;
|
|
18
|
+
* - once every group is terminal and the KeyPackage step is finished ONE transaction records the rotation `settled`
|
|
19
|
+
* (`gave-up` when some group `timed-out`) and `deviceKeyRotationSettled` fires after it, once.
|
|
20
|
+
*
|
|
21
|
+
* `forget` beats rotation: while ANY record of the local device's own forget exists (open, settled or given up)
|
|
22
|
+
* `rotateKey()` rejects `invalid-options` (`device-forgetting`), and an open rotation cancels its not-yet-terminal groups
|
|
23
|
+
* when an own forget is open or started since (leaving beats re-keying).
|
|
24
|
+
*
|
|
25
|
+
* The resume-time sweep (AC-ROT-11) is independent of any rotation record: every held member group whose own leaf key
|
|
26
|
+
* is a retired key of THIS device (one `self` descends from along the recorded links, i.e. directed ancestry) gets a `rekey` toward `self` (no new key, no signer call). It is the
|
|
27
|
+
* backstop for what the client's own follow-up skips (another own commit pending) and for a group created on the old key
|
|
28
|
+
* across a prepare.
|
|
29
|
+
*
|
|
30
|
+
* Everything runs on the device service's serial queue and inside its DEVICE_SCOPE frame (the service wires it); no
|
|
31
|
+
* signer, relay or group call is made inside a store transaction.
|
|
32
|
+
*/
|
|
33
|
+
import { prepareDeviceKeyRotation, readAllDeviceKeyRotations, readDeviceKeyLink, readDeviceKeyRotation, readDeviceSigningKey, RESUME_BACKOFF_MS, writeDeviceKeyRotation } from '../key-packages/index.js';
|
|
34
|
+
import { maintenanceFailureReason } from '../inbox/index.js';
|
|
35
|
+
import { isMarmotError, MarmotError } from '../shared/index.js';
|
|
36
|
+
import { DEVICE_REGISTRY_ARTIFACT, MAX_MAINTENANCE_FAILURES } from './device-deps.js';
|
|
37
|
+
import { directedAncestors, readRegistryEdges, recordSuccession } from './device-lineage.js';
|
|
38
|
+
import { MAX_GROUP_ATTEMPTS, stopsDeviceIntent } from './enrolment.js';
|
|
39
|
+
import { clearRestoreRotationOwed, putRestoreRotationOwed, readRestoreRotationsOwed, RESTORE_ROTATION_EXTENSION } from './restore-rotation.js';
|
|
40
|
+
const ARTIFACT = DEVICE_REGISTRY_ARTIFACT;
|
|
41
|
+
/** Groups of one rotation driven at the same time. Each group's own queue serialises its operations; this bounds the load. */
|
|
42
|
+
export const ROTATION_CONCURRENCY = 4;
|
|
43
|
+
/**
|
|
44
|
+
* Blocked KeyPackage retirements counted before the step is given up (the rotation settles without it). A block is counted at
|
|
45
|
+
* most once per {@link RESUME_BACKOFF_MS} window: passes are started by `devices.list()`, every inbox pass and every rewind, and a
|
|
46
|
+
* publish the publisher itself retries at most once per window must not burn the budget in between.
|
|
47
|
+
*/
|
|
48
|
+
export const MAX_KEYPACKAGE_ATTEMPTS = MAX_MAINTENANCE_FAILURES;
|
|
49
|
+
/** Failed rechecks of the KeyPackage retirement a service instance repeats (each may prompt the signer). */
|
|
50
|
+
export const MAX_RECHECK_FAILURES = 3;
|
|
51
|
+
/**
|
|
52
|
+
* How long a group may stay undecided (a convergence window, an own commit pending, a refusal that is not an attempt such as
|
|
53
|
+
* `commit-pending`, a read that fails transiently) before it is `timed-out`. A deadline, not a pass count: passes are started
|
|
54
|
+
* by many callers and their number says nothing about elapsed time. Kept per service instance (a restart restarts it).
|
|
55
|
+
*/
|
|
56
|
+
export const ROTATION_WAIT_DEADLINE_MS = 10 * 60_000;
|
|
57
|
+
function stepOf(record) {
|
|
58
|
+
const raw = record.keyPackages;
|
|
59
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
60
|
+
return { status: 'pending', attempts: 0, blocked: [] };
|
|
61
|
+
const r = raw;
|
|
62
|
+
const status = r.status === 'done' || r.status === 'gave-up' || r.status === 'cancelled' ? r.status : 'pending';
|
|
63
|
+
const blocked = Array.isArray(r.blocked)
|
|
64
|
+
? r.blocked.filter((b) => typeof b === 'object' && b !== null && typeof b.dSlot === 'string' && typeof b.reason === 'string')
|
|
65
|
+
: [];
|
|
66
|
+
const lastCountedAt = r.lastCountedAt;
|
|
67
|
+
return { status, attempts: typeof r.attempts === 'number' ? r.attempts : 0, ...(typeof lastCountedAt === 'number' ? { lastCountedAt } : {}), ...(r.thrown === true ? { thrown: true } : {}), blocked };
|
|
68
|
+
}
|
|
69
|
+
function withStep(record, step) {
|
|
70
|
+
return { ...record, keyPackages: step };
|
|
71
|
+
}
|
|
72
|
+
function withGroup(record, groupId, patch) {
|
|
73
|
+
return {
|
|
74
|
+
...record,
|
|
75
|
+
groups: record.groups.map((g) => {
|
|
76
|
+
if (g.groupId !== groupId)
|
|
77
|
+
return g;
|
|
78
|
+
const next = { ...g, ...patch };
|
|
79
|
+
for (const key of Object.keys(next))
|
|
80
|
+
if (next[key] === undefined)
|
|
81
|
+
delete next[key]; // the store holds no undefined
|
|
82
|
+
return next;
|
|
83
|
+
}),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function perGroup(record) {
|
|
87
|
+
const out = {};
|
|
88
|
+
for (const g of record.groups)
|
|
89
|
+
out[g.groupId] = g.outcome;
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
export function rotationOutcomeOf(record) {
|
|
93
|
+
return Object.freeze({
|
|
94
|
+
rotationId: record.id,
|
|
95
|
+
from: Object.freeze([...record.from]),
|
|
96
|
+
to: record.to,
|
|
97
|
+
perGroupOutcome: Object.freeze(perGroup(record)),
|
|
98
|
+
settled: record.status !== 'rotating',
|
|
99
|
+
status: record.status === 'rotating' ? 'rotating' : record.status === 'gave-up' ? 'gave-up' : 'rotated',
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function reasonOf(error) {
|
|
103
|
+
return (isMarmotError(error) ? error.details?.reason : undefined);
|
|
104
|
+
}
|
|
105
|
+
function classifyRekeyFailure(error) {
|
|
106
|
+
// A fenced group accepts no further sends: nothing to retry, nothing to burn.
|
|
107
|
+
if (isMarmotError(error, 'fenced'))
|
|
108
|
+
return 'fenced';
|
|
109
|
+
if (isMarmotError(error, 'not-a-member'))
|
|
110
|
+
return 'not-member';
|
|
111
|
+
if (isMarmotError(error, 'send-rejected')) {
|
|
112
|
+
const reason = reasonOf(error);
|
|
113
|
+
if (reason === 'superseded')
|
|
114
|
+
return 'superseded'; // the target is no longer the device key: a newer rotation owns the group
|
|
115
|
+
if (reason === 'already-rekeyed')
|
|
116
|
+
return 'transient'; // the read-back concludes it
|
|
117
|
+
if (reason === 'proof-invalid')
|
|
118
|
+
return 'permanent'; // the stored proof cannot be accepted: retrying cannot help
|
|
119
|
+
return 'counted'; // publish-refused, max-attempts, ...
|
|
120
|
+
}
|
|
121
|
+
if (isMarmotError(error, 'invalid-options'))
|
|
122
|
+
return 'permanent';
|
|
123
|
+
if (isMarmotError(error, 'publish-failed'))
|
|
124
|
+
return 'retained';
|
|
125
|
+
if (isMarmotError(error, 'commit-pending') || isMarmotError(error, 'confirm-blocked'))
|
|
126
|
+
return 'transient';
|
|
127
|
+
return maintenanceFailureReason(error) === undefined ? 'transient' : 'counted';
|
|
128
|
+
}
|
|
129
|
+
/** The group's state decides what is left to do (the read-back every outcome rests on). */
|
|
130
|
+
function judge(view, target) {
|
|
131
|
+
if (view === undefined || !view.member)
|
|
132
|
+
return 'removed';
|
|
133
|
+
const carries = view.ownLeaf !== undefined ? view.ownLeaf.leafKey === target : view.accountLeaves.some((l) => l.leafKey === target);
|
|
134
|
+
// A competing commit may still replace the state read here (and a rewind withdraw the rotation commit): no conclusion yet.
|
|
135
|
+
if (view.syncing)
|
|
136
|
+
return 'wait';
|
|
137
|
+
if (carries)
|
|
138
|
+
return 'done';
|
|
139
|
+
if (view.ownCommitPending)
|
|
140
|
+
return 'wait';
|
|
141
|
+
return 'act';
|
|
142
|
+
}
|
|
143
|
+
class AlreadyFinal extends Error {
|
|
144
|
+
}
|
|
145
|
+
async function pool(items, limit, fn) {
|
|
146
|
+
let next = 0;
|
|
147
|
+
let failure;
|
|
148
|
+
const worker = async () => {
|
|
149
|
+
for (;;) {
|
|
150
|
+
if (failure !== undefined)
|
|
151
|
+
return;
|
|
152
|
+
const index = next++;
|
|
153
|
+
if (index >= items.length)
|
|
154
|
+
return;
|
|
155
|
+
try {
|
|
156
|
+
await fn(items[index]);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
failure ??= { error };
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
165
|
+
if (failure !== undefined)
|
|
166
|
+
throw failure.error;
|
|
167
|
+
}
|
|
168
|
+
// ---------------------------------------------------------------------------
|
|
169
|
+
// The driver
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
export function createRotationDriver(deps, seams) {
|
|
172
|
+
/**
|
|
173
|
+
* Groups seen carrying `self`'s key, by `key@epoch` (a mark is stale once `self` changes, the group's epoch moved - a Welcome
|
|
174
|
+
* adoption, a competing-Welcome switch, a restore or any commit - or a rewind/notification names the group).
|
|
175
|
+
*/
|
|
176
|
+
const verified = new Map();
|
|
177
|
+
/** Groups (by `group|target`) the sweep was refused on: asked again only after `until` (client clock ms), further out with every failure. */
|
|
178
|
+
const refused = new Map();
|
|
179
|
+
/**
|
|
180
|
+
* When each pending group (by `rotation|group`) first stayed undecided, in THIS service instance only: the time a process was
|
|
181
|
+
* down or asleep is not time the group was undecided, so a restart starts the clock again.
|
|
182
|
+
*/
|
|
183
|
+
const waits = new Map();
|
|
184
|
+
/** The one-time re-run of the KeyPackage retirement at the first resume pass of this service (a settled rotation's leftovers). */
|
|
185
|
+
let keyPackagesRechecked = false;
|
|
186
|
+
/** A failed recheck is asked again no sooner than this (client clock ms), and at most {@link MAX_RECHECK_FAILURES} times per service. */
|
|
187
|
+
let recheckNotBefore = 0;
|
|
188
|
+
let recheckFailures = 0;
|
|
189
|
+
const read = (id) => deps.transaction((tx) => readDeviceKeyRotation(tx.artifact(ARTIFACT), id));
|
|
190
|
+
/** Applies `change` to the rotation while it is open (`rotating`); a closed or missing record is returned as is. */
|
|
191
|
+
async function update(id, change) {
|
|
192
|
+
return deps.transaction(async (tx) => {
|
|
193
|
+
const view = tx.artifact(ARTIFACT);
|
|
194
|
+
const current = (await readDeviceKeyRotation(view, id));
|
|
195
|
+
if (current?.status !== 'rotating')
|
|
196
|
+
return current;
|
|
197
|
+
const next = change(current);
|
|
198
|
+
if (next === undefined)
|
|
199
|
+
return current;
|
|
200
|
+
await writeDeviceKeyRotation(view, next);
|
|
201
|
+
return next;
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The prepare transaction wrote the links itself; this applies the rest of `recordSuccession` (alternate evidence for a key
|
|
206
|
+
* that already led elsewhere, entry consolidation). Idempotent, and it heals a crash before it ran. A key whose link is
|
|
207
|
+
* absent is left alone: the prepare writes every link atomically with the record, so an absent one was removed from the
|
|
208
|
+
* store on purpose and is not this pass's to write back.
|
|
209
|
+
*/
|
|
210
|
+
async function recordOwnSuccessions(record) {
|
|
211
|
+
if (record.from.length === 0)
|
|
212
|
+
return;
|
|
213
|
+
const at = deps.clock.now();
|
|
214
|
+
await deps.transaction(async (tx) => {
|
|
215
|
+
const view = tx.artifact(ARTIFACT);
|
|
216
|
+
for (const from of record.from) {
|
|
217
|
+
if ((await readDeviceKeyLink(view, from)) === undefined)
|
|
218
|
+
continue;
|
|
219
|
+
await recordSuccession(tx, { from, to: record.to, groupId: record.id, commitDigest: '', at, source: 'own' });
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
// -- the rotation ----------------------------------------------------------
|
|
224
|
+
async function readViews() {
|
|
225
|
+
const views = [];
|
|
226
|
+
for (const groupId of [...(await deps.groups.heldGroups())].sort()) {
|
|
227
|
+
const view = await deps.groups.snapshot(groupId);
|
|
228
|
+
if (view !== undefined)
|
|
229
|
+
views.push(view);
|
|
230
|
+
}
|
|
231
|
+
return views;
|
|
232
|
+
}
|
|
233
|
+
async function rotateKey() {
|
|
234
|
+
const ports = deps.rotation;
|
|
235
|
+
if (ports === undefined || deps.groups.rekey === undefined) {
|
|
236
|
+
throw new MarmotError('invalid-options', 'devices.rotateKey: this client cannot rotate the device key (no group rekey port)', { details: { reason: 'rotation-unavailable' } });
|
|
237
|
+
}
|
|
238
|
+
// Leaving beats re-keying (Decision 8, AC-ROT-5): any own forget record refuses it, before anything changes.
|
|
239
|
+
if (await seams.ownForget({ any: true })) {
|
|
240
|
+
throw new MarmotError('invalid-options', 'devices.rotateKey: the local device is being forgotten', { details: { reason: 'device-forgetting' } });
|
|
241
|
+
}
|
|
242
|
+
// A rotation already open is the answer (no second key): it is driven once more, like the first pass of a new one.
|
|
243
|
+
const open = await openRotation();
|
|
244
|
+
if (open !== undefined) {
|
|
245
|
+
await drive(open.id);
|
|
246
|
+
return rotationOutcomeOf((await read(open.id)) ?? open);
|
|
247
|
+
}
|
|
248
|
+
const views = await readViews();
|
|
249
|
+
const self = await readDeviceSigningKey((fn) => deps.transaction(fn));
|
|
250
|
+
const members = views.filter((v) => v.member);
|
|
251
|
+
if (self === undefined && members.length === 0) {
|
|
252
|
+
throw new MarmotError('invalid-options', 'devices.rotateKey: this client has no device key and holds no group to re-key', { details: { reason: 'no-device-key' } });
|
|
253
|
+
}
|
|
254
|
+
// Any other key an own leaf carries (a restore, an older retired key) is replaced too: its leaf is re-keyed to the target.
|
|
255
|
+
const replacedKeys = [...new Set(members.flatMap((v) => (v.ownLeaf === undefined || v.ownLeaf.leafKey === self?.leafKey ? [] : [v.ownLeaf.leafKey])))];
|
|
256
|
+
const accountPubkey = await deps.signer.getPublicKey();
|
|
257
|
+
const impl = await ports.ciphersuiteImpl();
|
|
258
|
+
const groups = members.map((v) => v.groupId);
|
|
259
|
+
const prepared = await deps.lifecycle.afterCommit('deviceKeyRotated', () => prepareDeviceKeyRotation({
|
|
260
|
+
transaction: (fn) => deps.transaction(fn),
|
|
261
|
+
impl,
|
|
262
|
+
signEvent: async (template) => deps.signer.signEvent(template),
|
|
263
|
+
accountPubkey,
|
|
264
|
+
groups,
|
|
265
|
+
nowMs: deps.clock.now(),
|
|
266
|
+
replacedKeys,
|
|
267
|
+
}), ({ rotation }) => ({ rotationId: rotation.id, from: rotation.from, to: rotation.to, groups: rotation.groups.map((g) => g.groupId) }));
|
|
268
|
+
await recordOwnSuccessions(prepared.rotation);
|
|
269
|
+
await drive(prepared.rotation.id);
|
|
270
|
+
return rotationOutcomeOf((await read(prepared.rotation.id)) ?? prepared.rotation);
|
|
271
|
+
}
|
|
272
|
+
async function openRotation() {
|
|
273
|
+
const all = (await deps.transaction((tx) => readAllDeviceKeyRotations(tx.artifact(ARTIFACT))));
|
|
274
|
+
return all.filter((r) => r.status === 'rotating').at(-1);
|
|
275
|
+
}
|
|
276
|
+
async function rotation() {
|
|
277
|
+
const { all, self } = await deps.transaction(async (tx) => ({
|
|
278
|
+
all: await readAllDeviceKeyRotations(tx.artifact(ARTIFACT)),
|
|
279
|
+
self: await readDeviceSigningKey(async (fn) => fn(tx)),
|
|
280
|
+
}));
|
|
281
|
+
const open = all.filter((r) => r.status === 'rotating').at(-1);
|
|
282
|
+
// The last one is the rotation that made the current device key (records started in the same millisecond tie on time).
|
|
283
|
+
const last = open ?? all.filter((r) => r.to === self?.leafKey).at(-1) ?? all.at(-1);
|
|
284
|
+
return last === undefined ? undefined : rotationOutcomeOf(last);
|
|
285
|
+
}
|
|
286
|
+
/** One pass over an open rotation; resolves with whether it is still open afterwards. */
|
|
287
|
+
async function drive(id) {
|
|
288
|
+
let record = await read(id);
|
|
289
|
+
if (record?.status !== 'rotating')
|
|
290
|
+
return false;
|
|
291
|
+
// The link prepare wrote is complete; the rest of the lineage bookkeeping is idempotent and heals a crash before it ran.
|
|
292
|
+
await recordOwnSuccessions(record);
|
|
293
|
+
if (await seams.ownForget({ since: record.startedAt })) {
|
|
294
|
+
await cancel(id);
|
|
295
|
+
await trySettle(id);
|
|
296
|
+
return (await read(id))?.status === 'rotating';
|
|
297
|
+
}
|
|
298
|
+
const failures = [];
|
|
299
|
+
await pool(record.groups.filter((g) => g.outcome === 'pending').map((g) => g.groupId), ROTATION_CONCURRENCY, async (groupId) => {
|
|
300
|
+
try {
|
|
301
|
+
await driveGroup(id, groupId);
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
if (stopsDeviceIntent(error))
|
|
305
|
+
throw error;
|
|
306
|
+
failures.push(error); // this group stays pending: the next pass reads it again
|
|
307
|
+
// An explicitly transient failure is not counted anywhere else: the deadline bounds it.
|
|
308
|
+
if (maintenanceFailureReason(error) === undefined) {
|
|
309
|
+
try {
|
|
310
|
+
await stall(id, groupId);
|
|
311
|
+
}
|
|
312
|
+
catch (stallError) {
|
|
313
|
+
if (stopsDeviceIntent(stallError))
|
|
314
|
+
throw stallError;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
const counted = failures.find((e) => maintenanceFailureReason(e) !== undefined);
|
|
320
|
+
if (counted !== undefined)
|
|
321
|
+
await countPassFailure(id, counted);
|
|
322
|
+
record = await read(id);
|
|
323
|
+
if (record?.status !== 'rotating')
|
|
324
|
+
return false;
|
|
325
|
+
await keyPackageStep(id);
|
|
326
|
+
await trySettle(id);
|
|
327
|
+
return (await read(id))?.status === 'rotating';
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* A group that stayed undecided in this pass: remembers since when (in memory, per service instance; a clock that moved back
|
|
331
|
+
* restarts it) and ends it `timed-out` once it has been undecided for {@link ROTATION_WAIT_DEADLINE_MS}. Issuing a re-key,
|
|
332
|
+
* a counted attempt and any conclusion reset the clock.
|
|
333
|
+
*/
|
|
334
|
+
async function stall(id, groupId, patch = {}) {
|
|
335
|
+
const now = deps.clock.now();
|
|
336
|
+
const key = `${id}|${groupId}`;
|
|
337
|
+
let since = waits.get(key) ?? now;
|
|
338
|
+
if (now < since)
|
|
339
|
+
since = now;
|
|
340
|
+
waits.set(key, since);
|
|
341
|
+
const expired = now - since >= ROTATION_WAIT_DEADLINE_MS;
|
|
342
|
+
if (expired) {
|
|
343
|
+
waits.delete(key);
|
|
344
|
+
await settleGroup(id, groupId, 'timed-out');
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
if (Object.keys(patch).length > 0)
|
|
348
|
+
await update(id, (r) => (r.groups.find((x) => x.groupId === groupId)?.outcome === 'pending' ? withGroup(r, groupId, patch) : undefined));
|
|
349
|
+
}
|
|
350
|
+
/** One pending group of the rotation, one pass (state decides each outcome, never the call that tried). */
|
|
351
|
+
async function driveGroup(id, groupId) {
|
|
352
|
+
seams.assertLive('rotateKey');
|
|
353
|
+
let record = await read(id);
|
|
354
|
+
if (record?.status !== 'rotating')
|
|
355
|
+
return;
|
|
356
|
+
const group = record.groups.find((g) => g.groupId === groupId);
|
|
357
|
+
if (group === undefined || group.outcome !== 'pending')
|
|
358
|
+
return;
|
|
359
|
+
const target = record.to;
|
|
360
|
+
let issued = false;
|
|
361
|
+
let failure;
|
|
362
|
+
let attempts = group.attempts;
|
|
363
|
+
let verdict = judge(await deps.groups.snapshot(groupId), target);
|
|
364
|
+
if (verdict === 'wait') {
|
|
365
|
+
// A commit of ours in the pipeline is bounded by the pipeline itself; only a group undecided for another reason is on the clock.
|
|
366
|
+
if (group.inflight === true)
|
|
367
|
+
waits.delete(`${id}|${groupId}`);
|
|
368
|
+
else
|
|
369
|
+
await stall(id, groupId);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (verdict === 'act') {
|
|
373
|
+
if (group.inflight === true) {
|
|
374
|
+
// An earlier re-key settled without moving the key (terminal after the call returned, or a lost race): it counts, once.
|
|
375
|
+
attempts += 1;
|
|
376
|
+
waits.delete(`${id}|${groupId}`);
|
|
377
|
+
record = await update(id, (r) => withGroup(r, groupId, { attempts, inflight: false }));
|
|
378
|
+
if (record?.status !== 'rotating')
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (attempts >= MAX_GROUP_ATTEMPTS) {
|
|
382
|
+
await settleGroup(id, groupId, 'timed-out');
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
// Persisted before the commit is issued (see DeviceKeyRotationGroup.inflight).
|
|
386
|
+
record = await update(id, (r) => withGroup(r, groupId, { inflight: true }));
|
|
387
|
+
if (record?.status !== 'rotating')
|
|
388
|
+
return;
|
|
389
|
+
try {
|
|
390
|
+
await deps.groups.rekey(groupId, target);
|
|
391
|
+
issued = true;
|
|
392
|
+
waits.delete(`${id}|${groupId}`); // a re-key was issued: progress
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
if (stopsDeviceIntent(error))
|
|
396
|
+
throw error;
|
|
397
|
+
failure = classifyRekeyFailure(error);
|
|
398
|
+
issued = failure === 'transient' || failure === 'retained' || failure === 'counted';
|
|
399
|
+
if (failure === 'retained' || failure === 'counted')
|
|
400
|
+
waits.delete(`${id}|${groupId}`); // the commit exists
|
|
401
|
+
}
|
|
402
|
+
verdict = judge(await deps.groups.snapshot(groupId), target);
|
|
403
|
+
if (verdict === 'act') {
|
|
404
|
+
// The state still says "not re-keyed" and nothing is in flight: the attempt ran (or was refused) and left the key.
|
|
405
|
+
if (failure === 'fenced' || failure === 'permanent' || failure === 'not-member') {
|
|
406
|
+
await settleGroup(id, groupId, 'timed-out');
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
if (failure === 'superseded') {
|
|
410
|
+
await settleGroup(id, groupId, 'cancelled');
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
if (failure === 'transient') {
|
|
414
|
+
// Refused before any commit existed (another own commit, a first sync still to come): not an attempt.
|
|
415
|
+
await stall(id, groupId, { inflight: false });
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
attempts += 1;
|
|
419
|
+
waits.delete(`${id}|${groupId}`);
|
|
420
|
+
record = await update(id, (r) => withGroup(r, groupId, { attempts, inflight: false }));
|
|
421
|
+
if (record?.status !== 'rotating')
|
|
422
|
+
return;
|
|
423
|
+
if (attempts >= MAX_GROUP_ATTEMPTS)
|
|
424
|
+
await settleGroup(id, groupId, 'timed-out');
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (verdict === 'wait') {
|
|
429
|
+
// A refusal that created no commit leaves nothing in flight and is on the clock; a commit in the pipeline stays `inflight`
|
|
430
|
+
// and is bounded by the pipeline.
|
|
431
|
+
if (failure === 'transient')
|
|
432
|
+
await stall(id, groupId, { inflight: false });
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (verdict === 'removed')
|
|
436
|
+
await settleGroup(id, groupId, 'removed');
|
|
437
|
+
else if (verdict === 'done')
|
|
438
|
+
await settleGroup(id, groupId, group.inflight === true || attempts > 0 || issued ? 'rekeyed' : 'satisfied');
|
|
439
|
+
}
|
|
440
|
+
async function settleGroup(id, groupId, outcome) {
|
|
441
|
+
waits.delete(`${id}|${groupId}`);
|
|
442
|
+
await update(id, (r) => {
|
|
443
|
+
const g = r.groups.find((x) => x.groupId === groupId);
|
|
444
|
+
if (g === undefined || g.outcome !== 'pending')
|
|
445
|
+
return undefined;
|
|
446
|
+
return withGroup(r, groupId, { outcome, inflight: false });
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
// -- the KeyPackage step ---------------------------------------------------
|
|
450
|
+
/** Every retired key of this device: what the rotation replaced and the directed ancestry of its target in the registry. */
|
|
451
|
+
async function retiredKeys(record) {
|
|
452
|
+
const edges = await deps.transaction((tx) => readRegistryEdges(tx.artifact(ARTIFACT)));
|
|
453
|
+
return [...new Set([...record.from, ...directedAncestors(record.to, edges)])].filter((k) => k !== record.to).sort();
|
|
454
|
+
}
|
|
455
|
+
async function keyPackageStep(id) {
|
|
456
|
+
const record = await read(id);
|
|
457
|
+
if (record?.status !== 'rotating' || stepOf(record).status !== 'pending')
|
|
458
|
+
return;
|
|
459
|
+
const ports = deps.rotation;
|
|
460
|
+
const keys = ports === undefined ? [] : await retiredKeys(record);
|
|
461
|
+
if (ports === undefined || keys.length === 0) {
|
|
462
|
+
await update(id, (r) => withStep(r, { status: 'done', attempts: stepOf(r).attempts, blocked: [] }));
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
seams.assertLive('rotateKey');
|
|
466
|
+
// A retirement that threw (the signer refused) is not repeated by every polling pass: each call prompts the signer again.
|
|
467
|
+
const before = stepOf(record);
|
|
468
|
+
if (before.thrown === true && before.lastCountedAt !== undefined && deps.clock.now() - before.lastCountedAt < RESUME_BACKOFF_MS)
|
|
469
|
+
return;
|
|
470
|
+
let blocked;
|
|
471
|
+
try {
|
|
472
|
+
blocked = (await ports.retireKeyPackages(keys)).blocked;
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
if (stopsDeviceIntent(error))
|
|
476
|
+
throw error;
|
|
477
|
+
// An explicitly transient cause is retried uncounted; anything else counts toward giving the step up.
|
|
478
|
+
if (maintenanceFailureReason(error) === undefined)
|
|
479
|
+
return;
|
|
480
|
+
await countKeyPackageAttempt(id, [], maintenanceFailureReason(error), true);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const retryable = blocked.filter((b) => b.reason !== 'relay-unreachable');
|
|
484
|
+
if (retryable.length === 0) {
|
|
485
|
+
// Finished, or blocked only on slots whose relays refuse even the re-publish: recorded for a later retry (the first resume pass).
|
|
486
|
+
await update(id, (r) => withStep(r, { status: 'done', attempts: stepOf(r).attempts, blocked }));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
await countKeyPackageAttempt(id, blocked, retryable[0].reason);
|
|
490
|
+
}
|
|
491
|
+
async function countKeyPackageAttempt(id, blocked, reason, thrown = false) {
|
|
492
|
+
let gaveUp = false;
|
|
493
|
+
const now = deps.clock.now();
|
|
494
|
+
await update(id, (r) => {
|
|
495
|
+
const step = stepOf(r);
|
|
496
|
+
if (step.status !== 'pending')
|
|
497
|
+
return undefined;
|
|
498
|
+
// Counted at most once per window: the publisher retries a pending publish no more often, so the passes in between add nothing.
|
|
499
|
+
const counts = step.lastCountedAt === undefined || now - step.lastCountedAt >= RESUME_BACKOFF_MS;
|
|
500
|
+
const attempts = step.attempts + (counts ? 1 : 0);
|
|
501
|
+
gaveUp = attempts >= MAX_KEYPACKAGE_ATTEMPTS;
|
|
502
|
+
return withStep(r, { status: gaveUp ? 'gave-up' : 'pending', attempts, lastCountedAt: counts ? now : step.lastCountedAt, ...(thrown ? { thrown: true } : {}), blocked });
|
|
503
|
+
});
|
|
504
|
+
if (gaveUp)
|
|
505
|
+
deps.onMaintenanceFailed({ invitationId: id, kind: 'device-rotation', reason: `keypackage-retirement:${reason}` });
|
|
506
|
+
}
|
|
507
|
+
// -- settlement, cancellation, give-up -----------------------------------------
|
|
508
|
+
/** The forget of the local device began: every not-yet-terminal group and the KeyPackage step are cancelled. */
|
|
509
|
+
async function cancel(id) {
|
|
510
|
+
await update(id, (r) => {
|
|
511
|
+
const step = stepOf(r);
|
|
512
|
+
const groups = r.groups.map((g) => (g.outcome === 'pending' ? { ...g, outcome: 'cancelled', inflight: false } : g));
|
|
513
|
+
return withStep({ ...r, groups, cancelled: { at: deps.clock.now() } }, { ...step, status: step.status === 'pending' ? 'cancelled' : step.status });
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Closes the rotation once every group is terminal and the KeyPackage step finished: each group recorded `rekeyed` /
|
|
518
|
+
* `satisfied` / `removed` is re-derived from a fresh snapshot first (a rewind since may have withdrawn the commit, or
|
|
519
|
+
* brought a removed leaf back): a contradicted group is reopened and the pass stays open.
|
|
520
|
+
*/
|
|
521
|
+
async function trySettle(id) {
|
|
522
|
+
const probe = await read(id);
|
|
523
|
+
if (probe?.status !== 'rotating' || probe.groups.some((g) => g.outcome === 'pending') || stepOf(probe).status === 'pending')
|
|
524
|
+
return false;
|
|
525
|
+
for (const group of probe.groups) {
|
|
526
|
+
if (group.outcome === 'timed-out') {
|
|
527
|
+
// A commit may have landed after the group was given up: the read-back is the truth.
|
|
528
|
+
let late;
|
|
529
|
+
try {
|
|
530
|
+
late = await deps.groups.snapshot(group.groupId);
|
|
531
|
+
}
|
|
532
|
+
catch (error) {
|
|
533
|
+
if (stopsDeviceIntent(error))
|
|
534
|
+
throw error;
|
|
535
|
+
continue; // a group that cannot be read stays as it was recorded
|
|
536
|
+
}
|
|
537
|
+
if (late !== undefined && late.member && judge(late, probe.to) === 'done') {
|
|
538
|
+
await update(id, (r) => withGroup(r, group.groupId, { outcome: 'rekeyed', inflight: false }));
|
|
539
|
+
}
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
if (group.outcome !== 'rekeyed' && group.outcome !== 'satisfied' && group.outcome !== 'removed')
|
|
543
|
+
continue;
|
|
544
|
+
const view = await deps.groups.snapshot(group.groupId);
|
|
545
|
+
if (view === undefined || !view.member)
|
|
546
|
+
continue; // not held / removed: nothing to contradict (a removed group stays removed)
|
|
547
|
+
const verdict = judge(view, probe.to);
|
|
548
|
+
if (verdict === 'done' && group.outcome !== 'removed')
|
|
549
|
+
continue;
|
|
550
|
+
if (verdict === 'wait')
|
|
551
|
+
return false; // converging: concluded by a later pass
|
|
552
|
+
// The state contradicts the recorded outcome: reopen the group.
|
|
553
|
+
await update(id, (r) => withGroup(r, group.groupId, { outcome: 'pending', inflight: false }));
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
return close(id, 'settled');
|
|
557
|
+
}
|
|
558
|
+
async function close(id, mode, reason) {
|
|
559
|
+
try {
|
|
560
|
+
await deps.lifecycle.afterCommit('deviceKeyRotationSettled', () => deps.transaction(async (tx) => {
|
|
561
|
+
const view = tx.artifact(ARTIFACT);
|
|
562
|
+
const current = (await readDeviceKeyRotation(view, id));
|
|
563
|
+
if (current?.status !== 'rotating')
|
|
564
|
+
throw new AlreadyFinal();
|
|
565
|
+
let next = current;
|
|
566
|
+
if (mode === 'gave-up') {
|
|
567
|
+
const step = stepOf(current);
|
|
568
|
+
next = withStep({ ...current, groups: current.groups.map((g) => (g.outcome === 'pending' ? { ...g, outcome: 'timed-out', inflight: false } : g)), gaveUp: reason ?? 'unknown-error' }, { ...step, status: step.status === 'pending' ? 'gave-up' : step.status });
|
|
569
|
+
}
|
|
570
|
+
else if (current.groups.some((g) => g.outcome === 'pending') || stepOf(current).status === 'pending') {
|
|
571
|
+
throw new AlreadyFinal();
|
|
572
|
+
}
|
|
573
|
+
const status = mode === 'gave-up' || next.groups.some((g) => g.outcome === 'timed-out') ? 'gave-up' : 'settled';
|
|
574
|
+
await writeDeviceKeyRotation(view, { ...next, status });
|
|
575
|
+
return perGroup(next);
|
|
576
|
+
}), (outcomes) => ({ rotationId: id, perGroupOutcome: outcomes }));
|
|
577
|
+
}
|
|
578
|
+
catch (error) {
|
|
579
|
+
if (!(error instanceof AlreadyFinal))
|
|
580
|
+
throw error;
|
|
581
|
+
return false;
|
|
582
|
+
}
|
|
583
|
+
return true;
|
|
584
|
+
}
|
|
585
|
+
/** Counts a failed pass over the rotation; the 10th gives it up (groups still pending become `timed-out`) and `maintenanceFailed` fires. */
|
|
586
|
+
async function countPassFailure(id, error) {
|
|
587
|
+
const reason = maintenanceFailureReason(error);
|
|
588
|
+
if (reason === undefined)
|
|
589
|
+
return;
|
|
590
|
+
let failed = false;
|
|
591
|
+
await update(id, (r) => {
|
|
592
|
+
const driverFailures = (r.driverFailures ?? 0) + 1;
|
|
593
|
+
failed = driverFailures >= MAX_MAINTENANCE_FAILURES;
|
|
594
|
+
return { ...r, driverFailures };
|
|
595
|
+
});
|
|
596
|
+
if (!failed)
|
|
597
|
+
return;
|
|
598
|
+
await close(id, 'gave-up', reason);
|
|
599
|
+
deps.onMaintenanceFailed({ invitationId: id, kind: 'device-rotation', reason });
|
|
600
|
+
}
|
|
601
|
+
// -- owed rotations after a restore (owner decision 13) -------------------------
|
|
602
|
+
/**
|
|
603
|
+
* Drains the rotations successful restores owe (restore-rotation.ts). A restored group whose own leaf carries a key
|
|
604
|
+
* `self` already descends from needs none — the sweep below re-keys it toward `self` without a new key (one rotation
|
|
605
|
+
* per batch of restores: the first one's prepare retires the backed-up key, every later restore of it lands here). A
|
|
606
|
+
* leaf on any other key (the backed-up key is still `self`, or another device's backup) owes `rotateKey()`, which joins
|
|
607
|
+
* a rotation already open. Leaving beats re-keying: an own forget drops the markers. A rotation that fails for a
|
|
608
|
+
* counted cause keeps the markers for the next pass and gives them up after `MAX_MAINTENANCE_FAILURES`
|
|
609
|
+
* (`maintenanceFailed` `device-rotation`, reason `restore-rotation`); the restore itself has long succeeded.
|
|
610
|
+
* Returns whether markers are left.
|
|
611
|
+
*/
|
|
612
|
+
async function drainRestoreRotations() {
|
|
613
|
+
const owed = await deps.transaction(async (tx) => readRestoreRotationsOwed(tx.extension(RESTORE_ROTATION_EXTENSION)));
|
|
614
|
+
if (owed.size === 0)
|
|
615
|
+
return false;
|
|
616
|
+
const clear = (groupIds) => deps.transaction(async (tx) => {
|
|
617
|
+
for (const groupId of groupIds)
|
|
618
|
+
await clearRestoreRotationOwed(tx.extension(RESTORE_ROTATION_EXTENSION), groupId);
|
|
619
|
+
});
|
|
620
|
+
if (deps.rotation === undefined || deps.groups.rekey === undefined || (await seams.ownForget({ any: true }))) {
|
|
621
|
+
await clear(owed.keys());
|
|
622
|
+
return false;
|
|
623
|
+
}
|
|
624
|
+
const { self, edges } = await deps.transaction(async (tx) => ({
|
|
625
|
+
self: await readDeviceSigningKey(async (fn) => fn(tx)),
|
|
626
|
+
edges: await readRegistryEdges(tx.artifact(ARTIFACT)),
|
|
627
|
+
}));
|
|
628
|
+
const retired = self === undefined ? new Set() : directedAncestors(self.leafKey, edges);
|
|
629
|
+
const settled = [];
|
|
630
|
+
let needed = false;
|
|
631
|
+
for (const groupId of owed.keys()) {
|
|
632
|
+
const view = await deps.groups.snapshot(groupId);
|
|
633
|
+
const key = view?.member === true ? view.ownLeaf?.leafKey : undefined;
|
|
634
|
+
// Gone, removed, or on a key this device already retired (the sweep re-keys it): nothing owed.
|
|
635
|
+
if (key === undefined || retired.has(key))
|
|
636
|
+
settled.push(groupId);
|
|
637
|
+
else
|
|
638
|
+
needed = true;
|
|
639
|
+
}
|
|
640
|
+
if (settled.length > 0)
|
|
641
|
+
await clear(settled);
|
|
642
|
+
if (!needed)
|
|
643
|
+
return false;
|
|
644
|
+
let outcome;
|
|
645
|
+
try {
|
|
646
|
+
outcome = await rotateKey();
|
|
647
|
+
}
|
|
648
|
+
catch (error) {
|
|
649
|
+
if (stopsDeviceIntent(error))
|
|
650
|
+
throw error;
|
|
651
|
+
const reason = maintenanceFailureReason(error);
|
|
652
|
+
const left = [...owed].filter(([groupId]) => !settled.includes(groupId));
|
|
653
|
+
if (reason === undefined)
|
|
654
|
+
return true; // transient: retried by the next pass, uncounted
|
|
655
|
+
let gaveUp = false;
|
|
656
|
+
await deps.transaction(async (tx) => {
|
|
657
|
+
const view = tx.extension(RESTORE_ROTATION_EXTENSION);
|
|
658
|
+
for (const [groupId, entry] of left) {
|
|
659
|
+
const failures = entry.failures + 1;
|
|
660
|
+
if (failures >= MAX_MAINTENANCE_FAILURES) {
|
|
661
|
+
gaveUp = true;
|
|
662
|
+
await clearRestoreRotationOwed(view, groupId);
|
|
663
|
+
}
|
|
664
|
+
else
|
|
665
|
+
await putRestoreRotationOwed(view, groupId, { ...entry, failures });
|
|
666
|
+
}
|
|
667
|
+
});
|
|
668
|
+
if (gaveUp)
|
|
669
|
+
deps.onMaintenanceFailed({ invitationId: 'restore-rotation', kind: 'device-rotation', reason, groups: left.map(([groupId]) => groupId) });
|
|
670
|
+
return !gaveUp;
|
|
671
|
+
}
|
|
672
|
+
// A rotation the prepare began now re-keys every held member group, the restored ones among them. One that was already
|
|
673
|
+
// open covers only its own groups: a restored group outside it keeps its marker, and the next pass (once that rotation
|
|
674
|
+
// settled, or a fresh one) rotates for it.
|
|
675
|
+
const covered = [...owed.keys()].filter((groupId) => !settled.includes(groupId) && groupId in outcome.perGroupOutcome);
|
|
676
|
+
const done = [...covered];
|
|
677
|
+
if (done.length > 0)
|
|
678
|
+
await clear(done);
|
|
679
|
+
return done.length < owed.size - settled.length;
|
|
680
|
+
}
|
|
681
|
+
// -- the resume pass -----------------------------------------------------------
|
|
682
|
+
async function resume() {
|
|
683
|
+
const owedLeft = await drainRestoreRotations();
|
|
684
|
+
const state = await deps.transaction(async (tx) => {
|
|
685
|
+
const view = tx.artifact(ARTIFACT);
|
|
686
|
+
const self = await readDeviceSigningKey(async (fn) => fn(tx));
|
|
687
|
+
const rotations = (await readAllDeviceKeyRotations(view));
|
|
688
|
+
const edges = await readRegistryEdges(view);
|
|
689
|
+
return { self, rotations, edges };
|
|
690
|
+
});
|
|
691
|
+
let left = false;
|
|
692
|
+
const open = state.rotations.filter((r) => r.status === 'rotating').at(-1);
|
|
693
|
+
const driven = new Set();
|
|
694
|
+
if (open !== undefined) {
|
|
695
|
+
for (const g of open.groups)
|
|
696
|
+
driven.add(g.groupId);
|
|
697
|
+
try {
|
|
698
|
+
left = await drive(open.id);
|
|
699
|
+
}
|
|
700
|
+
catch (error) {
|
|
701
|
+
if (stopsDeviceIntent(error))
|
|
702
|
+
throw error;
|
|
703
|
+
// A pass that keeps failing (a record that no longer reads, a store that keeps failing) is counted like the forget's.
|
|
704
|
+
await countPassFailure(open.id, error).catch(() => undefined);
|
|
705
|
+
left = true;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const self = state.self;
|
|
709
|
+
const retired = self === undefined ? new Set() : directedAncestors(self.leafKey, state.edges);
|
|
710
|
+
// Nothing is paid by a device that never rotated (no snapshot of any group, no KeyPackage scan); a forgotten device does not re-key.
|
|
711
|
+
if (self !== undefined && retired.size > 0 && !(await seams.ownForget({ any: true }))) {
|
|
712
|
+
if (deps.groups.rekey !== undefined)
|
|
713
|
+
await sweep(self.leafKey, retired, driven);
|
|
714
|
+
if (open === undefined && !keyPackagesRechecked && deps.rotation !== undefined && deps.clock.now() >= recheckNotBefore) {
|
|
715
|
+
keyPackagesRechecked = true;
|
|
716
|
+
await recheckKeyPackages(self.leafKey, [...retired], state.rotations).catch((error) => {
|
|
717
|
+
if (stopsDeviceIntent(error))
|
|
718
|
+
throw error;
|
|
719
|
+
// Retried later, not by every pass: each attempt may prompt the signer again.
|
|
720
|
+
recheckFailures += 1;
|
|
721
|
+
if (recheckFailures < MAX_RECHECK_FAILURES) {
|
|
722
|
+
keyPackagesRechecked = false;
|
|
723
|
+
recheckNotBefore = deps.clock.now() + RESUME_BACKOFF_MS;
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return left || owedLeft;
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* AC-ROT-11: every held member group whose own leaf key is one `self` descends from (a retired key of THIS device, along the
|
|
732
|
+
* directed links) gets a `rekey` toward `self` - no new key, no signer call. A group already on `self` gets none; a failure
|
|
733
|
+
* is not retried by the pass, and a group refused is not asked again before its back-off ends (a fenced or permanently refused
|
|
734
|
+
* group for an hour, others 30 s doubling); a group the open rotation drove in this pass is left to it.
|
|
735
|
+
*/
|
|
736
|
+
async function sweep(selfKey, ancestors, skip) {
|
|
737
|
+
const held = [...(await deps.groups.heldGroups())].sort();
|
|
738
|
+
for (const groupId of [...verified.keys()])
|
|
739
|
+
if (!held.includes(groupId))
|
|
740
|
+
verified.delete(groupId);
|
|
741
|
+
for (const key of [...refused.keys()])
|
|
742
|
+
if (!held.includes(key.split('|')[0]))
|
|
743
|
+
refused.delete(key);
|
|
744
|
+
for (const groupId of held) {
|
|
745
|
+
if (skip.has(groupId))
|
|
746
|
+
continue;
|
|
747
|
+
const now = deps.clock.now();
|
|
748
|
+
if ((refused.get(`${groupId}|${selfKey}`)?.until ?? 0) > now)
|
|
749
|
+
continue;
|
|
750
|
+
// The tip is a plain read (epoch and confirmation tag): any commit, Welcome adoption, switch or restore - also one at the
|
|
751
|
+
// same epoch - moves it and ends the mark.
|
|
752
|
+
const tip = await (deps.groups.groupTip?.(groupId) ?? deps.groups.groupEpoch(groupId).then((e) => (e === undefined ? undefined : String(e)))).catch(() => undefined);
|
|
753
|
+
const mark = tip === undefined ? undefined : `${selfKey}@${tip}`;
|
|
754
|
+
if (mark !== undefined && verified.get(groupId) === mark)
|
|
755
|
+
continue;
|
|
756
|
+
seams.assertLive('rotateKey');
|
|
757
|
+
let view;
|
|
758
|
+
try {
|
|
759
|
+
view = await deps.groups.snapshot(groupId);
|
|
760
|
+
}
|
|
761
|
+
catch (error) {
|
|
762
|
+
if (stopsDeviceIntent(error))
|
|
763
|
+
throw error;
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
const own = view?.ownLeaf?.leafKey;
|
|
767
|
+
if (view === undefined || !view.member || own === undefined)
|
|
768
|
+
continue;
|
|
769
|
+
if (own === selfKey) {
|
|
770
|
+
if (mark !== undefined)
|
|
771
|
+
verified.set(groupId, mark);
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
verified.delete(groupId);
|
|
775
|
+
if (!ancestors.has(own) || view.syncing || view.ownCommitPending)
|
|
776
|
+
continue; // a foreign key is left alone; a busy group is asked again later
|
|
777
|
+
try {
|
|
778
|
+
await deps.groups.rekey(groupId, selfKey);
|
|
779
|
+
refused.delete(`${groupId}|${selfKey}`);
|
|
780
|
+
}
|
|
781
|
+
catch (error) {
|
|
782
|
+
if (stopsDeviceIntent(error))
|
|
783
|
+
throw error;
|
|
784
|
+
const failure = classifyRekeyFailure(error);
|
|
785
|
+
if (failure === 'transient' || failure === 'retained')
|
|
786
|
+
continue;
|
|
787
|
+
const failures = (refused.get(`${groupId}|${selfKey}`)?.failures ?? 0) + 1;
|
|
788
|
+
const hour = 60 * 60_000;
|
|
789
|
+
const wait = failure === 'counted' ? Math.min(RESUME_BACKOFF_MS * 2 ** (failures - 1), hour) : hour;
|
|
790
|
+
refused.set(`${groupId}|${selfKey}`, { until: deps.clock.now() + wait, failures });
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Re-runs the KeyPackage retirement once per service lifetime for a device that rotated: what an earlier run left
|
|
796
|
+
* (`relay-unreachable` slots recorded on the last rotation) and a KeyPackage minted on a retired key across a prepare. The outcome
|
|
797
|
+
* replaces the blocked list recorded on the newest rotation.
|
|
798
|
+
*/
|
|
799
|
+
async function recheckKeyPackages(selfKey, retired, rotations) {
|
|
800
|
+
const outcome = await deps.rotation.retireKeyPackages(retired.filter((k) => k !== selfKey));
|
|
801
|
+
const last = rotations.at(-1);
|
|
802
|
+
if (last === undefined)
|
|
803
|
+
return;
|
|
804
|
+
const blocked = outcome.blocked.map((b) => ({ dSlot: b.dSlot, reason: b.reason }));
|
|
805
|
+
await deps.transaction(async (tx) => {
|
|
806
|
+
const view = tx.artifact(ARTIFACT);
|
|
807
|
+
const current = (await readDeviceKeyRotation(view, last.id));
|
|
808
|
+
if (current === undefined || current.status === 'rotating')
|
|
809
|
+
return;
|
|
810
|
+
const step = stepOf(current);
|
|
811
|
+
if (step.blocked.length === 0 && blocked.length === 0)
|
|
812
|
+
return;
|
|
813
|
+
await writeDeviceKeyRotation(view, withStep(current, { ...step, status: step.status === 'pending' ? 'done' : step.status, blocked }));
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
return {
|
|
817
|
+
rotateKey,
|
|
818
|
+
rotation,
|
|
819
|
+
resume,
|
|
820
|
+
invalidate(groupId) {
|
|
821
|
+
verified.delete(groupId);
|
|
822
|
+
for (const key of [...refused.keys()])
|
|
823
|
+
if (key.startsWith(`${groupId}|`))
|
|
824
|
+
refused.delete(key);
|
|
825
|
+
},
|
|
826
|
+
};
|
|
827
|
+
}
|