@kokuin/vault 0.0.0-stage → 0.1.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.
@@ -0,0 +1,339 @@
1
+ import { compareRecordDecisionHLC, parseCanonicalHLC, RecordContentRefusalError, recordPayloadDigest, recordPayloadMatches, verifyRecordOp, verifySignedRecord } from '@kokuin/records';
2
+ import { normalizeDID } from '@kokuin/token';
3
+ import { decodeVaultRecord, encodeVaultRecordPayload, VAULT_RECORD_TYPES, vaultRecordMeta } from './records.js';
4
+ const KEY = 'vault.key';
5
+ const BRANCH = 'vault.key-branch';
6
+ const WRAPPING = 'vault.wrapping';
7
+ const ENTRY = 'vault.entry';
8
+ const REVOCATION = 'vault.revocation';
9
+ function requestFor(op, record, store, transportContext, verb) {
10
+ const getMany = store.getMany;
11
+ const read = {
12
+ get: (key)=>store.get(key),
13
+ list: (types)=>store.list(types),
14
+ ...getMany === undefined ? {} : {
15
+ getMany: (keys)=>getMany.call(store, keys)
16
+ }
17
+ };
18
+ return {
19
+ source: 'record',
20
+ op,
21
+ owner: op.claim.owner,
22
+ issuer: op.issuer,
23
+ verb,
24
+ recordKey: {
25
+ type: op.claim.type,
26
+ owner: op.claim.owner,
27
+ id: op.claim.id
28
+ },
29
+ transportContext,
30
+ record,
31
+ store: read
32
+ };
33
+ }
34
+ async function authorized(params, request) {
35
+ return await params.validateConsumerMetadata(request.op.claim.meta.consumer, request) && await params.authority.authorize(request);
36
+ }
37
+ function entryOrder(claim) {
38
+ const meta = vaultRecordMeta(ENTRY, claim);
39
+ const stamp = meta === null ? null : parseCanonicalHLC(meta.contentHLC);
40
+ if (meta === null || stamp === null) throw new RecordContentRefusalError('Entry content stamp is malformed');
41
+ const node = Array.from({
42
+ length: stamp.nodeID.length
43
+ }, (_, i)=>stamp.nodeID.charCodeAt(i));
44
+ return [
45
+ stamp.wallTime,
46
+ stamp.counter,
47
+ ...node,
48
+ -1,
49
+ meta.keyVersion
50
+ ];
51
+ }
52
+ function keyOrder(claim) {
53
+ const meta = vaultRecordMeta(KEY, claim);
54
+ if (meta === null) throw new RecordContentRefusalError('Key metadata is malformed');
55
+ return [
56
+ meta.version,
57
+ claim.deleted ? 2 : meta.state === 'retired' ? 1 : 0
58
+ ];
59
+ }
60
+ function validStructure(type, op) {
61
+ const meta = vaultRecordMeta(type, op.claim);
62
+ if (meta === null) return false;
63
+ if (type === ENTRY) {
64
+ const entry = vaultRecordMeta(ENTRY, op.claim);
65
+ return entry !== null && parseCanonicalHLC(op.claim.hlc) !== null && compareRecordDecisionHLC(entry.contentHLC, op.claim.hlc) <= 0;
66
+ }
67
+ return true;
68
+ }
69
+ function decodedAs(record, op, type) {
70
+ if (op.claim.deleted || !recordPayloadMatches(record, op.claim)) return null;
71
+ try {
72
+ const decoded = decodeVaultRecord(record, op.claim.meta);
73
+ return decoded.type === type ? decoded : null;
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+ function keyAtLeast(owner, keyID, version) {
79
+ return {
80
+ type: KEY,
81
+ owner,
82
+ id: keyID,
83
+ satisfiedBy: (op)=>{
84
+ const meta = vaultRecordMeta(KEY, op.claim);
85
+ return op.claim.owner === owner && meta !== null && meta.version >= version;
86
+ }
87
+ };
88
+ }
89
+ function exactBranch(op, meta) {
90
+ return {
91
+ type: BRANCH,
92
+ owner: op.claim.owner,
93
+ id: meta.branchRecordID,
94
+ satisfiedBy: (branch)=>{
95
+ const info = vaultRecordMeta(BRANCH, branch.claim);
96
+ return info !== null && branch.claim.owner === op.claim.owner && !branch.claim.deleted && info.keyID === meta.keyID && info.keyVersion === meta.keyVersion && info.branchID === meta.branchID;
97
+ }
98
+ };
99
+ }
100
+ function dependencies(type, op) {
101
+ if (type === KEY) return [];
102
+ const meta = vaultRecordMeta(type, op.claim);
103
+ if (meta === null) return [];
104
+ const key = {
105
+ type: KEY,
106
+ owner: op.claim.owner,
107
+ id: meta.keyID
108
+ };
109
+ if (type === REVOCATION) return [
110
+ key
111
+ ];
112
+ const version = op.claim.meta.keyVersion;
113
+ if (type === BRANCH) return [
114
+ keyAtLeast(op.claim.owner, meta.keyID, version)
115
+ ];
116
+ const result = [
117
+ type === WRAPPING && op.claim.deleted ? key : keyAtLeast(op.claim.owner, meta.keyID, version)
118
+ ];
119
+ if (type === WRAPPING && op.claim.deleted) return result;
120
+ const { branchID, branchRecordID } = op.claim.meta;
121
+ if (typeof branchID === 'string' && typeof branchRecordID === 'string') result.push(exactBranch(op, {
122
+ keyID: meta.keyID,
123
+ keyVersion: version,
124
+ branchID,
125
+ branchRecordID
126
+ }));
127
+ return result;
128
+ }
129
+ async function keyOwnerMatches(params, op, ctx) {
130
+ // Apply serves the chunk's batched view. Holder proofs outside apply read the store.
131
+ const read = ctx.decision ?? ((key)=>ctx.store.get(key));
132
+ const decision = await read({
133
+ type: KEY,
134
+ owner: op.claim.owner,
135
+ id: op.claim.meta.keyID
136
+ });
137
+ if (decision === null) return false;
138
+ // Verification never throws, so the copies are verified together.
139
+ const keys = await Promise.all(decision.copies.map((record)=>verifySignedRecord(record, params.opKind, params.methods)));
140
+ return keys.some((key)=>{
141
+ return key !== null && vaultRecordMeta(KEY, key.claim) !== null && key.claim.owner === op.claim.owner;
142
+ });
143
+ }
144
+ async function revoked(params, op, store, descriptors) {
145
+ const denied = new Set((await params.portsFor(store).listRevocations({
146
+ ownerDID: op.claim.owner,
147
+ keyID: op.claim.meta.keyID
148
+ })).map((did)=>normalizeDID(did)));
149
+ const recipients = [
150
+ op.claim.meta.recipient,
151
+ ...descriptors.filter((d)=>d.kind === 'did').map((d)=>d.params.recipient)
152
+ ];
153
+ for (const recipient of recipients){
154
+ if (recipient === null || recipient === undefined) continue;
155
+ if (typeof recipient !== 'string') return true;
156
+ try {
157
+ if (denied.has(normalizeDID(recipient))) return true;
158
+ } catch {
159
+ return true;
160
+ }
161
+ }
162
+ return false;
163
+ }
164
+ async function authorizeBranch(params, op, ctx) {
165
+ const meta = vaultRecordMeta(BRANCH, op.claim);
166
+ const decoded = decodedAs(ctx.record, op, BRANCH);
167
+ if (meta === null || decoded === null) return false;
168
+ const payload = decoded.payload;
169
+ const introducing = await verifyRecordOp(payload.opJWT, params.opKind, params.methods);
170
+ const key = introducing === null ? null : vaultRecordMeta(KEY, introducing.claim);
171
+ if (introducing === null || key === null || introducing.claim.deleted || introducing.claim.id !== meta.keyID || introducing.claim.owner !== op.claim.owner || key.version !== meta.keyVersion || introducing.opHash !== payload.opHash || introducing.claim.hlc !== payload.hlc || introducing.issuer !== normalizeDID(payload.authorDID) || meta.branchID !== `${payload.hlc}:${payload.opHash}`) return false;
172
+ const keyPayload = encodeVaultRecordPayload(KEY, {
173
+ suite: payload.suite,
174
+ state: key.state
175
+ });
176
+ if (introducing.claim.payloadDigest !== recordPayloadDigest(keyPayload)) return false;
177
+ // The embedded op is independent authenticated evidence and gets its own consumer decision.
178
+ const keyRecord = {
179
+ type: KEY,
180
+ id: introducing.claim.id,
181
+ owner: introducing.claim.owner,
182
+ hlc: introducing.claim.hlc,
183
+ payload: keyPayload,
184
+ opJWT: payload.opJWT,
185
+ opHash: introducing.opHash
186
+ };
187
+ return await authorized(params, requestFor(introducing, keyRecord, ctx.store, ctx.transportContext, 'administer')) && await authorized(params, requestFor(op, ctx.record, ctx.store, ctx.transportContext, 'administer'));
188
+ }
189
+ function createType(type, params, bindReceiver = true) {
190
+ const definition = {
191
+ type,
192
+ policy: type === KEY ? {
193
+ kind: 'monotonic',
194
+ version: keyOrder
195
+ } : type === ENTRY ? {
196
+ kind: 'monotonic',
197
+ version: entryOrder
198
+ } : type === BRANCH ? {
199
+ kind: 'immutable'
200
+ } : {
201
+ kind: 'lww'
202
+ },
203
+ dependsOn: type === KEY ? [] : type === ENTRY || type === WRAPPING ? [
204
+ KEY,
205
+ BRANCH
206
+ ] : [
207
+ KEY
208
+ ],
209
+ precheck: async (op)=>validStructure(type, op),
210
+ dependencies: (_record, op)=>dependencies(type, op),
211
+ async authorize (op, ctx) {
212
+ // Enforce the factory's replay domain even when the engine is misconfigured.
213
+ const checked = await verifySignedRecord(ctx.record, params.opKind, params.methods);
214
+ if (checked === null || checked.opHash !== op.opHash) return false;
215
+ if (!validStructure(type, op) || !recordPayloadMatches(ctx.record, op.claim)) return false;
216
+ if (type !== KEY && !await keyOwnerMatches(params, op, ctx)) return false;
217
+ if (type === BRANCH) return await authorizeBranch(params, op, ctx);
218
+ if (!op.claim.deleted) {
219
+ const decoded = decodedAs(ctx.record, op, type);
220
+ if (decoded === null) return false;
221
+ if (decoded.type === KEY && decoded.payload.state !== op.claim.meta.state) return false;
222
+ if (decoded.type === WRAPPING && await revoked(params, op, ctx.store, decoded.payload.descriptors)) return false;
223
+ }
224
+ if (!await authorized(params, requestFor(op, ctx.record, ctx.store, ctx.transportContext, 'administer'))) return false;
225
+ return type !== WRAPPING || !bindReceiver || await authorized(params, requestFor(op, ctx.record, ctx.store, ctx.transportContext, 'read'));
226
+ },
227
+ async visibleTo (record, ctx) {
228
+ if (ctx.opKind !== params.opKind) return false;
229
+ const op = await verifySignedRecord(record, params.opKind, params.methods);
230
+ if (op === null || !validStructure(type, op) || !recordPayloadMatches(record, op.claim)) return false;
231
+ if (!op.claim.deleted) {
232
+ const decoded = decodedAs(record, op, type);
233
+ if (decoded === null) return false;
234
+ if (decoded.type === WRAPPING && await revoked(params, op, ctx.store, decoded.payload.descriptors)) return false;
235
+ }
236
+ return await authorized(params, requestFor(op, record, ctx.store, ctx.transportContext, 'read'));
237
+ },
238
+ async lockKeys (incoming, stored) {
239
+ const keys = new Map();
240
+ const records = [
241
+ incoming,
242
+ ...stored?.copies ?? []
243
+ ];
244
+ const ops = await Promise.all(records.map((record)=>verifySignedRecord(record, params.opKind, params.methods)));
245
+ for (const op of ops){
246
+ if (op === null) continue;
247
+ const keyID = op.claim.type === KEY ? op.claim.id : op.claim.meta.keyID;
248
+ if (typeof keyID !== 'string' || keyID === '') continue;
249
+ const key = JSON.stringify([
250
+ op.claim.owner,
251
+ keyID
252
+ ]);
253
+ keys.set(key, {
254
+ type: KEY,
255
+ key
256
+ });
257
+ }
258
+ return [
259
+ ...keys.values()
260
+ ];
261
+ }
262
+ };
263
+ if (type === KEY) {
264
+ // Equal-version branches remain independently proven; the current head uses claim digest.
265
+ definition.onEqual = ()=>'fork';
266
+ }
267
+ if (type === ENTRY) {
268
+ definition.afterAuthorize = async (record, store)=>{
269
+ await params.portsFor(store).retainEntryCandidate(record);
270
+ };
271
+ }
272
+ if (type === WRAPPING || type === REVOCATION) {
273
+ definition.afterApply = async (record, store)=>{
274
+ const op = await verifySignedRecord(record, params.opKind, params.methods);
275
+ if (op === null) throw new Error('Applied record signature is invalid');
276
+ await params.portsFor(store).dropRevokedWrappings({
277
+ ownerDID: op.claim.owner,
278
+ keyID: op.claim.meta.keyID
279
+ });
280
+ };
281
+ }
282
+ return definition;
283
+ }
284
+ /** One explicit replay domain and consumer policy for the five generic record types. */ export function vaultRecordTypes(params) {
285
+ if (typeof params.opKind !== 'string' || params.opKind.length === 0) throw new TypeError('An explicit operation kind is required');
286
+ return new Map(VAULT_RECORD_TYPES.map((type)=>[
287
+ type,
288
+ createType(type, params)
289
+ ]));
290
+ }
291
+ /** Only wrappings can prove key holding, regardless of other records' metadata. */ export function vaultHolderTypes(types) {
292
+ const wrapping = types.get(WRAPPING);
293
+ return new Map(wrapping === undefined ? [] : [
294
+ [
295
+ WRAPPING,
296
+ wrapping
297
+ ]
298
+ ]);
299
+ }
300
+ /** Read a live, owner-qualified key version in the explicit replay domain. */ export function vaultKeyVersionReader(store, params) {
301
+ return async (owner, keyID)=>{
302
+ const stored = await store.get({
303
+ type: KEY,
304
+ owner,
305
+ id: keyID
306
+ });
307
+ const copy = stored?.copies[0];
308
+ const op = copy === undefined ? null : await verifySignedRecord(copy, params.opKind, params.methods);
309
+ const meta = op === null ? null : vaultRecordMeta(KEY, op.claim);
310
+ return op === null || meta === null || op.claim.deleted || op.claim.owner !== owner ? null : meta.version;
311
+ };
312
+ }
313
+ // One proof definition per params object. It closes over `params` only and keeps no state.
314
+ const proofTypes = new WeakMap();
315
+ function proofTypeFor(params) {
316
+ let definition = proofTypes.get(params);
317
+ if (definition === undefined) {
318
+ definition = createType(WRAPPING, params, false);
319
+ proofTypes.set(params, definition);
320
+ }
321
+ return definition;
322
+ }
323
+ /** Proofs retain consumer authority checks but are never addressed to the local receiver. */ export function vaultProofAuthorizer(params, store, transportContext) {
324
+ const wrapping = proofTypeFor(params);
325
+ return async (record, stored)=>{
326
+ if (record.type !== WRAPPING) return false;
327
+ const op = await verifySignedRecord(record, params.opKind, params.methods);
328
+ if (op === null) return false;
329
+ return await wrapping.authorize(op, {
330
+ record,
331
+ stored,
332
+ store,
333
+ transportContext,
334
+ // Generic vault policy delegates all authority to the consumer callback.
335
+ resolveController: async ()=>null,
336
+ verifyCapability: async ()=>false
337
+ });
338
+ };
339
+ }
@@ -0,0 +1,91 @@
1
+ import type { RecordClaim, SignedRecord } from '@kokuin/records';
2
+ import type { EncryptEntryResult, WrapResult } from './suite.js';
3
+ export declare const VAULT_OP_KIND = "kokuin/vault-op/v1";
4
+ export declare const VAULT_RECORD_TYPES: readonly ["vault.key", "vault.key-branch", "vault.wrapping", "vault.entry", "vault.revocation"];
5
+ export type VaultRecordType = (typeof VAULT_RECORD_TYPES)[number];
6
+ export type VaultRecordPayloads = {
7
+ 'vault.key': {
8
+ suite: number;
9
+ state: 'active' | 'retired';
10
+ };
11
+ 'vault.key-branch': {
12
+ authorDID: string;
13
+ hlc: string;
14
+ opJWT: string;
15
+ opHash: string;
16
+ suite: number;
17
+ };
18
+ 'vault.wrapping': WrapResult;
19
+ 'vault.entry': EncryptEntryResult;
20
+ 'vault.revocation': Record<string, never>;
21
+ };
22
+ export type VaultEntryMetadata = {
23
+ kind: string;
24
+ label: string;
25
+ attributes: Record<string, string>;
26
+ };
27
+ type BranchReference = {
28
+ branchID: string;
29
+ branchRecordID: string;
30
+ };
31
+ export type VaultRecordMetas = {
32
+ 'vault.key': {
33
+ keyID: string;
34
+ keyUnique: string;
35
+ version: number;
36
+ state: 'active' | 'retired' | 'deleted';
37
+ consumer: unknown;
38
+ };
39
+ 'vault.key-branch': {
40
+ keyID: string;
41
+ keyVersion: number;
42
+ branchID: string;
43
+ consumer: unknown;
44
+ };
45
+ 'vault.wrapping': {
46
+ keyID: string;
47
+ keyVersion: number;
48
+ recipient: string | null;
49
+ consumer: unknown;
50
+ } & Partial<BranchReference>;
51
+ 'vault.entry': {
52
+ keyID: string;
53
+ keyVersion: number;
54
+ contentHLC: string;
55
+ consumer: unknown;
56
+ } & Partial<BranchReference> & Partial<VaultEntryMetadata>;
57
+ 'vault.revocation': {
58
+ keyID: string;
59
+ revokedDID: string;
60
+ consumer: unknown;
61
+ };
62
+ };
63
+ export type DecodedVaultRecord = {
64
+ [Type in VaultRecordType]: {
65
+ type: Type;
66
+ id: string;
67
+ owner: string;
68
+ hlc: string;
69
+ meta: VaultRecordMetas[Type];
70
+ payload: VaultRecordPayloads[Type];
71
+ };
72
+ }[VaultRecordType];
73
+ export declare class VaultRecordPayloadError extends Error {
74
+ #private;
75
+ constructor(params: {
76
+ type: string;
77
+ id: string;
78
+ reason: string;
79
+ cause?: unknown;
80
+ });
81
+ get type(): string;
82
+ get id(): string;
83
+ }
84
+ export declare function vaultRevocationRecordID(keyID: string, recipientDID: string): string;
85
+ /** Structural metadata only. Consumer evidence is checked by the injected validator. */
86
+ export declare function vaultRecordMeta<Type extends VaultRecordType>(type: Type, claim: RecordClaim): VaultRecordMetas[Type] | null;
87
+ /** Canonical JSON with binary fields encoded as unpadded base64url. */
88
+ export declare function encodeVaultRecordPayload<Type extends VaultRecordType>(type: Type, payload: VaultRecordPayloads[Type]): Uint8Array;
89
+ /** Pure codec. Signature and payload-digest verification belong to the caller. */
90
+ export declare function decodeVaultRecord(record: Pick<SignedRecord, 'type' | 'id' | 'owner' | 'hlc' | 'payload'>, meta: Record<string, unknown>): DecodedVaultRecord;
91
+ export {};
package/lib/records.js ADDED
@@ -0,0 +1,258 @@
1
+ import { parseCanonicalHLC, recordPayloadDigest } from '@kokuin/records';
2
+ import { normalizeDID } from '@kokuin/token';
3
+ import { canonicalStringify, fromB64U, fromUTF, toB64U, toUTF } from '@sozai/codec';
4
+ import { createVaultKeyID } from './id.js';
5
+ export const VAULT_OP_KIND = 'kokuin/vault-op/v1';
6
+ export const VAULT_RECORD_TYPES = [
7
+ 'vault.key',
8
+ 'vault.key-branch',
9
+ 'vault.wrapping',
10
+ 'vault.entry',
11
+ 'vault.revocation'
12
+ ];
13
+ export class VaultRecordPayloadError extends Error {
14
+ #type;
15
+ #id;
16
+ constructor(params){
17
+ const { type, id, reason, cause } = params;
18
+ super(`Vault record ${type} ${id}: ${reason}`, {
19
+ cause
20
+ });
21
+ this.name = 'VaultRecordPayloadError';
22
+ this.#type = type;
23
+ this.#id = id;
24
+ }
25
+ get type() {
26
+ return this.#type;
27
+ }
28
+ get id() {
29
+ return this.#id;
30
+ }
31
+ }
32
+ export function vaultRevocationRecordID(keyID, recipientDID) {
33
+ return `${keyID.length}:${keyID}/${normalizeDID(recipientDID)}`;
34
+ }
35
+ function plain(value) {
36
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
37
+ const prototype = Object.getPrototypeOf(value);
38
+ return prototype === Object.prototype || prototype === null;
39
+ }
40
+ const text = (value)=>typeof value === 'string' && value !== '';
41
+ const count = (value)=>{
42
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
43
+ };
44
+ function did(value) {
45
+ try {
46
+ return typeof value === 'string' && normalizeDID(value) === value;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+ function base64(value, length) {
52
+ try {
53
+ return typeof value === 'string' && fromB64U(value).length === length && toB64U(fromB64U(value)) === value;
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+ function keyID(value) {
59
+ if (typeof value !== 'string' || !/^k[0-9a-z]+$/.test(value) || value.length > 57) return false;
60
+ let integer = 0n;
61
+ for (const character of value.slice(1))integer = integer * 36n + BigInt(Number.parseInt(character, 36));
62
+ const hex = integer.toString(16);
63
+ return hex.length === 72 && hex.startsWith('b6011f20') && `k${integer.toString(36)}` === value;
64
+ }
65
+ function shape(value, required, optional = {}) {
66
+ return Object.keys(value).every((k)=>Object.hasOwn(required, k) || Object.hasOwn(optional, k)) && Object.entries(required).every(([k, check])=>Object.hasOwn(value, k) && check(value[k])) && Object.entries(optional).every(([k, check])=>!Object.hasOwn(value, k) || check(value[k]));
67
+ }
68
+ const consumer = {
69
+ consumer: (_value)=>true
70
+ };
71
+ const branch = {
72
+ branchID: text,
73
+ branchRecordID: (v)=>base64(v, 32)
74
+ };
75
+ const entryMetadata = {
76
+ kind: text,
77
+ label: (v)=>typeof v === 'string',
78
+ attributes: (v)=>{
79
+ return plain(v) && Object.values(v).every((value)=>typeof value === 'string');
80
+ }
81
+ };
82
+ /** Structural metadata only. Consumer evidence is checked by the injected validator. */ export function vaultRecordMeta(type, claim) {
83
+ if (claim.type !== type || !plain(claim.meta)) return null;
84
+ const m = claim.meta;
85
+ let valid;
86
+ switch(type){
87
+ case 'vault.key':
88
+ valid = shape(m, {
89
+ keyID,
90
+ keyUnique: (v)=>base64(v, 16),
91
+ version: count,
92
+ state: (v)=>claim.deleted ? v === 'deleted' : v === 'active' || v === 'retired',
93
+ ...consumer
94
+ }) && m.keyID === claim.id && createVaultKeyID(claim.owner, fromB64U(m.keyUnique)) === claim.id;
95
+ break;
96
+ case 'vault.key-branch':
97
+ valid = !claim.deleted && shape(m, {
98
+ keyID,
99
+ keyVersion: count,
100
+ branchID: text,
101
+ ...consumer
102
+ });
103
+ break;
104
+ case 'vault.wrapping':
105
+ valid = shape(m, {
106
+ keyID,
107
+ keyVersion: count,
108
+ recipient: (v)=>v === null || did(v),
109
+ ...consumer,
110
+ ...claim.deleted ? {} : branch
111
+ }, claim.deleted ? branch : {}) && Object.hasOwn(m, 'branchID') === Object.hasOwn(m, 'branchRecordID');
112
+ break;
113
+ case 'vault.entry':
114
+ valid = shape(m, {
115
+ keyID,
116
+ keyVersion: count,
117
+ contentHLC: (v)=>typeof v === 'string' && parseCanonicalHLC(v) !== null,
118
+ ...consumer,
119
+ ...claim.deleted ? {} : {
120
+ ...branch,
121
+ ...entryMetadata
122
+ }
123
+ }, claim.deleted ? {
124
+ ...branch,
125
+ ...entryMetadata
126
+ } : {}) && Object.hasOwn(m, 'branchID') === Object.hasOwn(m, 'branchRecordID');
127
+ break;
128
+ case 'vault.revocation':
129
+ valid = !claim.deleted && shape(m, {
130
+ keyID,
131
+ revokedDID: did,
132
+ ...consumer
133
+ }) && claim.id === vaultRevocationRecordID(m.keyID, m.revokedDID);
134
+ break;
135
+ default:
136
+ return null;
137
+ }
138
+ return valid ? m : null;
139
+ }
140
+ function wire(type, payload) {
141
+ if (type === 'vault.wrapping') {
142
+ const { descriptors, descriptorDigest, iv, wrappedKey } = payload;
143
+ return {
144
+ descriptors,
145
+ descriptorDigest,
146
+ iv: toB64U(iv),
147
+ wrappedKey: toB64U(wrappedKey)
148
+ };
149
+ }
150
+ if (type === 'vault.entry') {
151
+ const { iv, ciphertext } = payload;
152
+ return {
153
+ iv: toB64U(iv),
154
+ ciphertext: toB64U(ciphertext)
155
+ };
156
+ }
157
+ return payload;
158
+ }
159
+ /** Canonical JSON with binary fields encoded as unpadded base64url. */ export function encodeVaultRecordPayload(type, payload) {
160
+ return fromUTF(canonicalStringify(wire(type, payload)));
161
+ }
162
+ function bytes(value) {
163
+ if (typeof value !== 'string') throw new Error('binary field is not a string');
164
+ const decoded = fromB64U(value);
165
+ if (toB64U(decoded) !== value) throw new Error('binary field is not canonical base64url');
166
+ return decoded;
167
+ }
168
+ const anything = (_value)=>true;
169
+ function payloadOf(type, data) {
170
+ const parsed = JSON.parse(toUTF(data));
171
+ if (!plain(parsed)) throw new Error('payload is not an object');
172
+ const canonical = fromUTF(canonicalStringify(parsed));
173
+ if (canonical.length !== data.length || canonical.some((v, i)=>v !== data[i])) throw new Error('payload is not canonical JSON');
174
+ switch(type){
175
+ case 'vault.key':
176
+ if (!shape(parsed, {
177
+ suite: count,
178
+ state: (v)=>v === 'active' || v === 'retired'
179
+ })) throw new Error('key payload fields');
180
+ return parsed;
181
+ case 'vault.key-branch':
182
+ if (!shape(parsed, {
183
+ authorDID: did,
184
+ hlc: text,
185
+ opJWT: text,
186
+ opHash: (v)=>base64(v, 32),
187
+ suite: count
188
+ })) throw new Error('branch payload fields');
189
+ return parsed;
190
+ case 'vault.wrapping':
191
+ {
192
+ if (!shape(parsed, {
193
+ descriptors: (v)=>{
194
+ return Array.isArray(v) && v.every((factor)=>plain(factor) && shape(factor, {
195
+ kind: text,
196
+ params: plain
197
+ }));
198
+ },
199
+ descriptorDigest: (v)=>base64(v, 32),
200
+ iv: anything,
201
+ wrappedKey: anything
202
+ })) throw new Error('wrapping payload fields');
203
+ return {
204
+ descriptors: parsed.descriptors,
205
+ descriptorDigest: parsed.descriptorDigest,
206
+ iv: bytes(parsed.iv),
207
+ wrappedKey: bytes(parsed.wrappedKey)
208
+ };
209
+ }
210
+ case 'vault.entry':
211
+ if (!shape(parsed, {
212
+ iv: anything,
213
+ ciphertext: anything
214
+ })) throw new Error('entry payload fields');
215
+ return {
216
+ iv: bytes(parsed.iv),
217
+ ciphertext: bytes(parsed.ciphertext)
218
+ };
219
+ case 'vault.revocation':
220
+ if (!shape(parsed, {})) throw new Error('revocation payload fields');
221
+ return {};
222
+ }
223
+ }
224
+ /** Pure codec. Signature and payload-digest verification belong to the caller. */ export function decodeVaultRecord(record, meta) {
225
+ const { type, id, owner, hlc, payload } = record;
226
+ try {
227
+ if (!VAULT_RECORD_TYPES.includes(type)) throw new Error('unknown record type');
228
+ if (payload === null) throw new Error('a tombstone has no payload');
229
+ const recordType = type;
230
+ const decodedMeta = vaultRecordMeta(recordType, {
231
+ type,
232
+ id,
233
+ owner,
234
+ hlc,
235
+ meta,
236
+ deleted: false,
237
+ payloadDigest: recordPayloadDigest(payload)
238
+ });
239
+ if (decodedMeta === null) throw new Error('record metadata');
240
+ if (type === 'vault.key-branch' && id !== recordPayloadDigest(payload)) throw new Error('record id is not the payload digest');
241
+ return {
242
+ type,
243
+ id,
244
+ owner,
245
+ hlc,
246
+ meta: decodedMeta,
247
+ payload: payloadOf(recordType, payload)
248
+ };
249
+ } catch (cause) {
250
+ // biome-ignore lint/style/useErrorCause: the constructor carries cause in its parameter object
251
+ throw new VaultRecordPayloadError({
252
+ type,
253
+ id,
254
+ reason: cause instanceof Error ? cause.message : 'invalid record',
255
+ cause
256
+ });
257
+ }
258
+ }