@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,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The device signing key (S8, ADR-003): ONE MLS leaf signature key pair per
|
|
3
|
+
* client instance (per account store), used for the leaf of every
|
|
4
|
+
* KeyPackage this client mints — `keyPackages.create/rotate`, enrolment
|
|
5
|
+
* KeyPackages and the creator leaf of `groups.create`.
|
|
6
|
+
*
|
|
7
|
+
* Why one key: ADR-003's device registry binds labels to "leaf signature
|
|
8
|
+
* keys" and `devices.forget(leafKey)` removes "the leaf from every shared
|
|
9
|
+
* group" — both presuppose that a device's leaf carries the same signature
|
|
10
|
+
* key in every group it belongs to. The engine's `generateKeyPackage` draws a
|
|
11
|
+
* fresh key pair from `ciphersuiteImpl.signature.keygen()` whenever it is
|
|
12
|
+
* given an `accountProofSigner` (and binds that key with the ADR-012 proof);
|
|
13
|
+
* {@link withDeviceSignatureKey} hands it a `CiphersuiteImpl` whose `keygen`
|
|
14
|
+
* returns the device key instead — an injected dependency, not an engine
|
|
15
|
+
* edit. RFC 9420 requires signature keys to be unique only within one
|
|
16
|
+
* group's tree; the same-account `clientConfig` (account/) compares a
|
|
17
|
+
* KeyPackage with a leaf by signature key alone, so a device can never hold
|
|
18
|
+
* two leaves of one group.
|
|
19
|
+
*
|
|
20
|
+
* Stored in the account `deviceRegistry` artifact under
|
|
21
|
+
* {@link DEVICE_KEY_ENTRY} (the registry's other keys are 64-hex leaf keys,
|
|
22
|
+
* so the entry can never collide with one). The private half never leaves
|
|
23
|
+
* the account store (the KeyPackage private material next to it already
|
|
24
|
+
* carries the same key).
|
|
25
|
+
*/
|
|
26
|
+
import { type AccountIdentityProofSigner } from '@941design/marmot-engine/core';
|
|
27
|
+
import type { CiphersuiteImpl } from '@941design/marmot-engine/mls';
|
|
28
|
+
import type { EventTemplate, NostrEvent } from '@941design/nostr-events/event';
|
|
29
|
+
import type { AccountStoreTx } from '../storage/index.js';
|
|
30
|
+
import { type DeviceKeyRotationRecord } from './device-rotation-records.js';
|
|
31
|
+
/** The `deviceRegistry` key holding this client's own device signing key. */
|
|
32
|
+
export declare const DEVICE_KEY_ENTRY = "self";
|
|
33
|
+
export interface DeviceSigningKey {
|
|
34
|
+
readonly publicKey: Uint8Array;
|
|
35
|
+
readonly signKey: Uint8Array;
|
|
36
|
+
/** Hex of `publicKey`: the `leafKey` every leaf of this device carries. */
|
|
37
|
+
readonly leafKey: string;
|
|
38
|
+
/** Client clock (ms) when the key was created. */
|
|
39
|
+
readonly createdAt: number;
|
|
40
|
+
/**
|
|
41
|
+
* The 64-byte BIP-340 ADR-012 identity proof signature the account key made
|
|
42
|
+
* for this key (epic marmot-device-key-rotation, Design Decision 3). It
|
|
43
|
+
* depends on (account, key, ciphersuite) only, so one signature serves the
|
|
44
|
+
* leaf of every group and every KeyPackage minted with the key. Absent on a
|
|
45
|
+
* key created by {@link ensureDeviceSigningKey} (the proof is then signed
|
|
46
|
+
* per leaf, as before) and present on one created by
|
|
47
|
+
* {@link prepareDeviceKeyRotation}. Not secret: it is public in every leaf.
|
|
48
|
+
*/
|
|
49
|
+
readonly proof?: Uint8Array;
|
|
50
|
+
}
|
|
51
|
+
/** The device signing key read through an open transaction `tx` (for a check that must be atomic with the caller's own writes). */
|
|
52
|
+
export declare function readDeviceSigningKeyIn(tx: AccountStoreTx): Promise<DeviceSigningKey | undefined>;
|
|
53
|
+
/** The device signing key, or `undefined` when this client has not minted any leaf yet. */
|
|
54
|
+
export declare function readDeviceSigningKey(transaction: <T>(fn: (tx: AccountStoreTx) => Promise<T> | T) => Promise<T>): Promise<DeviceSigningKey | undefined>;
|
|
55
|
+
/**
|
|
56
|
+
* The device signing key, created on first use: the key pair is generated
|
|
57
|
+
* outside any transaction, then the transaction re-reads the entry and keeps
|
|
58
|
+
* whichever key is already stored (two concurrent first mints agree on one).
|
|
59
|
+
*/
|
|
60
|
+
export declare function ensureDeviceSigningKey(transaction: <T>(fn: (tx: AccountStoreTx) => Promise<T> | T) => Promise<T>, impl: CiphersuiteImpl, nowMs: number): Promise<DeviceSigningKey>;
|
|
61
|
+
/**
|
|
62
|
+
* `impl` with a `signature.keygen()` that yields the device key pair (fresh
|
|
63
|
+
* copies each call); every other primitive is `impl`'s own. Handed to the
|
|
64
|
+
* engine's `generateKeyPackage`, it makes the minted leaf carry the device
|
|
65
|
+
* key (and the ADR-012 proof bind that key).
|
|
66
|
+
*/
|
|
67
|
+
export declare function withDeviceSignatureKey(impl: CiphersuiteImpl, key: DeviceSigningKey): CiphersuiteImpl;
|
|
68
|
+
/**
|
|
69
|
+
* The `accountProofSigner` for minting a leaf with `key`: when the key carries
|
|
70
|
+
* its stored proof ({@link DeviceSigningKey.proof}) the signer is the function
|
|
71
|
+
* form of the engine's `AccountIdentityProofSigner` and returns the stored
|
|
72
|
+
* signature, so minting needs no kind-450 `signEvent` (Design Decision 3,
|
|
73
|
+
* AC-KEY-7); otherwise — a key created before any rotation, or a request for
|
|
74
|
+
* another key — it is `{ signEvent }` over `fallback` and the proof is signed
|
|
75
|
+
* per leaf as before.
|
|
76
|
+
*/
|
|
77
|
+
export declare function deviceProofSigner(key: DeviceSigningKey, fallback: (template: EventTemplate) => Promise<NostrEvent>): AccountIdentityProofSigner;
|
|
78
|
+
export interface PrepareDeviceKeyRotationInput {
|
|
79
|
+
/** `AccountStore.transaction`, already routed through the client's re-entrancy guard. */
|
|
80
|
+
readonly transaction: <T>(fn: (tx: AccountStoreTx) => Promise<T> | T) => Promise<T>;
|
|
81
|
+
readonly impl: CiphersuiteImpl;
|
|
82
|
+
/** The account signer's `signEvent`; called exactly once (the kind-450 proof), outside any transaction. */
|
|
83
|
+
readonly signEvent: (template: EventTemplate) => Promise<NostrEvent>;
|
|
84
|
+
/** Hex of the account's x-only pubkey: the credential identity the proof binds the key to. */
|
|
85
|
+
readonly accountPubkey: string;
|
|
86
|
+
/** The held groups whose own leaf the rotation must cover; recorded `pending`. Duplicates are dropped. */
|
|
87
|
+
readonly groups: readonly string[];
|
|
88
|
+
readonly nowMs: number;
|
|
89
|
+
/**
|
|
90
|
+
* Further own-leaf keys to retire next to the previous `self` key — e.g. the
|
|
91
|
+
* key of a leaf restored from a backup (Open Product Question 2). Each is
|
|
92
|
+
* linked to the new key like the previous `self` key.
|
|
93
|
+
*/
|
|
94
|
+
readonly replacedKeys?: readonly string[];
|
|
95
|
+
}
|
|
96
|
+
export interface PreparedDeviceKeyRotation {
|
|
97
|
+
/** The new device key, as stored in `deviceRegistry/self` (with its proof). */
|
|
98
|
+
readonly key: DeviceSigningKey;
|
|
99
|
+
/** The `rotation:<id>` record as written. */
|
|
100
|
+
readonly rotation: DeviceKeyRotationRecord;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Prepare of a device-key rotation (Design Decision 5): makes a fresh key the
|
|
104
|
+
* device key and records the rotation, in ONE account transaction.
|
|
105
|
+
*
|
|
106
|
+
* Outside any transaction — never inside one — it reads the keys already in
|
|
107
|
+
* use, generates a key pair that is none of them, and has the account signer
|
|
108
|
+
* sign the ADR-012 identity proof for it (one kind-450 `signEvent`, however
|
|
109
|
+
* many groups or KeyPackage slots follow: the signer cost is independent of
|
|
110
|
+
* them, ADR-009). The transaction then, all or nothing:
|
|
111
|
+
*
|
|
112
|
+
* - rejects `invalid-options` / `details.reason: 'rotation-open'` when a
|
|
113
|
+
* rotation is already `rotating` (two concurrent prepares end with one);
|
|
114
|
+
* - writes `deviceRegistry/self` = the new key with its proof — the private
|
|
115
|
+
* half of the previous key leaves the registry here (Design Decision 9);
|
|
116
|
+
* - writes `rotation:<id>` (`status: 'rotating'`, `from` = the previous
|
|
117
|
+
* `self` key then any `replacedKeys`, `to`, the groups each `pending`);
|
|
118
|
+
* - writes `rotated:<k>` (`source: 'own'`) for every `from` key, keeping an
|
|
119
|
+
* existing link of a key as it is (one record per key);
|
|
120
|
+
* - re-keys the registry entry of the previous `self` key to the new key,
|
|
121
|
+
* `label`, `enrolledAt`, `leafIndex` and any tombstone preserved.
|
|
122
|
+
*
|
|
123
|
+
* A client that never minted anything has no previous key: `from` is then
|
|
124
|
+
* only `replacedKeys` (possibly empty); whether that is a rotation worth
|
|
125
|
+
* running is the caller's rule (AC-ROT-2's `no-device-key`).
|
|
126
|
+
*
|
|
127
|
+
* After it commits, every new mint carries the new key and the stored proof
|
|
128
|
+
* ({@link deviceProofSigner}); group re-keys and KeyPackage retirement
|
|
129
|
+
* (`retireKeyPackagesSignedWith`, publisher.ts) are reconciliation the caller drives.
|
|
130
|
+
*/
|
|
131
|
+
export declare function prepareDeviceKeyRotation(input: PrepareDeviceKeyRotationInput): Promise<PreparedDeviceKeyRotation>;
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The device signing key (S8, ADR-003): ONE MLS leaf signature key pair per
|
|
3
|
+
* client instance (per account store), used for the leaf of every
|
|
4
|
+
* KeyPackage this client mints — `keyPackages.create/rotate`, enrolment
|
|
5
|
+
* KeyPackages and the creator leaf of `groups.create`.
|
|
6
|
+
*
|
|
7
|
+
* Why one key: ADR-003's device registry binds labels to "leaf signature
|
|
8
|
+
* keys" and `devices.forget(leafKey)` removes "the leaf from every shared
|
|
9
|
+
* group" — both presuppose that a device's leaf carries the same signature
|
|
10
|
+
* key in every group it belongs to. The engine's `generateKeyPackage` draws a
|
|
11
|
+
* fresh key pair from `ciphersuiteImpl.signature.keygen()` whenever it is
|
|
12
|
+
* given an `accountProofSigner` (and binds that key with the ADR-012 proof);
|
|
13
|
+
* {@link withDeviceSignatureKey} hands it a `CiphersuiteImpl` whose `keygen`
|
|
14
|
+
* returns the device key instead — an injected dependency, not an engine
|
|
15
|
+
* edit. RFC 9420 requires signature keys to be unique only within one
|
|
16
|
+
* group's tree; the same-account `clientConfig` (account/) compares a
|
|
17
|
+
* KeyPackage with a leaf by signature key alone, so a device can never hold
|
|
18
|
+
* two leaves of one group.
|
|
19
|
+
*
|
|
20
|
+
* Stored in the account `deviceRegistry` artifact under
|
|
21
|
+
* {@link DEVICE_KEY_ENTRY} (the registry's other keys are 64-hex leaf keys,
|
|
22
|
+
* so the entry can never collide with one). The private half never leaves
|
|
23
|
+
* the account store (the KeyPackage private material next to it already
|
|
24
|
+
* carries the same key).
|
|
25
|
+
*/
|
|
26
|
+
import { accountIdentityProofSignatureFromSignedEvent, buildAccountIdentityProofEvent, createCredential, makeAccountIdentityProofExtension, verifyLeafAccountIdentityProof, mlsSignatureScheme, } from '@941design/marmot-engine/core';
|
|
27
|
+
import { MarmotError } from '../shared/index.js';
|
|
28
|
+
import { findOpenDeviceKeyRotation, isLeafKeyHex, moveRegistryEntry, readAllDeviceKeyLinks, readAllDeviceKeyRotations, writeDeviceKeyLink, writeDeviceKeyRotation, } from './device-rotation-records.js';
|
|
29
|
+
/** The `deviceRegistry` key holding this client's own device signing key. */
|
|
30
|
+
export const DEVICE_KEY_ENTRY = 'self';
|
|
31
|
+
const ARTIFACT = 'deviceRegistry';
|
|
32
|
+
const PROOF_BYTES = 64;
|
|
33
|
+
function toHex(bytes) {
|
|
34
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
35
|
+
}
|
|
36
|
+
function malformedSelf() {
|
|
37
|
+
return new MarmotError('store-failed', 'deviceRegistry/self: malformed device signing key record', { details: { key: 'self', malformed: true } });
|
|
38
|
+
}
|
|
39
|
+
function decode(raw) {
|
|
40
|
+
if (raw === undefined)
|
|
41
|
+
return undefined;
|
|
42
|
+
const r = raw;
|
|
43
|
+
if (!(r.publicKey instanceof Uint8Array) || !(r.signKey instanceof Uint8Array) || typeof r.createdAt !== 'number')
|
|
44
|
+
throw malformedSelf();
|
|
45
|
+
if (r.proof === undefined)
|
|
46
|
+
return { publicKey: r.publicKey, signKey: r.signKey, leafKey: toHex(r.publicKey), createdAt: r.createdAt };
|
|
47
|
+
if (!(r.proof instanceof Uint8Array) || r.proof.length !== PROOF_BYTES)
|
|
48
|
+
throw malformedSelf();
|
|
49
|
+
return { publicKey: r.publicKey, signKey: r.signKey, leafKey: toHex(r.publicKey), createdAt: r.createdAt, proof: r.proof };
|
|
50
|
+
}
|
|
51
|
+
function encode(key) {
|
|
52
|
+
return {
|
|
53
|
+
publicKey: key.publicKey,
|
|
54
|
+
signKey: key.signKey,
|
|
55
|
+
createdAt: key.createdAt,
|
|
56
|
+
...(key.proof === undefined ? {} : { proof: key.proof }),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** The device signing key read through an open transaction `tx` (for a check that must be atomic with the caller's own writes). */
|
|
60
|
+
export async function readDeviceSigningKeyIn(tx) {
|
|
61
|
+
return decode(await tx.artifact(ARTIFACT).get(DEVICE_KEY_ENTRY));
|
|
62
|
+
}
|
|
63
|
+
/** The device signing key, or `undefined` when this client has not minted any leaf yet. */
|
|
64
|
+
export async function readDeviceSigningKey(transaction) {
|
|
65
|
+
return transaction(async (tx) => decode(await tx.artifact(ARTIFACT).get(DEVICE_KEY_ENTRY)));
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The device signing key, created on first use: the key pair is generated
|
|
69
|
+
* outside any transaction, then the transaction re-reads the entry and keeps
|
|
70
|
+
* whichever key is already stored (two concurrent first mints agree on one).
|
|
71
|
+
*/
|
|
72
|
+
export async function ensureDeviceSigningKey(transaction, impl, nowMs) {
|
|
73
|
+
const existing = await readDeviceSigningKey(transaction);
|
|
74
|
+
if (existing !== undefined)
|
|
75
|
+
return existing;
|
|
76
|
+
const fresh = await impl.signature.keygen();
|
|
77
|
+
return transaction(async (tx) => {
|
|
78
|
+
const view = tx.artifact(ARTIFACT);
|
|
79
|
+
const stored = decode(await view.get(DEVICE_KEY_ENTRY));
|
|
80
|
+
if (stored !== undefined)
|
|
81
|
+
return stored;
|
|
82
|
+
await view.put(DEVICE_KEY_ENTRY, encode({ publicKey: fresh.publicKey, signKey: fresh.signKey, createdAt: nowMs }));
|
|
83
|
+
return { publicKey: fresh.publicKey, signKey: fresh.signKey, leafKey: toHex(fresh.publicKey), createdAt: nowMs };
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* `impl` with a `signature.keygen()` that yields the device key pair (fresh
|
|
88
|
+
* copies each call); every other primitive is `impl`'s own. Handed to the
|
|
89
|
+
* engine's `generateKeyPackage`, it makes the minted leaf carry the device
|
|
90
|
+
* key (and the ADR-012 proof bind that key).
|
|
91
|
+
*/
|
|
92
|
+
export function withDeviceSignatureKey(impl, key) {
|
|
93
|
+
const signature = impl.signature;
|
|
94
|
+
return {
|
|
95
|
+
...impl,
|
|
96
|
+
signature: {
|
|
97
|
+
sign: (signKey, message) => signature.sign(signKey, message),
|
|
98
|
+
verify: (publicKey, message, sig) => signature.verify(publicKey, message, sig),
|
|
99
|
+
keygen: async () => ({ publicKey: key.publicKey.slice(), signKey: key.signKey.slice() }),
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The `accountProofSigner` for minting a leaf with `key`: when the key carries
|
|
105
|
+
* its stored proof ({@link DeviceSigningKey.proof}) the signer is the function
|
|
106
|
+
* form of the engine's `AccountIdentityProofSigner` and returns the stored
|
|
107
|
+
* signature, so minting needs no kind-450 `signEvent` (Design Decision 3,
|
|
108
|
+
* AC-KEY-7); otherwise — a key created before any rotation, or a request for
|
|
109
|
+
* another key — it is `{ signEvent }` over `fallback` and the proof is signed
|
|
110
|
+
* per leaf as before.
|
|
111
|
+
*/
|
|
112
|
+
export function deviceProofSigner(key, fallback) {
|
|
113
|
+
const signed = { signEvent: fallback };
|
|
114
|
+
const stored = key.proof;
|
|
115
|
+
if (stored === undefined)
|
|
116
|
+
return signed;
|
|
117
|
+
return async (request) => {
|
|
118
|
+
if (!sameBytes(request.mlsSignaturePublicKey, key.publicKey) || !storedProofVerifies(stored, request)) {
|
|
119
|
+
// Not this key's proof for this request (another key, account or ciphersuite, or a corrupt record): sign it
|
|
120
|
+
// the ordinary way (one signer call) rather than mint a leaf the group would reject.
|
|
121
|
+
return accountIdentityProofSignatureFromSignedEvent(request, await fallback(buildAccountIdentityProofEvent(request)));
|
|
122
|
+
}
|
|
123
|
+
return stored.slice();
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Whether `proof` is a valid account signature for `request`: checked with the engine's own leaf verifier. */
|
|
127
|
+
function storedProofVerifies(proof, request) {
|
|
128
|
+
try {
|
|
129
|
+
const leaf = {
|
|
130
|
+
credential: createCredential(toHex(request.accountIdentity)),
|
|
131
|
+
signaturePublicKey: request.mlsSignaturePublicKey,
|
|
132
|
+
extensions: [makeAccountIdentityProofExtension({ request, signature: proof })],
|
|
133
|
+
};
|
|
134
|
+
verifyLeafAccountIdentityProof(leaf, request.ciphersuite);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function sameBytes(a, b) {
|
|
142
|
+
if (a.length !== b.length)
|
|
143
|
+
return false;
|
|
144
|
+
for (let i = 0; i < a.length; i++)
|
|
145
|
+
if (a[i] !== b[i])
|
|
146
|
+
return false;
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
function hexBytes(hex) {
|
|
150
|
+
const out = new Uint8Array(hex.length / 2);
|
|
151
|
+
for (let i = 0; i < out.length; i++)
|
|
152
|
+
out[i] = Number.parseInt(hex.slice(2 * i, 2 * i + 2), 16);
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
function randomHex(bytes) {
|
|
156
|
+
const out = new Uint8Array(bytes);
|
|
157
|
+
globalThis.crypto.getRandomValues(out);
|
|
158
|
+
return toHex(out);
|
|
159
|
+
}
|
|
160
|
+
const MAX_FRESH_KEY_ATTEMPTS = 3;
|
|
161
|
+
function rotationOpen(openId) {
|
|
162
|
+
return new MarmotError('invalid-options', 'devices: a device key rotation is already open', { details: { reason: 'rotation-open', rotationId: openId } });
|
|
163
|
+
}
|
|
164
|
+
/** Every leaf-key-shaped value the registry has ever held or named: `self`, entries, links, rotation records. */
|
|
165
|
+
async function usedLeafKeys(view) {
|
|
166
|
+
const used = new Set();
|
|
167
|
+
for (const key of await view.keys())
|
|
168
|
+
if (isLeafKeyHex(key))
|
|
169
|
+
used.add(key);
|
|
170
|
+
const self = decode(await view.get(DEVICE_KEY_ENTRY));
|
|
171
|
+
if (self !== undefined)
|
|
172
|
+
used.add(self.leafKey);
|
|
173
|
+
for (const [from, link] of await readAllDeviceKeyLinks(view)) {
|
|
174
|
+
used.add(from);
|
|
175
|
+
used.add(link.to);
|
|
176
|
+
}
|
|
177
|
+
for (const rotation of await readAllDeviceKeyRotations(view)) {
|
|
178
|
+
for (const k of rotation.from)
|
|
179
|
+
used.add(k);
|
|
180
|
+
used.add(rotation.to);
|
|
181
|
+
}
|
|
182
|
+
return used;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Prepare of a device-key rotation (Design Decision 5): makes a fresh key the
|
|
186
|
+
* device key and records the rotation, in ONE account transaction.
|
|
187
|
+
*
|
|
188
|
+
* Outside any transaction — never inside one — it reads the keys already in
|
|
189
|
+
* use, generates a key pair that is none of them, and has the account signer
|
|
190
|
+
* sign the ADR-012 identity proof for it (one kind-450 `signEvent`, however
|
|
191
|
+
* many groups or KeyPackage slots follow: the signer cost is independent of
|
|
192
|
+
* them, ADR-009). The transaction then, all or nothing:
|
|
193
|
+
*
|
|
194
|
+
* - rejects `invalid-options` / `details.reason: 'rotation-open'` when a
|
|
195
|
+
* rotation is already `rotating` (two concurrent prepares end with one);
|
|
196
|
+
* - writes `deviceRegistry/self` = the new key with its proof — the private
|
|
197
|
+
* half of the previous key leaves the registry here (Design Decision 9);
|
|
198
|
+
* - writes `rotation:<id>` (`status: 'rotating'`, `from` = the previous
|
|
199
|
+
* `self` key then any `replacedKeys`, `to`, the groups each `pending`);
|
|
200
|
+
* - writes `rotated:<k>` (`source: 'own'`) for every `from` key, keeping an
|
|
201
|
+
* existing link of a key as it is (one record per key);
|
|
202
|
+
* - re-keys the registry entry of the previous `self` key to the new key,
|
|
203
|
+
* `label`, `enrolledAt`, `leafIndex` and any tombstone preserved.
|
|
204
|
+
*
|
|
205
|
+
* A client that never minted anything has no previous key: `from` is then
|
|
206
|
+
* only `replacedKeys` (possibly empty); whether that is a rotation worth
|
|
207
|
+
* running is the caller's rule (AC-ROT-2's `no-device-key`).
|
|
208
|
+
*
|
|
209
|
+
* After it commits, every new mint carries the new key and the stored proof
|
|
210
|
+
* ({@link deviceProofSigner}); group re-keys and KeyPackage retirement
|
|
211
|
+
* (`retireKeyPackagesSignedWith`, publisher.ts) are reconciliation the caller drives.
|
|
212
|
+
*/
|
|
213
|
+
export async function prepareDeviceKeyRotation(input) {
|
|
214
|
+
const { transaction, impl, signEvent, accountPubkey, nowMs } = input;
|
|
215
|
+
if (!/^[0-9a-f]{64}$/.test(accountPubkey))
|
|
216
|
+
throw new MarmotError('invalid-options', 'devices: accountPubkey must be 64 lowercase hex');
|
|
217
|
+
const replacedKeys = [...new Set(input.replacedKeys ?? [])];
|
|
218
|
+
if (!replacedKeys.every(isLeafKeyHex))
|
|
219
|
+
throw new MarmotError('invalid-options', 'devices: replacedKeys must be 64-hex leaf keys');
|
|
220
|
+
const groups = [...new Set(input.groups)];
|
|
221
|
+
// Cheap early refusal; the transaction below is the authority.
|
|
222
|
+
const early = await transaction(async (tx) => findOpenDeviceKeyRotation(tx.artifact(ARTIFACT)));
|
|
223
|
+
if (early !== undefined)
|
|
224
|
+
throw rotationOpen(early.id);
|
|
225
|
+
// Outside any transaction: a key that is none of the keys ever used, and its proof.
|
|
226
|
+
const used = await transaction(async (tx) => usedLeafKeys(tx.artifact(ARTIFACT)));
|
|
227
|
+
let fresh;
|
|
228
|
+
for (let attempt = 0; attempt < MAX_FRESH_KEY_ATTEMPTS && fresh === undefined; attempt++) {
|
|
229
|
+
const candidate = await impl.signature.keygen();
|
|
230
|
+
if (!used.has(toHex(candidate.publicKey)))
|
|
231
|
+
fresh = candidate;
|
|
232
|
+
}
|
|
233
|
+
if (fresh === undefined)
|
|
234
|
+
throw new MarmotError('store-failed', 'devices: could not generate a device key distinct from every earlier one', { details: { reason: 'key-collision' } });
|
|
235
|
+
const request = {
|
|
236
|
+
accountIdentity: hexBytes(accountPubkey),
|
|
237
|
+
mlsSignaturePublicKey: fresh.publicKey,
|
|
238
|
+
ciphersuite: impl.id,
|
|
239
|
+
signatureScheme: mlsSignatureScheme(impl.id),
|
|
240
|
+
};
|
|
241
|
+
const proof = accountIdentityProofSignatureFromSignedEvent(request, await signEvent(buildAccountIdentityProofEvent(request)));
|
|
242
|
+
const leafKey = toHex(fresh.publicKey);
|
|
243
|
+
const id = randomHex(16);
|
|
244
|
+
return transaction(async (tx) => {
|
|
245
|
+
const view = tx.artifact(ARTIFACT);
|
|
246
|
+
const open = await findOpenDeviceKeyRotation(view);
|
|
247
|
+
if (open !== undefined)
|
|
248
|
+
throw rotationOpen(open.id);
|
|
249
|
+
if ((await usedLeafKeys(view)).has(leafKey)) {
|
|
250
|
+
throw new MarmotError('store-failed', 'devices: the generated device key collides with an earlier one', { details: { reason: 'key-collision' } });
|
|
251
|
+
}
|
|
252
|
+
const previous = decode(await view.get(DEVICE_KEY_ENTRY));
|
|
253
|
+
const from = [...new Set([...(previous === undefined ? [] : [previous.leafKey]), ...replacedKeys])];
|
|
254
|
+
const key = { publicKey: fresh.publicKey, signKey: fresh.signKey, leafKey, createdAt: nowMs, proof };
|
|
255
|
+
const rotation = {
|
|
256
|
+
v: 1,
|
|
257
|
+
id,
|
|
258
|
+
from,
|
|
259
|
+
to: leafKey,
|
|
260
|
+
startedAt: nowMs,
|
|
261
|
+
status: 'rotating',
|
|
262
|
+
groups: groups.map((groupId) => ({ groupId, outcome: 'pending', attempts: 0 })),
|
|
263
|
+
};
|
|
264
|
+
await view.put(DEVICE_KEY_ENTRY, encode(key));
|
|
265
|
+
await writeDeviceKeyRotation(view, rotation);
|
|
266
|
+
for (const k of from)
|
|
267
|
+
await writeDeviceKeyLink(view, k, { v: 1, to: leafKey, at: nowMs, source: 'own' });
|
|
268
|
+
if (previous !== undefined)
|
|
269
|
+
await moveRegistryEntry(view, previous.leafKey, leafKey);
|
|
270
|
+
return { key, rotation };
|
|
271
|
+
});
|
|
272
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { KeyValueView, Storable } from '../storage/index.js';
|
|
2
|
+
/** Prefix of a lineage link: `rotated:<fromKey>` -> {@link DeviceKeyLinkRecord}. */
|
|
3
|
+
export declare const ROTATED_PREFIX = "rotated:";
|
|
4
|
+
/** Prefix of a rotation intent: `rotation:<id>` -> {@link DeviceKeyRotationRecord}. */
|
|
5
|
+
export declare const ROTATION_PREFIX = "rotation:";
|
|
6
|
+
/** Whether `key` is the 64-lowercase-hex form of a leaf signature key. */
|
|
7
|
+
export declare function isLeafKeyHex(key: string): boolean;
|
|
8
|
+
export declare const deviceKeyLinkKey: (fromKey: string) => string;
|
|
9
|
+
export declare const deviceKeyRotationKey: (id: string) => string;
|
|
10
|
+
/** Where a link was learned: `own` — this client generated the successor key; `observed` — read from MLS state (a sibling's rotation). */
|
|
11
|
+
export type DeviceKeyLinkSource = 'own' | 'observed';
|
|
12
|
+
/** "`fromKey` was succeeded by `to`" — a fact about what the device generated, not about any group's tip (Design Decision 7). */
|
|
13
|
+
export interface DeviceKeyLinkRecord {
|
|
14
|
+
readonly v: 1;
|
|
15
|
+
readonly to: string;
|
|
16
|
+
/** Client clock (ms) when the link was recorded. */
|
|
17
|
+
readonly at: number;
|
|
18
|
+
readonly source: DeviceKeyLinkSource;
|
|
19
|
+
}
|
|
20
|
+
/** Strict decode of the `rotated:<fromKey>` row; `undefined` when absent. */
|
|
21
|
+
export declare function readDeviceKeyLink(view: KeyValueView, fromKey: string): Promise<DeviceKeyLinkRecord | undefined>;
|
|
22
|
+
/**
|
|
23
|
+
* Writes `rotated:<fromKey>` unless a record for that key already exists —
|
|
24
|
+
* exactly one record per `fromKey` (Design Decision 4): an existing record
|
|
25
|
+
* with the same `to` is left as is (idempotent: nothing is written), one with
|
|
26
|
+
* a different `to` is kept and the new one ignored. Returns whether it wrote.
|
|
27
|
+
* Rejects a link of a key to itself.
|
|
28
|
+
*/
|
|
29
|
+
export declare function writeDeviceKeyLink(view: KeyValueView, fromKey: string, link: DeviceKeyLinkRecord): Promise<'written' | 'kept'>;
|
|
30
|
+
/** Every link in the registry as `fromKey -> record` (strict decode of each `rotated:` row). */
|
|
31
|
+
export declare function readAllDeviceKeyLinks(view: KeyValueView): Promise<Map<string, DeviceKeyLinkRecord>>;
|
|
32
|
+
/**
|
|
33
|
+
* `rotating` — open, the pass still has work; `settled` — every group is
|
|
34
|
+
* terminal; `gave-up` — the pass gave up (AC-ROT-1/11). A `gave-up` rotation
|
|
35
|
+
* does not block a new one (AC-ROT-3); only `rotating` does.
|
|
36
|
+
*/
|
|
37
|
+
export type DeviceKeyRotationStatus = 'rotating' | 'settled' | 'gave-up';
|
|
38
|
+
export type DeviceKeyRotationGroupOutcome = 'pending' | 'rekeyed' | 'satisfied' | 'removed' | 'timed-out' | 'cancelled';
|
|
39
|
+
export interface DeviceKeyRotationGroup {
|
|
40
|
+
readonly groupId: string;
|
|
41
|
+
readonly outcome: DeviceKeyRotationGroupOutcome;
|
|
42
|
+
/** Re-key attempts that ran and left the leaf on its old key. */
|
|
43
|
+
readonly attempts: number;
|
|
44
|
+
/** A re-key was issued and its fate is not known yet. */
|
|
45
|
+
readonly inflight?: boolean;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The rotation intent. Prepare (S4) writes `id`, `from`, `to`, `startedAt`,
|
|
49
|
+
* `status: 'rotating'` and the held groups each `pending`; the service (S7)
|
|
50
|
+
* owns every later field. A decode keeps fields it does not know (the
|
|
51
|
+
* service's `keyPackages`, `cancelled`, `gaveUp`) so a read-modify-write by
|
|
52
|
+
* either side never drops the other's.
|
|
53
|
+
*/
|
|
54
|
+
export interface DeviceKeyRotationRecord {
|
|
55
|
+
readonly v: 1;
|
|
56
|
+
readonly id: string;
|
|
57
|
+
/** Every distinct key this rotation replaces, oldest first (the previous `self` key, then any other own-leaf key supplied). */
|
|
58
|
+
readonly from: readonly string[];
|
|
59
|
+
/** The new device (leaf) key. */
|
|
60
|
+
readonly to: string;
|
|
61
|
+
readonly startedAt: number;
|
|
62
|
+
readonly status: DeviceKeyRotationStatus;
|
|
63
|
+
readonly groups: readonly DeviceKeyRotationGroup[];
|
|
64
|
+
/** Service-owned (S7); opaque here. */
|
|
65
|
+
readonly keyPackages?: Storable;
|
|
66
|
+
readonly cancelled?: Storable;
|
|
67
|
+
readonly gaveUp?: Storable;
|
|
68
|
+
}
|
|
69
|
+
/** Strict decode of `rotation:<id>`; `undefined` when absent. */
|
|
70
|
+
export declare function readDeviceKeyRotation(view: KeyValueView, id: string): Promise<DeviceKeyRotationRecord | undefined>;
|
|
71
|
+
export declare function writeDeviceKeyRotation(view: KeyValueView, record: DeviceKeyRotationRecord): Promise<void>;
|
|
72
|
+
/** Every rotation record, oldest `startedAt` first (ties by id). */
|
|
73
|
+
export declare function readAllDeviceKeyRotations(view: KeyValueView): Promise<DeviceKeyRotationRecord[]>;
|
|
74
|
+
/** The open rotation (`status: 'rotating'`), newest first when several exist (a corrupt store), or `undefined`. */
|
|
75
|
+
export declare function findOpenDeviceKeyRotation(view: KeyValueView): Promise<DeviceKeyRotationRecord | undefined>;
|
|
76
|
+
/**
|
|
77
|
+
* Re-keys the registry entry stored under `fromKey` to `toKey`: the same
|
|
78
|
+
* record with its `leafKey` replaced — every other field (`label`, `enrolledAt`,
|
|
79
|
+
* `leafIndex`, any `tombstone`) is copied opaquely — and the old row deleted. A
|
|
80
|
+
* no-op when there is no entry at `fromKey`. The entry's shape belongs to
|
|
81
|
+
* `account`; this checks only that the row names its own key.
|
|
82
|
+
*/
|
|
83
|
+
export declare function moveRegistryEntry(view: KeyValueView, fromKey: string, toKey: string): Promise<boolean>;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The raw `deviceRegistry` records a device-key rotation writes (epic
|
|
3
|
+
* marmot-device-key-rotation, Design Decisions 4, 5 and 9): the lineage link
|
|
4
|
+
* `rotated:<fromKey>` and the durable intent `rotation:<id>`. This module is
|
|
5
|
+
* the one codec for both, shared by the prepare step (`device-key.ts`, S4),
|
|
6
|
+
* which writes them, and by the lineage resolution (`account`, S5) and the
|
|
7
|
+
* rotation service (`account`, S7), which read and extend them. It lives in
|
|
8
|
+
* `key-packages` because `account` may import `key-packages` and not the
|
|
9
|
+
* reverse; it knows nothing of lineage resolution (chains, heads, cycles).
|
|
10
|
+
*
|
|
11
|
+
* Both record kinds hold public keys and bookkeeping only — never key
|
|
12
|
+
* material. Every decode is strict: a record that is present and malformed
|
|
13
|
+
* rejects `store-failed` with `details.malformed: true` (never silently
|
|
14
|
+
* skipped), the convention of the registry's own entries.
|
|
15
|
+
*/
|
|
16
|
+
import { MarmotError } from '../shared/index.js';
|
|
17
|
+
const LEAF_KEY = /^[0-9a-f]{64}$/;
|
|
18
|
+
/** Prefix of a lineage link: `rotated:<fromKey>` -> {@link DeviceKeyLinkRecord}. */
|
|
19
|
+
export const ROTATED_PREFIX = 'rotated:';
|
|
20
|
+
/** Prefix of a rotation intent: `rotation:<id>` -> {@link DeviceKeyRotationRecord}. */
|
|
21
|
+
export const ROTATION_PREFIX = 'rotation:';
|
|
22
|
+
/** Whether `key` is the 64-lowercase-hex form of a leaf signature key. */
|
|
23
|
+
export function isLeafKeyHex(key) {
|
|
24
|
+
return LEAF_KEY.test(key);
|
|
25
|
+
}
|
|
26
|
+
export const deviceKeyLinkKey = (fromKey) => `${ROTATED_PREFIX}${fromKey}`;
|
|
27
|
+
export const deviceKeyRotationKey = (id) => `${ROTATION_PREFIX}${id}`;
|
|
28
|
+
function malformed(key, reason) {
|
|
29
|
+
return new MarmotError('store-failed', `deviceRegistry/${key}: malformed record (${reason})`, { details: { key, malformed: true } });
|
|
30
|
+
}
|
|
31
|
+
/** Strict decode of the `rotated:<fromKey>` row; `undefined` when absent. */
|
|
32
|
+
export async function readDeviceKeyLink(view, fromKey) {
|
|
33
|
+
const key = deviceKeyLinkKey(fromKey);
|
|
34
|
+
const raw = await view.get(key);
|
|
35
|
+
if (raw === undefined)
|
|
36
|
+
return undefined;
|
|
37
|
+
return decodeDeviceKeyLink(key, raw);
|
|
38
|
+
}
|
|
39
|
+
function decodeDeviceKeyLink(key, raw) {
|
|
40
|
+
if (!isLeafKeyHex(key.slice(ROTATED_PREFIX.length)))
|
|
41
|
+
throw malformed(key, 'fromKey is not 64 lowercase hex');
|
|
42
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
|
|
43
|
+
throw malformed(key, 'not an object');
|
|
44
|
+
const r = raw;
|
|
45
|
+
if (r['v'] !== 1)
|
|
46
|
+
throw malformed(key, 'unsupported version');
|
|
47
|
+
const to = r['to'];
|
|
48
|
+
if (typeof to !== 'string' || !isLeafKeyHex(to))
|
|
49
|
+
throw malformed(key, 'to is not 64 lowercase hex');
|
|
50
|
+
const at = r['at'];
|
|
51
|
+
if (typeof at !== 'number' || !Number.isFinite(at))
|
|
52
|
+
throw malformed(key, 'at is not a number');
|
|
53
|
+
const source = r['source'];
|
|
54
|
+
if (source !== 'own' && source !== 'observed')
|
|
55
|
+
throw malformed(key, 'source is invalid');
|
|
56
|
+
return { v: 1, to, at, source };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Writes `rotated:<fromKey>` unless a record for that key already exists —
|
|
60
|
+
* exactly one record per `fromKey` (Design Decision 4): an existing record
|
|
61
|
+
* with the same `to` is left as is (idempotent: nothing is written), one with
|
|
62
|
+
* a different `to` is kept and the new one ignored. Returns whether it wrote.
|
|
63
|
+
* Rejects a link of a key to itself.
|
|
64
|
+
*/
|
|
65
|
+
export async function writeDeviceKeyLink(view, fromKey, link) {
|
|
66
|
+
if (!isLeafKeyHex(fromKey) || !isLeafKeyHex(link.to))
|
|
67
|
+
throw new MarmotError('invalid-options', 'deviceRegistry: a lineage link names two 64-hex leaf keys');
|
|
68
|
+
if (fromKey === link.to)
|
|
69
|
+
throw new MarmotError('invalid-options', 'deviceRegistry: a key cannot be linked to itself');
|
|
70
|
+
const existing = await readDeviceKeyLink(view, fromKey);
|
|
71
|
+
if (existing !== undefined)
|
|
72
|
+
return 'kept';
|
|
73
|
+
await view.put(deviceKeyLinkKey(fromKey), { v: 1, to: link.to, at: link.at, source: link.source });
|
|
74
|
+
return 'written';
|
|
75
|
+
}
|
|
76
|
+
/** Every link in the registry as `fromKey -> record` (strict decode of each `rotated:` row). */
|
|
77
|
+
export async function readAllDeviceKeyLinks(view) {
|
|
78
|
+
const out = new Map();
|
|
79
|
+
for (const key of await view.keys()) {
|
|
80
|
+
if (!key.startsWith(ROTATED_PREFIX))
|
|
81
|
+
continue;
|
|
82
|
+
const raw = await view.get(key);
|
|
83
|
+
if (raw === undefined)
|
|
84
|
+
continue;
|
|
85
|
+
out.set(key.slice(ROTATED_PREFIX.length), decodeDeviceKeyLink(key, raw));
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
const OUTCOMES = new Set(['pending', 'rekeyed', 'satisfied', 'removed', 'timed-out', 'cancelled']);
|
|
90
|
+
function decodeRotation(key, raw) {
|
|
91
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
|
|
92
|
+
throw malformed(key, 'not an object');
|
|
93
|
+
const r = raw;
|
|
94
|
+
if (r['v'] !== 1)
|
|
95
|
+
throw malformed(key, 'unsupported version');
|
|
96
|
+
const id = r['id'];
|
|
97
|
+
if (typeof id !== 'string' || id.length === 0 || key !== deviceKeyRotationKey(id))
|
|
98
|
+
throw malformed(key, 'id does not match the key');
|
|
99
|
+
const from = r['from'];
|
|
100
|
+
if (!Array.isArray(from) || !from.every((k) => typeof k === 'string' && isLeafKeyHex(k)))
|
|
101
|
+
throw malformed(key, 'from is not a list of 64-hex keys');
|
|
102
|
+
const to = r['to'];
|
|
103
|
+
if (typeof to !== 'string' || !isLeafKeyHex(to))
|
|
104
|
+
throw malformed(key, 'to is not 64 lowercase hex');
|
|
105
|
+
if (typeof r['startedAt'] !== 'number')
|
|
106
|
+
throw malformed(key, 'startedAt is not a number');
|
|
107
|
+
const status = r['status'];
|
|
108
|
+
if (status !== 'rotating' && status !== 'settled' && status !== 'gave-up')
|
|
109
|
+
throw malformed(key, 'status is invalid');
|
|
110
|
+
const groups = r['groups'];
|
|
111
|
+
if (!Array.isArray(groups))
|
|
112
|
+
throw malformed(key, 'groups is not a list');
|
|
113
|
+
for (const g of groups) {
|
|
114
|
+
if (typeof g !== 'object' || g === null || Array.isArray(g) || g instanceof Uint8Array)
|
|
115
|
+
throw malformed(key, 'a group entry is not an object');
|
|
116
|
+
const e = g;
|
|
117
|
+
if (typeof e['groupId'] !== 'string' || typeof e['outcome'] !== 'string' || !OUTCOMES.has(e['outcome']) || typeof e['attempts'] !== 'number') {
|
|
118
|
+
throw malformed(key, 'a group entry is malformed');
|
|
119
|
+
}
|
|
120
|
+
if (e['inflight'] !== undefined && typeof e['inflight'] !== 'boolean')
|
|
121
|
+
throw malformed(key, 'a group entry is malformed');
|
|
122
|
+
}
|
|
123
|
+
return r;
|
|
124
|
+
}
|
|
125
|
+
/** Strict decode of `rotation:<id>`; `undefined` when absent. */
|
|
126
|
+
export async function readDeviceKeyRotation(view, id) {
|
|
127
|
+
const key = deviceKeyRotationKey(id);
|
|
128
|
+
const raw = await view.get(key);
|
|
129
|
+
return raw === undefined ? undefined : decodeRotation(key, raw);
|
|
130
|
+
}
|
|
131
|
+
export async function writeDeviceKeyRotation(view, record) {
|
|
132
|
+
await view.put(deviceKeyRotationKey(record.id), record);
|
|
133
|
+
}
|
|
134
|
+
/** Every rotation record, oldest `startedAt` first (ties by id). */
|
|
135
|
+
export async function readAllDeviceKeyRotations(view) {
|
|
136
|
+
const out = [];
|
|
137
|
+
for (const key of await view.keys()) {
|
|
138
|
+
if (!key.startsWith(ROTATION_PREFIX))
|
|
139
|
+
continue;
|
|
140
|
+
const raw = await view.get(key);
|
|
141
|
+
if (raw !== undefined)
|
|
142
|
+
out.push(decodeRotation(key, raw));
|
|
143
|
+
}
|
|
144
|
+
return out.sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
145
|
+
}
|
|
146
|
+
/** The open rotation (`status: 'rotating'`), newest first when several exist (a corrupt store), or `undefined`. */
|
|
147
|
+
export async function findOpenDeviceKeyRotation(view) {
|
|
148
|
+
const open = (await readAllDeviceKeyRotations(view)).filter((r) => r.status === 'rotating');
|
|
149
|
+
return open[open.length - 1];
|
|
150
|
+
}
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
// The registry entry (label, enrolment time, leaf index, tombstone)
|
|
153
|
+
// ---------------------------------------------------------------------------
|
|
154
|
+
/**
|
|
155
|
+
* Re-keys the registry entry stored under `fromKey` to `toKey`: the same
|
|
156
|
+
* record with its `leafKey` replaced — every other field (`label`, `enrolledAt`,
|
|
157
|
+
* `leafIndex`, any `tombstone`) is copied opaquely — and the old row deleted. A
|
|
158
|
+
* no-op when there is no entry at `fromKey`. The entry's shape belongs to
|
|
159
|
+
* `account`; this checks only that the row names its own key.
|
|
160
|
+
*/
|
|
161
|
+
export async function moveRegistryEntry(view, fromKey, toKey) {
|
|
162
|
+
const raw = await view.get(fromKey);
|
|
163
|
+
if (raw === undefined)
|
|
164
|
+
return false;
|
|
165
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
|
|
166
|
+
throw malformed(fromKey, 'registry entry is not an object');
|
|
167
|
+
const r = raw;
|
|
168
|
+
if (r['leafKey'] !== fromKey)
|
|
169
|
+
throw malformed(fromKey, 'registry entry does not name its own key');
|
|
170
|
+
await view.put(toKey, { ...r, leafKey: toKey });
|
|
171
|
+
await view.delete(fromKey);
|
|
172
|
+
return true;
|
|
173
|
+
}
|