@kokuin/vault 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/records.js ADDED
@@ -0,0 +1,301 @@
1
+ import { nobleCrypto } from '@kokuin/crypto';
2
+ import { parseCanonicalHLC, recordPayloadDigest } from '@kokuin/records';
3
+ import { normalizeDID } from '@kokuin/token';
4
+ import { canonicalStringify, fromB64U, fromUTF, toB64U, toUTF } from '@sozai/codec';
5
+ import { createVaultKeyID } from './id.js';
6
+ export const VAULT_OP_KIND = 'kokuin/vault-op/v1';
7
+ export const VAULT_RECORD_TYPES = [
8
+ 'vault.key',
9
+ 'vault.key-branch',
10
+ 'vault.wrapping',
11
+ 'vault.entry',
12
+ 'vault.revocation'
13
+ ];
14
+ export class VaultRecordPayloadError extends Error {
15
+ #type;
16
+ #id;
17
+ constructor(params){
18
+ const { type, id, reason, cause } = params;
19
+ super(`Vault record ${type} ${id}: ${reason}`, {
20
+ cause
21
+ });
22
+ this.name = 'VaultRecordPayloadError';
23
+ this.#type = type;
24
+ this.#id = id;
25
+ }
26
+ get type() {
27
+ return this.#type;
28
+ }
29
+ get id() {
30
+ return this.#id;
31
+ }
32
+ }
33
+ export function vaultRevocationRecordID({ recipientDID, keyID }) {
34
+ return `${keyID.length}:${keyID}/${normalizeDID(recipientDID)}`;
35
+ }
36
+ function plain(value) {
37
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
38
+ const prototype = Object.getPrototypeOf(value);
39
+ return prototype === Object.prototype || prototype === null;
40
+ }
41
+ const text = (value)=>typeof value === 'string' && value !== '';
42
+ const count = (value)=>{
43
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
44
+ };
45
+ function did(value) {
46
+ try {
47
+ return typeof value === 'string' && normalizeDID(value) === value;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+ function base64(value, length) {
53
+ try {
54
+ return typeof value === 'string' && fromB64U(value).length === length && toB64U(fromB64U(value)) === value;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ function keyID(value) {
60
+ if (typeof value !== 'string' || !/^k[0-9a-z]+$/.test(value) || value.length > 57) return false;
61
+ let integer = 0n;
62
+ for (const character of value.slice(1))integer = integer * 36n + BigInt(Number.parseInt(character, 36));
63
+ const hex = integer.toString(16);
64
+ return hex.length === 72 && hex.startsWith('b6011f20') && `k${integer.toString(36)}` === value;
65
+ }
66
+ function shape(value, required, optional = {}) {
67
+ 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]));
68
+ }
69
+ const consumer = {
70
+ consumer: (_value)=>true
71
+ };
72
+ const branch = {
73
+ branchID: text,
74
+ branchRecordID: (v)=>base64(v, 32)
75
+ };
76
+ const entryMetadata = {
77
+ kind: text,
78
+ label: (v)=>typeof v === 'string',
79
+ attributes: (v)=>{
80
+ return plain(v) && Object.values(v).every((value)=>typeof value === 'string');
81
+ }
82
+ };
83
+ /** Structural metadata only. Consumer evidence is checked by the injected validator. */ export function parseVaultRecordMeta(type, claim) {
84
+ if (claim.type !== type || !plain(claim.meta)) return null;
85
+ const m = claim.meta;
86
+ let valid;
87
+ switch(type){
88
+ case 'vault.key':
89
+ valid = shape(m, {
90
+ keyID,
91
+ keyUnique: (v)=>base64(v, 16),
92
+ version: count,
93
+ state: (v)=>claim.deleted ? v === 'deleted' : v === 'active' || v === 'retired',
94
+ ...consumer
95
+ }) && m.keyID === claim.id;
96
+ break;
97
+ case 'vault.key-branch':
98
+ valid = !claim.deleted && shape(m, {
99
+ keyID,
100
+ keyVersion: count,
101
+ branchID: text,
102
+ ...consumer
103
+ });
104
+ break;
105
+ case 'vault.wrapping':
106
+ valid = shape(m, {
107
+ keyID,
108
+ keyVersion: count,
109
+ recipient: (v)=>v === null || did(v),
110
+ ...consumer,
111
+ ...claim.deleted ? {} : branch
112
+ }, claim.deleted ? branch : {}) && Object.hasOwn(m, 'branchID') === Object.hasOwn(m, 'branchRecordID');
113
+ break;
114
+ case 'vault.entry':
115
+ valid = shape(m, {
116
+ keyID,
117
+ keyVersion: count,
118
+ contentHLC: (v)=>typeof v === 'string' && parseCanonicalHLC(v) !== null,
119
+ ...consumer,
120
+ ...claim.deleted ? {} : {
121
+ ...branch,
122
+ ...entryMetadata
123
+ }
124
+ }, claim.deleted ? {
125
+ ...branch,
126
+ ...entryMetadata
127
+ } : {}) && Object.hasOwn(m, 'branchID') === Object.hasOwn(m, 'branchRecordID');
128
+ break;
129
+ case 'vault.revocation':
130
+ valid = !claim.deleted && shape(m, {
131
+ keyID,
132
+ revokedDID: did,
133
+ ...consumer
134
+ }) && claim.id === vaultRevocationRecordID({
135
+ keyID: m.keyID,
136
+ recipientDID: m.revokedDID
137
+ });
138
+ break;
139
+ default:
140
+ return null;
141
+ }
142
+ return valid ? m : null;
143
+ }
144
+ export async function vaultRecordMeta({ claim, type, ...options }) {
145
+ const { id, owner } = claim;
146
+ const parsed = parseVaultRecordMeta(type, claim);
147
+ if (parsed === null) return null;
148
+ const meta = JSON.parse(JSON.stringify(parsed));
149
+ if (type === 'vault.key') {
150
+ const key = meta;
151
+ if (await createVaultKeyID({
152
+ ...options,
153
+ owner,
154
+ unique: fromB64U(key.keyUnique)
155
+ }) !== id) return null;
156
+ }
157
+ return meta;
158
+ }
159
+ function wire(type, payload) {
160
+ if (type === 'vault.wrapping') {
161
+ const { descriptors, descriptorDigest, iv, wrappedKey } = payload;
162
+ return {
163
+ descriptors,
164
+ descriptorDigest,
165
+ iv: toB64U(iv),
166
+ wrappedKey: toB64U(wrappedKey)
167
+ };
168
+ }
169
+ if (type === 'vault.entry') {
170
+ const { iv, ciphertext } = payload;
171
+ return {
172
+ iv: toB64U(iv),
173
+ ciphertext: toB64U(ciphertext)
174
+ };
175
+ }
176
+ return payload;
177
+ }
178
+ export function encodeVaultRecordPayload({ payload, type }) {
179
+ return fromUTF(canonicalStringify(wire(type, payload)));
180
+ }
181
+ function bytes(value) {
182
+ if (typeof value !== 'string') throw new Error('binary field is not a string');
183
+ const decoded = fromB64U(value);
184
+ if (toB64U(decoded) !== value) throw new Error('binary field is not canonical base64url');
185
+ return decoded;
186
+ }
187
+ const anything = (_value)=>true;
188
+ function payloadOf(type, data) {
189
+ const parsed = JSON.parse(toUTF(data));
190
+ if (!plain(parsed)) throw new Error('payload is not an object');
191
+ const canonical = fromUTF(canonicalStringify(parsed));
192
+ if (canonical.length !== data.length || canonical.some((v, i)=>v !== data[i])) throw new Error('payload is not canonical JSON');
193
+ switch(type){
194
+ case 'vault.key':
195
+ if (!shape(parsed, {
196
+ suite: count,
197
+ state: (v)=>v === 'active' || v === 'retired'
198
+ })) throw new Error('key payload fields');
199
+ return parsed;
200
+ case 'vault.key-branch':
201
+ if (!shape(parsed, {
202
+ authorDID: did,
203
+ hlc: text,
204
+ opJWT: text,
205
+ opHash: (v)=>base64(v, 32),
206
+ suite: count
207
+ })) throw new Error('branch payload fields');
208
+ return parsed;
209
+ case 'vault.wrapping':
210
+ {
211
+ if (!shape(parsed, {
212
+ descriptors: (v)=>{
213
+ return Array.isArray(v) && v.every((factor)=>plain(factor) && shape(factor, {
214
+ kind: text,
215
+ params: plain
216
+ }));
217
+ },
218
+ descriptorDigest: (v)=>base64(v, 32),
219
+ iv: anything,
220
+ wrappedKey: anything
221
+ })) throw new Error('wrapping payload fields');
222
+ return {
223
+ descriptors: parsed.descriptors,
224
+ descriptorDigest: parsed.descriptorDigest,
225
+ iv: bytes(parsed.iv),
226
+ wrappedKey: bytes(parsed.wrappedKey)
227
+ };
228
+ }
229
+ case 'vault.entry':
230
+ if (!shape(parsed, {
231
+ iv: anything,
232
+ ciphertext: anything
233
+ })) throw new Error('entry payload fields');
234
+ return {
235
+ iv: bytes(parsed.iv),
236
+ ciphertext: bytes(parsed.ciphertext)
237
+ };
238
+ case 'vault.revocation':
239
+ if (!shape(parsed, {})) throw new Error('revocation payload fields');
240
+ return {};
241
+ }
242
+ }
243
+ export async function decodeVaultRecord({ recordMeta, record, ...options }) {
244
+ const { type, id, owner, hlc } = record;
245
+ const captured = {
246
+ crypto: options.crypto ?? nobleCrypto
247
+ };
248
+ const payload = record.payload === null ? null : new Uint8Array(record.payload);
249
+ let meta;
250
+ try {
251
+ meta = JSON.parse(JSON.stringify(recordMeta));
252
+ } catch (cause) {
253
+ // biome-ignore lint/style/useErrorCause: the constructor carries cause in its parameter object
254
+ throw new VaultRecordPayloadError({
255
+ type,
256
+ id,
257
+ reason: cause instanceof Error ? cause.message : 'invalid record',
258
+ cause
259
+ });
260
+ }
261
+ const payloadDigest = payload === null ? null : await recordPayloadDigest({
262
+ ...captured,
263
+ payload
264
+ });
265
+ const recordType = type;
266
+ const decodedMeta = VAULT_RECORD_TYPES.includes(type) ? await vaultRecordMeta({
267
+ ...captured,
268
+ type: recordType,
269
+ claim: {
270
+ type,
271
+ id,
272
+ owner,
273
+ hlc,
274
+ meta,
275
+ deleted: false,
276
+ payloadDigest
277
+ }
278
+ }) : null;
279
+ try {
280
+ if (!VAULT_RECORD_TYPES.includes(type)) throw new Error('unknown record type');
281
+ if (payload === null) throw new Error('a tombstone has no payload');
282
+ if (decodedMeta === null) throw new Error('record metadata');
283
+ if (type === 'vault.key-branch' && id !== payloadDigest) throw new Error('record id is not the payload digest');
284
+ return {
285
+ type,
286
+ id,
287
+ owner,
288
+ hlc,
289
+ meta: decodedMeta,
290
+ payload: payloadOf(recordType, payload)
291
+ };
292
+ } catch (cause) {
293
+ // biome-ignore lint/style/useErrorCause: the constructor carries cause in its parameter object
294
+ throw new VaultRecordPayloadError({
295
+ type,
296
+ id,
297
+ reason: cause instanceof Error ? cause.message : 'invalid record',
298
+ cause
299
+ });
300
+ }
301
+ }
package/lib/suite.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ import type { CryptoOptions, KeyAgreementIdentity, MethodRegistry } from '@kokuin/token';
2
+ import type { Runtime } from '@sozai/runtime';
3
+ import type { FactorDescriptor } from './factors.js';
4
+ /** X25519 / HKDF-SHA256 / Argon2id / A256GCM. */
5
+ export declare const SUITE_VAULT_1 = 1;
6
+ export type Argon2Cost = {
7
+ m: number;
8
+ t: number;
9
+ p: number;
10
+ };
11
+ /** Memory KiB, passes, lanes. Costs are per wrapping, independent of suite version. */
12
+ export declare const DEFAULT_ARGON2_COST: Argon2Cost;
13
+ export type SecretFactorKind = 'passphrase' | 'pin';
14
+ export type FactorInput = {
15
+ kind: 'did';
16
+ recipientDID: string;
17
+ } | {
18
+ kind: SecretFactorKind;
19
+ input: Uint8Array;
20
+ cost?: Argon2Cost;
21
+ };
22
+ export type FactorInputs = Partial<Record<SecretFactorKind, Uint8Array>>;
23
+ export type VaultSuite = {
24
+ id: number;
25
+ name: string;
26
+ generateContentKey(runtime: Runtime): Uint8Array;
27
+ wrap(params: WrapParams): Promise<WrapResult>;
28
+ unwrap(params: UnwrapParams): Promise<Uint8Array>;
29
+ encryptEntry(params: EncryptEntryParams): EncryptEntryResult;
30
+ decryptEntry(params: DecryptEntryParams): Uint8Array;
31
+ };
32
+ export type WrapParams = CryptoOptions & {
33
+ runtime: Runtime;
34
+ contentKey: Uint8Array;
35
+ factors: Array<FactorInput>;
36
+ wrappingID: string;
37
+ keyID: string;
38
+ keyVersion: number;
39
+ methods?: MethodRegistry;
40
+ };
41
+ export type EncryptEntryResult = {
42
+ iv: Uint8Array;
43
+ ciphertext: Uint8Array;
44
+ };
45
+ export type WrapResult = {
46
+ descriptorDigest: string;
47
+ descriptors: Array<FactorDescriptor>;
48
+ iv: Uint8Array;
49
+ wrappedKey: Uint8Array;
50
+ };
51
+ export type UnwrapParams = CryptoOptions & {
52
+ /** Trusted local state or authenticated metadata, independent of presented descriptors. */
53
+ expectedDescriptorDigest?: string;
54
+ /** Informational digest from the presented wrapping, never used as a trust anchor. */
55
+ descriptorDigest?: string;
56
+ identity: KeyAgreementIdentity | null;
57
+ descriptors: Array<FactorDescriptor>;
58
+ inputs?: FactorInputs;
59
+ iv: Uint8Array;
60
+ wrappedKey: Uint8Array;
61
+ wrappingID: string;
62
+ keyID: string;
63
+ keyVersion: number;
64
+ };
65
+ export type EncryptEntryParams = {
66
+ runtime: Runtime;
67
+ contentKey: Uint8Array;
68
+ plaintext: Uint8Array;
69
+ keyID: string;
70
+ keyVersion: number;
71
+ entryID: string;
72
+ };
73
+ export type DecryptEntryParams = {
74
+ contentKey: Uint8Array;
75
+ iv: Uint8Array;
76
+ ciphertext: Uint8Array;
77
+ keyID: string;
78
+ keyVersion: number;
79
+ entryID: string;
80
+ };
81
+ export declare function validateFactorList(kinds: Array<string>): void;
82
+ export declare function getSuite(id: number): VaultSuite;
83
+ export declare function isSupportedSuite(id: number): boolean;
84
+ export type WrappedKey = WrapResult;
85
+ export type EncryptedEntry = EncryptEntryResult;
86
+ export type CryptoAddress = {
87
+ keyID: string;
88
+ keyVersion: number;
89
+ };