@tik-choco/mistvault 0.0.0-stage → 0.2.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/LICENSE +373 -0
- package/README.ja.md +126 -0
- package/README.md +183 -2
- package/README.zh.md +126 -0
- package/dist/appState.d.ts +24 -0
- package/dist/appState.js +20 -0
- package/dist/code.d.ts +7 -0
- package/dist/code.js +49 -0
- package/dist/controller.d.ts +55 -0
- package/dist/controller.js +74 -0
- package/dist/core/client.d.ts +112 -0
- package/dist/core/client.js +536 -0
- package/dist/core/crypto.d.ts +24 -0
- package/dist/core/crypto.js +185 -0
- package/dist/core/head.d.ts +54 -0
- package/dist/core/head.js +123 -0
- package/dist/core/parse.d.ts +1 -0
- package/dist/core/parse.js +1 -0
- package/dist/core/protocol.d.ts +74 -0
- package/dist/core/protocol.js +93 -0
- package/dist/i18n.d.ts +132 -0
- package/dist/i18n.js +96 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +12 -0
- package/dist/parts.d.ts +42 -0
- package/dist/parts.js +267 -0
- package/dist/preact/RoomControls.d.ts +13 -0
- package/dist/preact/RoomControls.js +12 -0
- package/dist/preact/ScopeVaultPanel.d.ts +6 -0
- package/dist/preact/ScopeVaultPanel.js +20 -0
- package/dist/preact/VaultPanel.d.ts +12 -0
- package/dist/preact/VaultPanel.js +111 -0
- package/dist/preact/index.d.ts +5 -0
- package/dist/preact/index.js +3 -0
- package/dist/preact/ui.css +131 -0
- package/dist/preact/useVault.d.ts +6 -0
- package/dist/preact/useVault.js +13 -0
- package/dist/scopeKey.d.ts +1 -0
- package/dist/scopeKey.js +49 -0
- package/dist/scopeManager.d.ts +14 -0
- package/dist/scopeManager.js +110 -0
- package/dist/scopeVault.d.ts +39 -0
- package/dist/scopeVault.js +212 -0
- package/dist/session.d.ts +44 -0
- package/dist/session.js +736 -0
- package/dist/settings.d.ts +21 -0
- package/dist/settings.js +59 -0
- package/dist/stored.d.ts +4 -0
- package/dist/stored.js +27 -0
- package/dist/transport.d.ts +20 -0
- package/dist/transport.js +117 -0
- package/package.json +52 -4
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
export const utf8 = (value) => new TextEncoder().encode(value);
|
|
2
|
+
export const hex = (bytes) => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
|
|
3
|
+
export const fromHex = (value) => {
|
|
4
|
+
if (!/^(?:[0-9a-f]{2})*$/.test(value))
|
|
5
|
+
throw new Error('Invalid hex');
|
|
6
|
+
return Uint8Array.from(value.match(/../g) ?? [], b => parseInt(b, 16));
|
|
7
|
+
};
|
|
8
|
+
export function base64url(bytes) {
|
|
9
|
+
let binary = '';
|
|
10
|
+
for (const byte of bytes)
|
|
11
|
+
binary += String.fromCharCode(byte);
|
|
12
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
13
|
+
}
|
|
14
|
+
export function fromBase64url(value) {
|
|
15
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value))
|
|
16
|
+
throw new Error('Invalid base64url');
|
|
17
|
+
const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - value.length % 4) % 4));
|
|
18
|
+
const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
|
|
19
|
+
if (base64url(bytes) !== value)
|
|
20
|
+
throw new Error('Noncanonical base64url');
|
|
21
|
+
return bytes;
|
|
22
|
+
}
|
|
23
|
+
export const sha256 = async (bytes) => hex(new Uint8Array(await crypto.subtle.digest('SHA-256', new Uint8Array(bytes))));
|
|
24
|
+
const masterCache = new Map();
|
|
25
|
+
const keyCache = new Map();
|
|
26
|
+
export function deriveEscrowKeys(app, roomId) {
|
|
27
|
+
if (typeof app !== 'string' || typeof roomId !== 'string')
|
|
28
|
+
throw new Error('Invalid escrow key inputs');
|
|
29
|
+
const cacheId = JSON.stringify([app, roomId]);
|
|
30
|
+
let pending = keyCache.get(cacheId);
|
|
31
|
+
if (!pending) {
|
|
32
|
+
pending = derive(app, roomId);
|
|
33
|
+
keyCache.set(cacheId, pending);
|
|
34
|
+
void pending.catch(() => { if (keyCache.get(cacheId) === pending)
|
|
35
|
+
keyCache.delete(cacheId); });
|
|
36
|
+
}
|
|
37
|
+
return pending;
|
|
38
|
+
}
|
|
39
|
+
function cachedMaster(app, roomId) {
|
|
40
|
+
if (typeof app !== 'string' || typeof roomId !== 'string')
|
|
41
|
+
throw new Error('Invalid escrow key inputs');
|
|
42
|
+
const id = JSON.stringify([app, roomId]);
|
|
43
|
+
let pending = masterCache.get(id);
|
|
44
|
+
if (!pending) {
|
|
45
|
+
pending = deriveMaster(app, roomId);
|
|
46
|
+
masterCache.set(id, pending);
|
|
47
|
+
void pending.catch(() => { if (masterCache.get(id) === pending)
|
|
48
|
+
masterCache.delete(id); });
|
|
49
|
+
}
|
|
50
|
+
return pending;
|
|
51
|
+
}
|
|
52
|
+
async function deriveMaster(app, roomId) {
|
|
53
|
+
const password = await crypto.subtle.importKey('raw', utf8('tc-escrow/v1\n' + app + '\n' + roomId), 'PBKDF2', false, ['deriveBits']);
|
|
54
|
+
const master = new Uint8Array(await crypto.subtle.deriveBits({
|
|
55
|
+
name: 'PBKDF2', hash: 'SHA-256', salt: utf8('tc-escrow/v1/salt'), iterations: 200000,
|
|
56
|
+
}, password, 256));
|
|
57
|
+
const ikm = await crypto.subtle.importKey('raw', master, 'HKDF', false, ['deriveBits']);
|
|
58
|
+
master.fill(0);
|
|
59
|
+
return ikm;
|
|
60
|
+
}
|
|
61
|
+
async function hkdf(ikm, name, bits) {
|
|
62
|
+
return new Uint8Array(await crypto.subtle.deriveBits({
|
|
63
|
+
name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: utf8('tc-escrow/v1/' + name),
|
|
64
|
+
}, ikm, bits));
|
|
65
|
+
}
|
|
66
|
+
export async function deriveAutoRoom(app, roomId) {
|
|
67
|
+
return 'tce-' + hex(await hkdf(await cachedMaster(app, roomId), 'room', 96));
|
|
68
|
+
}
|
|
69
|
+
async function derive(app, roomId) {
|
|
70
|
+
const ikm = await cachedMaster(app, roomId);
|
|
71
|
+
const slot = hex(await hkdf(ikm, 'slot', 128));
|
|
72
|
+
const enc = await hkdf(ikm, 'enc', 256);
|
|
73
|
+
const seed = await hkdf(ikm, 'write', 256);
|
|
74
|
+
const pkcs8 = new Uint8Array(48);
|
|
75
|
+
pkcs8.set(fromHex('302e020100300506032b657004220420'));
|
|
76
|
+
pkcs8.set(seed, 16);
|
|
77
|
+
// Export only long enough to obtain the public component, then reimport nonextractable.
|
|
78
|
+
const pair = await crypto.subtle.importKey('pkcs8', pkcs8, 'Ed25519', true, ['sign']);
|
|
79
|
+
const jwk = await crypto.subtle.exportKey('jwk', pair);
|
|
80
|
+
const writer = jwk.x;
|
|
81
|
+
const signingKey = await crypto.subtle.importKey('pkcs8', pkcs8, 'Ed25519', false, ['sign']);
|
|
82
|
+
const encKey = await crypto.subtle.importKey('raw', enc, 'AES-GCM', false, ['encrypt', 'decrypt']);
|
|
83
|
+
enc.fill(0);
|
|
84
|
+
seed.fill(0);
|
|
85
|
+
pkcs8.fill(0);
|
|
86
|
+
return Object.freeze({ slot, encKey, writer, sign: async (bytes) => new Uint8Array(await crypto.subtle.sign('Ed25519', signingKey, new Uint8Array(bytes))) });
|
|
87
|
+
}
|
|
88
|
+
export function blobAAD(slot, seq) {
|
|
89
|
+
if (!/^[0-9a-f]{32}$/.test(slot) || !Number.isSafeInteger(seq) || seq < 1)
|
|
90
|
+
throw new Error('Invalid blob context');
|
|
91
|
+
return utf8('tc-escrow/v1|' + slot + '|' + seq);
|
|
92
|
+
}
|
|
93
|
+
export async function encryptBlob(encKey, slot, seq, plaintext) {
|
|
94
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
95
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
96
|
+
name: 'AES-GCM', iv, additionalData: blobAAD(slot, seq), tagLength: 128,
|
|
97
|
+
}, encKey, new Uint8Array(plaintext)));
|
|
98
|
+
const blob = new Uint8Array(12 + ciphertext.length);
|
|
99
|
+
blob.set(iv);
|
|
100
|
+
blob.set(ciphertext, 12);
|
|
101
|
+
return blob;
|
|
102
|
+
}
|
|
103
|
+
export async function decryptBlob(encKey, slot, seq, blob) {
|
|
104
|
+
if (blob.length < 28)
|
|
105
|
+
throw new Error('Truncated escrow blob');
|
|
106
|
+
return new Uint8Array(await crypto.subtle.decrypt({
|
|
107
|
+
name: 'AES-GCM', iv: new Uint8Array(blob.subarray(0, 12)), additionalData: blobAAD(slot, seq), tagLength: 128,
|
|
108
|
+
}, encKey, new Uint8Array(blob.subarray(12))));
|
|
109
|
+
}
|
|
110
|
+
export const DEFAULT_MAX_PLAINTEXT = 128 * 1024 * 1024;
|
|
111
|
+
export const PART_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
112
|
+
/** Part slots share the main slot's cached PBKDF2 master. */
|
|
113
|
+
export function derivePartKeys(app, vaultCode, part) {
|
|
114
|
+
if (typeof app !== 'string' || typeof vaultCode !== 'string' || typeof part !== 'string' || !PART_ID_RE.test(part))
|
|
115
|
+
throw new Error('Invalid part key inputs');
|
|
116
|
+
const id = JSON.stringify(['part', app, vaultCode, part]);
|
|
117
|
+
let pending = keyCache.get(id);
|
|
118
|
+
if (!pending) {
|
|
119
|
+
pending = (async () => {
|
|
120
|
+
const master = await cachedMaster(app, vaultCode);
|
|
121
|
+
const material = async (name, bits) => new Uint8Array(await crypto.subtle.deriveBits({
|
|
122
|
+
name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: utf8('tc-vault/v1/part\n' + part + '\n' + name),
|
|
123
|
+
}, master, bits));
|
|
124
|
+
const slot = hex(await material('slot', 128)), enc = await material('enc', 256), seed = await material('write', 256);
|
|
125
|
+
const pkcs8 = new Uint8Array(48);
|
|
126
|
+
pkcs8.set(fromHex('302e020100300506032b657004220420'));
|
|
127
|
+
pkcs8.set(seed, 16);
|
|
128
|
+
const pair = await crypto.subtle.importKey('pkcs8', pkcs8, 'Ed25519', true, ['sign']);
|
|
129
|
+
const writer = (await crypto.subtle.exportKey('jwk', pair)).x;
|
|
130
|
+
const signingKey = await crypto.subtle.importKey('pkcs8', pkcs8, 'Ed25519', false, ['sign']);
|
|
131
|
+
const encKey = await crypto.subtle.importKey('raw', enc, 'AES-GCM', false, ['encrypt', 'decrypt']);
|
|
132
|
+
enc.fill(0);
|
|
133
|
+
seed.fill(0);
|
|
134
|
+
pkcs8.fill(0);
|
|
135
|
+
return Object.freeze({ slot, encKey, writer, sign: async (bytes) => new Uint8Array(await crypto.subtle.sign('Ed25519', signingKey, new Uint8Array(bytes))) });
|
|
136
|
+
})();
|
|
137
|
+
keyCache.set(id, pending);
|
|
138
|
+
void pending.catch(() => { if (keyCache.get(id) === pending)
|
|
139
|
+
keyCache.delete(id); });
|
|
140
|
+
}
|
|
141
|
+
return pending;
|
|
142
|
+
}
|
|
143
|
+
async function transform(bytes, stream, maxBytes) {
|
|
144
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
|
|
145
|
+
throw new Error('Invalid output limit');
|
|
146
|
+
const reader = new Blob([new Uint8Array(bytes)]).stream().pipeThrough(stream).getReader();
|
|
147
|
+
const chunks = [];
|
|
148
|
+
let size = 0;
|
|
149
|
+
try {
|
|
150
|
+
for (;;) {
|
|
151
|
+
const { done, value } = await reader.read();
|
|
152
|
+
if (done)
|
|
153
|
+
break;
|
|
154
|
+
size += value.length;
|
|
155
|
+
if (size > maxBytes)
|
|
156
|
+
throw new Error('Escrow output exceeds limit');
|
|
157
|
+
chunks.push(value);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
await reader.cancel().catch(() => { });
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
reader.releaseLock();
|
|
166
|
+
}
|
|
167
|
+
const result = new Uint8Array(size);
|
|
168
|
+
let offset = 0;
|
|
169
|
+
for (const chunk of chunks) {
|
|
170
|
+
result.set(chunk, offset);
|
|
171
|
+
offset += chunk.length;
|
|
172
|
+
}
|
|
173
|
+
return result;
|
|
174
|
+
}
|
|
175
|
+
export const supportsGzip = () => typeof CompressionStream !== 'undefined' && typeof DecompressionStream !== 'undefined';
|
|
176
|
+
export function gzip(bytes, maxBytes = DEFAULT_MAX_PLAINTEXT) {
|
|
177
|
+
if (typeof CompressionStream === 'undefined')
|
|
178
|
+
throw new Error('Gzip compression unavailable');
|
|
179
|
+
return transform(bytes, new CompressionStream('gzip'), maxBytes);
|
|
180
|
+
}
|
|
181
|
+
export function gunzip(bytes, maxBytes = DEFAULT_MAX_PLAINTEXT) {
|
|
182
|
+
if (typeof DecompressionStream === 'undefined')
|
|
183
|
+
throw new Error('Gzip decompression unavailable');
|
|
184
|
+
return transform(bytes, new DecompressionStream('gzip'), maxBytes);
|
|
185
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export { isRecord } from './parse.js';
|
|
2
|
+
import type { EscrowKeys } from './crypto.js';
|
|
3
|
+
export declare const DEFAULT_MAX_BLOB: number;
|
|
4
|
+
export declare const MAX_CID_BYTES = 1024;
|
|
5
|
+
export declare const MAX_SCHEMA_BYTES = 256;
|
|
6
|
+
export declare const SLOT_RE: RegExp;
|
|
7
|
+
export declare const HASH_RE: RegExp;
|
|
8
|
+
export interface UnsignedHead {
|
|
9
|
+
v: 1;
|
|
10
|
+
type: 'tc-escrow-head';
|
|
11
|
+
slot: string;
|
|
12
|
+
seq: number;
|
|
13
|
+
parent: string | null;
|
|
14
|
+
cid: string;
|
|
15
|
+
size: number;
|
|
16
|
+
sha256: string;
|
|
17
|
+
comp: 'gzip' | 'none';
|
|
18
|
+
schema: string;
|
|
19
|
+
writer: string;
|
|
20
|
+
at: number;
|
|
21
|
+
}
|
|
22
|
+
export interface EscrowHead extends UnsignedHead {
|
|
23
|
+
sig: string;
|
|
24
|
+
}
|
|
25
|
+
export interface HeadValidation {
|
|
26
|
+
slot?: string;
|
|
27
|
+
writer?: string;
|
|
28
|
+
maxBlob?: number;
|
|
29
|
+
}
|
|
30
|
+
export declare function stableStringify(value: unknown): string;
|
|
31
|
+
export declare const safeInt: (value: unknown, min: number, max?: number) => value is number;
|
|
32
|
+
export declare function boundedText(value: unknown, maxBytes: number): value is string;
|
|
33
|
+
export declare function parseHead(value: unknown, options?: HeadValidation): EscrowHead | null;
|
|
34
|
+
export declare function signingPayload(head: UnsignedHead | EscrowHead): Uint8Array<ArrayBuffer>;
|
|
35
|
+
export declare function signHead(head: UnsignedHead, keys: Pick<EscrowKeys, 'slot' | 'writer' | 'sign'>, options?: HeadValidation): Promise<EscrowHead>;
|
|
36
|
+
export declare function buildHead(keys: Pick<EscrowKeys, 'slot' | 'writer' | 'sign'>, fields: Omit<UnsignedHead, 'v' | 'type' | 'slot' | 'writer' | 'at'> & {
|
|
37
|
+
at?: number;
|
|
38
|
+
}, options?: HeadValidation): Promise<EscrowHead>;
|
|
39
|
+
export declare function verifyHead(value: unknown, options: HeadValidation & {
|
|
40
|
+
slot: string;
|
|
41
|
+
writer: string;
|
|
42
|
+
}): Promise<boolean>;
|
|
43
|
+
export declare function headHash(head: EscrowHead, options?: HeadValidation): Promise<string>;
|
|
44
|
+
export interface DeleteFields {
|
|
45
|
+
slot: string;
|
|
46
|
+
seq: number;
|
|
47
|
+
head: string;
|
|
48
|
+
}
|
|
49
|
+
export interface SignedDelete extends DeleteFields {
|
|
50
|
+
sig: string;
|
|
51
|
+
}
|
|
52
|
+
export declare function parseDelete(value: unknown): SignedDelete | null;
|
|
53
|
+
export declare function deleteSigningPayload(fields: DeleteFields): Uint8Array<ArrayBuffer>;
|
|
54
|
+
export declare function signDelete(current: EscrowHead, keys: Pick<EscrowKeys, 'slot' | 'writer' | 'sign'>, options?: HeadValidation): Promise<SignedDelete>;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { isRecord } from './parse.js';
|
|
2
|
+
export { isRecord } from './parse.js';
|
|
3
|
+
import { base64url, fromBase64url, sha256, utf8 } from './crypto.js';
|
|
4
|
+
export const DEFAULT_MAX_BLOB = 32 * 1024 * 1024;
|
|
5
|
+
export const MAX_CID_BYTES = 1024;
|
|
6
|
+
export const MAX_SCHEMA_BYTES = 256;
|
|
7
|
+
export const SLOT_RE = /^[0-9a-f]{32}$/;
|
|
8
|
+
export const HASH_RE = /^[0-9a-f]{64}$/;
|
|
9
|
+
export function stableStringify(value) {
|
|
10
|
+
function stable(x, array = false) {
|
|
11
|
+
if (x === undefined || typeof x === 'function' || typeof x === 'symbol')
|
|
12
|
+
return array ? 'null' : undefined;
|
|
13
|
+
if (x === null || typeof x !== 'object')
|
|
14
|
+
return JSON.stringify(x);
|
|
15
|
+
if (Array.isArray(x))
|
|
16
|
+
return '[' + Array.from(x, v => stable(v, true)).join(',') + ']';
|
|
17
|
+
const record = x;
|
|
18
|
+
return '{' + Object.keys(record).sort().flatMap(key => {
|
|
19
|
+
const encoded = stable(record[key]);
|
|
20
|
+
return encoded === undefined ? [] : [JSON.stringify(key) + ':' + encoded];
|
|
21
|
+
}).join(',') + '}';
|
|
22
|
+
}
|
|
23
|
+
const result = stable(value);
|
|
24
|
+
if (result === undefined)
|
|
25
|
+
throw new Error('Not a JSON value');
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
export const safeInt = (value, min, max = Number.MAX_SAFE_INTEGER) => typeof value === 'number' && Number.isSafeInteger(value) && value >= min && value <= max;
|
|
29
|
+
export function boundedText(value, maxBytes) {
|
|
30
|
+
return typeof value === 'string' && value.length > 0 && value.length <= maxBytes &&
|
|
31
|
+
!/[\u0000-\u001f\u007f]/.test(value) && utf8(value).length <= maxBytes;
|
|
32
|
+
}
|
|
33
|
+
function canonicalB64(value, bytes) {
|
|
34
|
+
if (typeof value !== 'string' || value.length !== Math.ceil(bytes * 8 / 6))
|
|
35
|
+
return false;
|
|
36
|
+
try {
|
|
37
|
+
return fromBase64url(value).length === bytes;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const fields = ['v', 'type', 'slot', 'seq', 'parent', 'cid', 'size', 'sha256', 'comp', 'schema', 'writer', 'at'];
|
|
44
|
+
function parseUnsigned(value, options, signed) {
|
|
45
|
+
if (!isRecord(value))
|
|
46
|
+
return null;
|
|
47
|
+
const keys = signed ? [...fields, 'sig'] : fields;
|
|
48
|
+
if (Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key)))
|
|
49
|
+
return null;
|
|
50
|
+
const maxBlob = options.maxBlob ?? DEFAULT_MAX_BLOB;
|
|
51
|
+
if (!safeInt(maxBlob, 28) || value.v !== 1 || value.type !== 'tc-escrow-head' ||
|
|
52
|
+
typeof value.slot !== 'string' || !SLOT_RE.test(value.slot) ||
|
|
53
|
+
!safeInt(value.seq, 1) || !(value.parent === null || typeof value.parent === 'string' && HASH_RE.test(value.parent)) ||
|
|
54
|
+
!boundedText(value.cid, MAX_CID_BYTES) || !/^[\x21-\x7e]+$/.test(value.cid) ||
|
|
55
|
+
!safeInt(value.size, 28, maxBlob) || typeof value.sha256 !== 'string' || !HASH_RE.test(value.sha256) ||
|
|
56
|
+
!(value.comp === 'gzip' || value.comp === 'none') || !boundedText(value.schema, MAX_SCHEMA_BYTES) ||
|
|
57
|
+
!canonicalB64(value.writer, 32) || !safeInt(value.at, 0) ||
|
|
58
|
+
(options.slot !== undefined && value.slot !== options.slot) ||
|
|
59
|
+
(options.writer !== undefined && value.writer !== options.writer))
|
|
60
|
+
return null;
|
|
61
|
+
return { v: 1, type: 'tc-escrow-head', slot: value.slot, seq: value.seq, parent: value.parent,
|
|
62
|
+
cid: value.cid, size: value.size, sha256: value.sha256, comp: value.comp, schema: value.schema,
|
|
63
|
+
writer: value.writer, at: value.at };
|
|
64
|
+
}
|
|
65
|
+
export function parseHead(value, options = {}) {
|
|
66
|
+
const unsigned = parseUnsigned(value, options, true);
|
|
67
|
+
if (!unsigned || !isRecord(value) || !canonicalB64(value.sig, 64))
|
|
68
|
+
return null;
|
|
69
|
+
return { ...unsigned, sig: value.sig };
|
|
70
|
+
}
|
|
71
|
+
export function signingPayload(head) {
|
|
72
|
+
const { sig: _sig, ...unsigned } = head;
|
|
73
|
+
return utf8('tc-escrow/v1/head\n' + stableStringify(unsigned));
|
|
74
|
+
}
|
|
75
|
+
export async function signHead(head, keys, options = {}) {
|
|
76
|
+
const parsed = parseUnsigned(head, { ...options, slot: keys.slot, writer: keys.writer }, false);
|
|
77
|
+
if (!parsed)
|
|
78
|
+
throw new Error('Invalid escrow head');
|
|
79
|
+
const result = { ...parsed, sig: base64url(await keys.sign(signingPayload(parsed))) };
|
|
80
|
+
if (!parseHead(result, options))
|
|
81
|
+
throw new Error('Invalid escrow signature');
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
export async function buildHead(keys, fields, options = {}) {
|
|
85
|
+
return signHead({ ...fields, v: 1, type: 'tc-escrow-head', slot: keys.slot, writer: keys.writer, at: fields.at ?? Date.now() }, keys, options);
|
|
86
|
+
}
|
|
87
|
+
export async function verifyHead(value, options) {
|
|
88
|
+
const head = parseHead(value, options);
|
|
89
|
+
if (!head)
|
|
90
|
+
return false;
|
|
91
|
+
try {
|
|
92
|
+
const key = await crypto.subtle.importKey('raw', fromBase64url(head.writer), 'Ed25519', false, ['verify']);
|
|
93
|
+
return await crypto.subtle.verify('Ed25519', key, fromBase64url(head.sig), signingPayload(head));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
export async function headHash(head, options = {}) {
|
|
100
|
+
const parsed = parseHead(head, options);
|
|
101
|
+
if (!parsed)
|
|
102
|
+
throw new Error('Invalid escrow head');
|
|
103
|
+
return sha256(utf8(stableStringify(parsed)));
|
|
104
|
+
}
|
|
105
|
+
export function parseDelete(value) {
|
|
106
|
+
if (!isRecord(value) || typeof value.slot !== 'string' || !SLOT_RE.test(value.slot) ||
|
|
107
|
+
!safeInt(value.seq, 1) || typeof value.head !== 'string' || !HASH_RE.test(value.head) ||
|
|
108
|
+
!canonicalB64(value.sig, 64))
|
|
109
|
+
return null;
|
|
110
|
+
return { slot: value.slot, seq: value.seq, head: value.head, sig: value.sig };
|
|
111
|
+
}
|
|
112
|
+
export function deleteSigningPayload(fields) {
|
|
113
|
+
return utf8('tc-escrow/v1/delete\n' + stableStringify({ slot: fields.slot, seq: fields.seq, head: fields.head }));
|
|
114
|
+
}
|
|
115
|
+
export async function signDelete(current, keys, options = {}) {
|
|
116
|
+
if (!await verifyHead(current, { ...options, slot: keys.slot, writer: keys.writer }))
|
|
117
|
+
throw new Error('Invalid escrow head');
|
|
118
|
+
const fields = { slot: keys.slot, seq: current.seq, head: await headHash(current, options) };
|
|
119
|
+
const result = { ...fields, sig: base64url(await keys.sign(deleteSigningPayload(fields))) };
|
|
120
|
+
if (!parseDelete(result))
|
|
121
|
+
throw new Error('Invalid escrow signature');
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { EscrowHead, SignedDelete } from './head.js';
|
|
2
|
+
export declare const MAX_MESSAGE_BYTES: number;
|
|
3
|
+
export declare const ERROR_CODES: readonly ["conflict", "bad_request", "bad_sig", "bad_signature", "writer_mismatch", "too_large", "fetch_failed", "hash_mismatch", "quota", "busy", "deleted"];
|
|
4
|
+
export type EscrowErrorCode = typeof ERROR_CODES[number];
|
|
5
|
+
export interface EscrowHello {
|
|
6
|
+
v: 1;
|
|
7
|
+
type: 'escrow_hello';
|
|
8
|
+
}
|
|
9
|
+
export interface EscrowProvider {
|
|
10
|
+
v: 1;
|
|
11
|
+
type: 'escrow_provider';
|
|
12
|
+
maxBlob: number;
|
|
13
|
+
version: 1;
|
|
14
|
+
features?: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface EscrowGet {
|
|
17
|
+
v: 1;
|
|
18
|
+
type: 'escrow_get';
|
|
19
|
+
id: string;
|
|
20
|
+
slot: string;
|
|
21
|
+
}
|
|
22
|
+
export interface EscrowHeadMessage {
|
|
23
|
+
v: 1;
|
|
24
|
+
type: 'escrow_head';
|
|
25
|
+
id: string;
|
|
26
|
+
slot: string;
|
|
27
|
+
head: EscrowHead | null;
|
|
28
|
+
}
|
|
29
|
+
export interface EscrowPut {
|
|
30
|
+
v: 1;
|
|
31
|
+
type: 'escrow_put';
|
|
32
|
+
id: string;
|
|
33
|
+
head: EscrowHead;
|
|
34
|
+
}
|
|
35
|
+
export interface EscrowDelete extends SignedDelete {
|
|
36
|
+
v: 1;
|
|
37
|
+
type: 'escrow_delete';
|
|
38
|
+
id: string;
|
|
39
|
+
}
|
|
40
|
+
export interface EscrowDeleted {
|
|
41
|
+
v: 1;
|
|
42
|
+
type: 'escrow_deleted';
|
|
43
|
+
id: string;
|
|
44
|
+
slot: string;
|
|
45
|
+
}
|
|
46
|
+
export interface EscrowAck {
|
|
47
|
+
v: 1;
|
|
48
|
+
type: 'escrow_ack';
|
|
49
|
+
id: string;
|
|
50
|
+
slot: string;
|
|
51
|
+
seq: number;
|
|
52
|
+
hash: string;
|
|
53
|
+
}
|
|
54
|
+
export type EscrowError = {
|
|
55
|
+
v: 1;
|
|
56
|
+
type: 'escrow_error';
|
|
57
|
+
id: string;
|
|
58
|
+
message: string;
|
|
59
|
+
} & ({
|
|
60
|
+
code: 'conflict';
|
|
61
|
+
head: EscrowHead | null;
|
|
62
|
+
} | {
|
|
63
|
+
code: 'deleted';
|
|
64
|
+
head?: EscrowHead;
|
|
65
|
+
} | {
|
|
66
|
+
code: Exclude<EscrowErrorCode, 'conflict' | 'deleted'>;
|
|
67
|
+
});
|
|
68
|
+
export type EscrowMessage = EscrowHello | EscrowProvider | EscrowGet | EscrowHeadMessage | EscrowPut | EscrowAck | EscrowDelete | EscrowDeleted | EscrowError;
|
|
69
|
+
export interface ProtocolLimits {
|
|
70
|
+
maxBlob?: number;
|
|
71
|
+
}
|
|
72
|
+
/** Unknown wire fields are ignored; signed heads retain their exact field set. */
|
|
73
|
+
export declare function parseEscrowMessage(input: unknown, limits?: ProtocolLimits): EscrowMessage | null;
|
|
74
|
+
export declare function encodeEscrowMessage(message: EscrowMessage, limits?: ProtocolLimits): Uint8Array<ArrayBuffer>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { utf8 } from './crypto.js';
|
|
2
|
+
import { boundedText, DEFAULT_MAX_BLOB, HASH_RE, isRecord, parseDelete, parseHead, safeInt, SLOT_RE } from './head.js';
|
|
3
|
+
export const MAX_MESSAGE_BYTES = 16 * 1024;
|
|
4
|
+
export const ERROR_CODES = ['conflict', 'bad_request', 'bad_sig', 'bad_signature', 'writer_mismatch', 'too_large', 'fetch_failed', 'hash_mismatch', 'quota', 'busy', 'deleted'];
|
|
5
|
+
const isSlot = (value) => typeof value === 'string' && SLOT_RE.test(value);
|
|
6
|
+
const isHash = (value) => typeof value === 'string' && HASH_RE.test(value);
|
|
7
|
+
function parseObject(value, limits) {
|
|
8
|
+
if (!isRecord(value) || value.v !== 1)
|
|
9
|
+
return null;
|
|
10
|
+
if (value.type === 'escrow_hello')
|
|
11
|
+
return { v: 1, type: value.type };
|
|
12
|
+
if (value.type === 'escrow_provider') {
|
|
13
|
+
if (!safeInt(value.maxBlob, 28) || value.version !== 1 || (value.features !== undefined &&
|
|
14
|
+
(!Array.isArray(value.features) || value.features.length > 32 || !value.features.every(f => boundedText(f, 64)))))
|
|
15
|
+
return null;
|
|
16
|
+
return { v: 1, type: value.type, maxBlob: value.maxBlob, version: 1,
|
|
17
|
+
...(value.features === undefined ? {} : { features: [...value.features] }) };
|
|
18
|
+
}
|
|
19
|
+
if (!boundedText(value.id, 64))
|
|
20
|
+
return null;
|
|
21
|
+
const base = { v: 1, id: value.id };
|
|
22
|
+
switch (value.type) {
|
|
23
|
+
case 'escrow_get':
|
|
24
|
+
return isSlot(value.slot) ? { ...base, type: value.type, slot: value.slot } : null;
|
|
25
|
+
case 'escrow_head': {
|
|
26
|
+
if (!isSlot(value.slot))
|
|
27
|
+
return null;
|
|
28
|
+
const head = value.head === null ? null : parseHead(value.head, { ...limits, slot: value.slot });
|
|
29
|
+
return head || value.head === null ? { ...base, type: value.type, slot: value.slot, head } : null;
|
|
30
|
+
}
|
|
31
|
+
case 'escrow_put': {
|
|
32
|
+
const head = parseHead(value.head, limits);
|
|
33
|
+
return head ? { ...base, type: value.type, head } : null;
|
|
34
|
+
}
|
|
35
|
+
case 'escrow_delete': {
|
|
36
|
+
const fields = parseDelete(value);
|
|
37
|
+
return fields ? { ...base, type: value.type, ...fields } : null;
|
|
38
|
+
}
|
|
39
|
+
case 'escrow_deleted':
|
|
40
|
+
return isSlot(value.slot) ? { ...base, type: value.type, slot: value.slot } : null;
|
|
41
|
+
case 'escrow_ack':
|
|
42
|
+
return isSlot(value.slot) && safeInt(value.seq, 1) && isHash(value.hash) ?
|
|
43
|
+
{ ...base, type: value.type, slot: value.slot, seq: value.seq, hash: value.hash } : null;
|
|
44
|
+
case 'escrow_error': {
|
|
45
|
+
if (!ERROR_CODES.includes(value.code) ||
|
|
46
|
+
typeof value.message !== 'string' || value.message.length > 1024 || utf8(value.message).length > 1024)
|
|
47
|
+
return null;
|
|
48
|
+
if (value.code === 'conflict') {
|
|
49
|
+
const head = value.head === null ? null : parseHead(value.head, limits);
|
|
50
|
+
return head || value.head === null ? { ...base, type: value.type, code: 'conflict', message: value.message, head } : null;
|
|
51
|
+
}
|
|
52
|
+
if (value.code === 'deleted') {
|
|
53
|
+
const head = value.head === undefined ? undefined : parseHead(value.head, limits);
|
|
54
|
+
if (head === null)
|
|
55
|
+
return null;
|
|
56
|
+
return { ...base, type: value.type, code: 'deleted', message: value.message, ...(head ? { head } : {}) };
|
|
57
|
+
}
|
|
58
|
+
return { ...base, type: value.type, code: value.code, message: value.message };
|
|
59
|
+
}
|
|
60
|
+
default: return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Unknown wire fields are ignored; signed heads retain their exact field set. */
|
|
64
|
+
export function parseEscrowMessage(input, limits = {}) {
|
|
65
|
+
try {
|
|
66
|
+
let value = input;
|
|
67
|
+
if (input instanceof Uint8Array) {
|
|
68
|
+
if (input.byteLength > MAX_MESSAGE_BYTES)
|
|
69
|
+
return null;
|
|
70
|
+
value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(input));
|
|
71
|
+
}
|
|
72
|
+
else if (typeof input === 'string') {
|
|
73
|
+
if (input.length > MAX_MESSAGE_BYTES || utf8(input).length > MAX_MESSAGE_BYTES)
|
|
74
|
+
return null;
|
|
75
|
+
value = JSON.parse(input);
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
const encoded = JSON.stringify(input);
|
|
79
|
+
if (!encoded || encoded.length > MAX_MESSAGE_BYTES || utf8(encoded).length > MAX_MESSAGE_BYTES)
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
return parseObject(value, { maxBlob: limits.maxBlob ?? DEFAULT_MAX_BLOB });
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function encodeEscrowMessage(message, limits = {}) {
|
|
89
|
+
const parsed = parseEscrowMessage(message, limits);
|
|
90
|
+
if (!parsed)
|
|
91
|
+
throw new Error('Invalid escrow message');
|
|
92
|
+
return utf8(JSON.stringify(parsed));
|
|
93
|
+
}
|
package/dist/i18n.d.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
export declare const en: {
|
|
2
|
+
readonly title: "Distributed vault";
|
|
3
|
+
readonly scopeRoomHint: "Add this room to mistl (Storage → Escrow).";
|
|
4
|
+
readonly extraRooms: "Additional mistl rooms";
|
|
5
|
+
readonly copyAll: "Copy all rooms";
|
|
6
|
+
readonly invalidRoom: "Invalid mistl room.";
|
|
7
|
+
readonly explanation: "Your data is encrypted in this browser and stored on your mistl node. mistl cannot read it. Keep your vault code secret: anyone with it can read and write your vault.";
|
|
8
|
+
readonly master: "Enable personal vault";
|
|
9
|
+
readonly app: "Back up {app} data";
|
|
10
|
+
readonly appFallback: "this app";
|
|
11
|
+
readonly turnOn: "Turn on the distributed vault";
|
|
12
|
+
readonly useCode: "Use a code from another device";
|
|
13
|
+
readonly save: "Save now";
|
|
14
|
+
readonly restore: "Restore now";
|
|
15
|
+
readonly room: "mistl room";
|
|
16
|
+
readonly hint: "Add in mistl: Storage → Distributed vault";
|
|
17
|
+
readonly roomPending: "Preparing room…";
|
|
18
|
+
readonly roomUnavailable: "Available when backup is on";
|
|
19
|
+
readonly advanced: "Advanced";
|
|
20
|
+
readonly mode: "Mode";
|
|
21
|
+
readonly auto: "Automatic";
|
|
22
|
+
readonly custom: "Custom";
|
|
23
|
+
readonly off: "Off";
|
|
24
|
+
readonly apply: "Apply";
|
|
25
|
+
readonly code: "Vault code";
|
|
26
|
+
readonly codeHint: "Keep this code private. Anyone with it can read and write your vault.";
|
|
27
|
+
readonly reveal: "Reveal";
|
|
28
|
+
readonly hide: "Hide";
|
|
29
|
+
readonly copy: "Copy";
|
|
30
|
+
readonly copied: "Copied";
|
|
31
|
+
readonly link: "Copy link for another device";
|
|
32
|
+
readonly import: "Import code";
|
|
33
|
+
readonly importAnother: "Import another code";
|
|
34
|
+
readonly importLabel: "Code from another device";
|
|
35
|
+
readonly pendingTitle: "Use a code from another device?";
|
|
36
|
+
readonly confirmation: "Your local data stays on this device. If you already use a vault, this switches it to the new code.";
|
|
37
|
+
readonly confirm: "Confirm import";
|
|
38
|
+
readonly cancel: "Cancel";
|
|
39
|
+
readonly invalid: "Invalid vault code or room.";
|
|
40
|
+
readonly copyError: "Copy failed. Select and copy the value manually.";
|
|
41
|
+
readonly invalidCode: "Invalid vault code.";
|
|
42
|
+
readonly importError: "Could not import this vault code.";
|
|
43
|
+
readonly savedNow: "Saved just now";
|
|
44
|
+
readonly savedAgo: "Saved {minutes} min ago";
|
|
45
|
+
readonly savedHoursAgo: "Saved {hours} hr ago";
|
|
46
|
+
readonly savedDayAgo: "Saved 1 day ago";
|
|
47
|
+
readonly savedDaysAgo: "Saved {days} days ago";
|
|
48
|
+
readonly parts: "Attachments: {stored} stored, {pending} pending, {omitted} omitted";
|
|
49
|
+
readonly status_off: "Vault is off";
|
|
50
|
+
readonly status_appOff: "Backup is off for this app";
|
|
51
|
+
readonly status_searching: "Searching for mistl…";
|
|
52
|
+
readonly status_noProvider: "No provider found; still listening";
|
|
53
|
+
readonly status_restoring: "Restoring…";
|
|
54
|
+
readonly status_saving: "Saving…";
|
|
55
|
+
readonly status_saved: "Saved";
|
|
56
|
+
readonly status_restored: "Restored";
|
|
57
|
+
readonly status_upToDate: "Up to date";
|
|
58
|
+
readonly status_error: "Vault operation failed";
|
|
59
|
+
};
|
|
60
|
+
type ScopeMessage = 'scopeRoomHint' | 'extraRooms' | 'copyAll' | 'invalidRoom';
|
|
61
|
+
export type VaultMessages = Record<Exclude<keyof typeof en, ScopeMessage>, string> & Partial<Record<ScopeMessage, string>>;
|
|
62
|
+
export declare const ja: VaultMessages;
|
|
63
|
+
export declare const zhCN: VaultMessages;
|
|
64
|
+
export declare const zhTW: VaultMessages;
|
|
65
|
+
export declare const messages: {
|
|
66
|
+
en: {
|
|
67
|
+
readonly title: "Distributed vault";
|
|
68
|
+
readonly scopeRoomHint: "Add this room to mistl (Storage → Escrow).";
|
|
69
|
+
readonly extraRooms: "Additional mistl rooms";
|
|
70
|
+
readonly copyAll: "Copy all rooms";
|
|
71
|
+
readonly invalidRoom: "Invalid mistl room.";
|
|
72
|
+
readonly explanation: "Your data is encrypted in this browser and stored on your mistl node. mistl cannot read it. Keep your vault code secret: anyone with it can read and write your vault.";
|
|
73
|
+
readonly master: "Enable personal vault";
|
|
74
|
+
readonly app: "Back up {app} data";
|
|
75
|
+
readonly appFallback: "this app";
|
|
76
|
+
readonly turnOn: "Turn on the distributed vault";
|
|
77
|
+
readonly useCode: "Use a code from another device";
|
|
78
|
+
readonly save: "Save now";
|
|
79
|
+
readonly restore: "Restore now";
|
|
80
|
+
readonly room: "mistl room";
|
|
81
|
+
readonly hint: "Add in mistl: Storage → Distributed vault";
|
|
82
|
+
readonly roomPending: "Preparing room…";
|
|
83
|
+
readonly roomUnavailable: "Available when backup is on";
|
|
84
|
+
readonly advanced: "Advanced";
|
|
85
|
+
readonly mode: "Mode";
|
|
86
|
+
readonly auto: "Automatic";
|
|
87
|
+
readonly custom: "Custom";
|
|
88
|
+
readonly off: "Off";
|
|
89
|
+
readonly apply: "Apply";
|
|
90
|
+
readonly code: "Vault code";
|
|
91
|
+
readonly codeHint: "Keep this code private. Anyone with it can read and write your vault.";
|
|
92
|
+
readonly reveal: "Reveal";
|
|
93
|
+
readonly hide: "Hide";
|
|
94
|
+
readonly copy: "Copy";
|
|
95
|
+
readonly copied: "Copied";
|
|
96
|
+
readonly link: "Copy link for another device";
|
|
97
|
+
readonly import: "Import code";
|
|
98
|
+
readonly importAnother: "Import another code";
|
|
99
|
+
readonly importLabel: "Code from another device";
|
|
100
|
+
readonly pendingTitle: "Use a code from another device?";
|
|
101
|
+
readonly confirmation: "Your local data stays on this device. If you already use a vault, this switches it to the new code.";
|
|
102
|
+
readonly confirm: "Confirm import";
|
|
103
|
+
readonly cancel: "Cancel";
|
|
104
|
+
readonly invalid: "Invalid vault code or room.";
|
|
105
|
+
readonly copyError: "Copy failed. Select and copy the value manually.";
|
|
106
|
+
readonly invalidCode: "Invalid vault code.";
|
|
107
|
+
readonly importError: "Could not import this vault code.";
|
|
108
|
+
readonly savedNow: "Saved just now";
|
|
109
|
+
readonly savedAgo: "Saved {minutes} min ago";
|
|
110
|
+
readonly savedHoursAgo: "Saved {hours} hr ago";
|
|
111
|
+
readonly savedDayAgo: "Saved 1 day ago";
|
|
112
|
+
readonly savedDaysAgo: "Saved {days} days ago";
|
|
113
|
+
readonly parts: "Attachments: {stored} stored, {pending} pending, {omitted} omitted";
|
|
114
|
+
readonly status_off: "Vault is off";
|
|
115
|
+
readonly status_appOff: "Backup is off for this app";
|
|
116
|
+
readonly status_searching: "Searching for mistl…";
|
|
117
|
+
readonly status_noProvider: "No provider found; still listening";
|
|
118
|
+
readonly status_restoring: "Restoring…";
|
|
119
|
+
readonly status_saving: "Saving…";
|
|
120
|
+
readonly status_saved: "Saved";
|
|
121
|
+
readonly status_restored: "Restored";
|
|
122
|
+
readonly status_upToDate: "Up to date";
|
|
123
|
+
readonly status_error: "Vault operation failed";
|
|
124
|
+
};
|
|
125
|
+
ja: VaultMessages;
|
|
126
|
+
'zh-CN': VaultMessages;
|
|
127
|
+
'zh-TW': VaultMessages;
|
|
128
|
+
};
|
|
129
|
+
export type VaultLocale = keyof typeof messages;
|
|
130
|
+
export declare function resolveLocale(locale?: string): VaultLocale;
|
|
131
|
+
export declare function vaultMessage(locale: string | undefined, key: keyof VaultMessages, values?: Record<string, string | number>): string;
|
|
132
|
+
export {};
|