@tik-choco/mistvault 0.0.0-stage → 0.3.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 +164 -0
- package/README.md +221 -2
- package/README.zh.md +164 -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/elements/PanelElement.d.ts +30 -0
- package/dist/elements/PanelElement.js +56 -0
- package/dist/elements/RoomControls.d.ts +21 -0
- package/dist/elements/RoomControls.js +27 -0
- package/dist/elements/ScopeVaultPanelElement.d.ts +10 -0
- package/dist/elements/ScopeVaultPanelElement.js +27 -0
- package/dist/elements/VaultPanelElement.d.ts +39 -0
- package/dist/elements/VaultPanelElement.js +191 -0
- package/dist/elements/dom.d.ts +14 -0
- package/dist/elements/dom.js +58 -0
- package/dist/elements/index.d.ts +15 -0
- package/dist/elements/index.js +12 -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/ScopeVaultPanel.d.ts +10 -0
- package/dist/preact/ScopeVaultPanel.js +8 -0
- package/dist/preact/VaultPanel.d.ts +16 -0
- package/dist/preact/VaultPanel.js +14 -0
- package/dist/preact/index.d.ts +5 -0
- package/dist/preact/index.js +3 -0
- package/dist/preact/ui.css +132 -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 +57 -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
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Dom } from './dom.js';
|
|
2
|
+
type Source<V> = {
|
|
3
|
+
getView(): V;
|
|
4
|
+
subscribe(cb: (view: V) => void): () => void;
|
|
5
|
+
};
|
|
6
|
+
declare const HTMLElementBase: {
|
|
7
|
+
new (): HTMLElement;
|
|
8
|
+
prototype: HTMLElement;
|
|
9
|
+
};
|
|
10
|
+
export declare abstract class PanelElement<V, S extends Source<V>> extends HTMLElementBase {
|
|
11
|
+
static observedAttributes: string[];
|
|
12
|
+
private active;
|
|
13
|
+
private currentSource?;
|
|
14
|
+
private view?;
|
|
15
|
+
private unsubscribe?;
|
|
16
|
+
protected dom: Dom;
|
|
17
|
+
protected abstract renderPanel(view: V, source: S): void;
|
|
18
|
+
get locale(): string | undefined;
|
|
19
|
+
set locale(value: string | undefined);
|
|
20
|
+
protected setStringAttribute(name: string, value: string | undefined): void;
|
|
21
|
+
attributeChangedCallback(): void;
|
|
22
|
+
protected get source(): S | undefined;
|
|
23
|
+
protected set source(value: S | undefined);
|
|
24
|
+
protected upgradeProperties(names: string[]): void;
|
|
25
|
+
connectedCallback(): void;
|
|
26
|
+
disconnectedCallback(): void;
|
|
27
|
+
private bind;
|
|
28
|
+
protected render(): void;
|
|
29
|
+
}
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Dom } from './dom.js';
|
|
2
|
+
const HTMLElementBase = globalThis.HTMLElement ?? class {
|
|
3
|
+
};
|
|
4
|
+
export class PanelElement extends HTMLElementBase {
|
|
5
|
+
static observedAttributes = ['locale'];
|
|
6
|
+
active = false;
|
|
7
|
+
currentSource;
|
|
8
|
+
view;
|
|
9
|
+
unsubscribe;
|
|
10
|
+
dom = new Dom(this);
|
|
11
|
+
get locale() { return this.getAttribute('locale') ?? undefined; }
|
|
12
|
+
set locale(value) { this.setStringAttribute('locale', value); }
|
|
13
|
+
setStringAttribute(name, value) {
|
|
14
|
+
if (value == null)
|
|
15
|
+
this.removeAttribute(name);
|
|
16
|
+
else if (this.getAttribute(name) !== value)
|
|
17
|
+
this.setAttribute(name, value);
|
|
18
|
+
}
|
|
19
|
+
attributeChangedCallback() { this.render(); }
|
|
20
|
+
get source() { return this.currentSource; }
|
|
21
|
+
set source(value) {
|
|
22
|
+
if (this.currentSource === value)
|
|
23
|
+
return;
|
|
24
|
+
this.currentSource = value;
|
|
25
|
+
this.bind();
|
|
26
|
+
}
|
|
27
|
+
upgradeProperties(names) {
|
|
28
|
+
for (const name of names)
|
|
29
|
+
if (Object.hasOwn(this, name)) {
|
|
30
|
+
const value = Reflect.get(this, name);
|
|
31
|
+
Reflect.deleteProperty(this, name);
|
|
32
|
+
Reflect.set(this, name, value);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
connectedCallback() { this.active = true; this.bind(); }
|
|
36
|
+
disconnectedCallback() { this.active = false; this.unsubscribe?.(); this.unsubscribe = undefined; this.view = undefined; }
|
|
37
|
+
bind() {
|
|
38
|
+
this.unsubscribe?.();
|
|
39
|
+
this.unsubscribe = undefined;
|
|
40
|
+
this.view = undefined;
|
|
41
|
+
const source = this.source;
|
|
42
|
+
if (this.active && source) {
|
|
43
|
+
this.unsubscribe = source.subscribe(view => { this.view = view; this.render(); });
|
|
44
|
+
this.view = source.getView();
|
|
45
|
+
}
|
|
46
|
+
this.render();
|
|
47
|
+
}
|
|
48
|
+
render() {
|
|
49
|
+
if (!this.active)
|
|
50
|
+
return;
|
|
51
|
+
if (this.source && this.view)
|
|
52
|
+
this.renderPanel(this.view, this.source);
|
|
53
|
+
else
|
|
54
|
+
this.dom.finish();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { VaultMode } from '../settings.js';
|
|
2
|
+
import type { Dom } from './dom.js';
|
|
3
|
+
interface RoomControlsProps {
|
|
4
|
+
locale?: string;
|
|
5
|
+
mode: VaultMode;
|
|
6
|
+
room: string;
|
|
7
|
+
controller: {
|
|
8
|
+
configure(mode: VaultMode, room: string): boolean;
|
|
9
|
+
};
|
|
10
|
+
disableUnchanged?: boolean;
|
|
11
|
+
onInvalid(): void;
|
|
12
|
+
}
|
|
13
|
+
export declare class RoomControls {
|
|
14
|
+
private update;
|
|
15
|
+
private previous?;
|
|
16
|
+
private mode;
|
|
17
|
+
private room;
|
|
18
|
+
constructor(update: () => void);
|
|
19
|
+
render({ node: n }: Dom, props: RoomControlsProps): (false | HTMLButtonElement | HTMLLabelElement)[];
|
|
20
|
+
}
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { vaultMessage } from '../i18n.js';
|
|
2
|
+
import { validVaultRoom } from '../settings.js';
|
|
3
|
+
export class RoomControls {
|
|
4
|
+
update;
|
|
5
|
+
previous;
|
|
6
|
+
mode = 'off';
|
|
7
|
+
room = '';
|
|
8
|
+
constructor(update) {
|
|
9
|
+
this.update = update;
|
|
10
|
+
}
|
|
11
|
+
render({ node: n }, props) {
|
|
12
|
+
if (this.previous?.mode !== props.mode || this.previous?.room !== props.room || this.previous?.controller !== props.controller) {
|
|
13
|
+
this.mode = props.mode;
|
|
14
|
+
this.room = props.room;
|
|
15
|
+
}
|
|
16
|
+
this.previous = props;
|
|
17
|
+
const t = (key) => vaultMessage(props.locale, key);
|
|
18
|
+
return [n('mode-label', 'label', {}, t('mode'), n('mode', 'select', { value: this.mode,
|
|
19
|
+
onchange: e => { this.mode = e.currentTarget.value; this.update(); } }, n('auto', 'option', { value: 'auto' }, t('auto')), n('custom', 'option', { value: 'custom' }, t('custom')), n('off', 'option', { value: 'off' }, t('off')))),
|
|
20
|
+
this.mode === 'custom' && n('custom-room-label', 'label', {}, t('room'), n('custom-room', 'input', { value: this.room, maxLength: 96,
|
|
21
|
+
attrs: { 'aria-invalid': String(!validVaultRoom(this.room)) }, oninput: e => { this.room = e.currentTarget.value; this.update(); } })),
|
|
22
|
+
n('apply', 'button', { type: 'button', disabled: this.mode === 'custom' && !validVaultRoom(this.room) ||
|
|
23
|
+
!!props.disableUnchanged && this.mode === props.mode && (this.mode !== 'custom' || this.room === props.room),
|
|
24
|
+
onclick: () => { if (!props.controller.configure(this.mode, this.room))
|
|
25
|
+
props.onInvalid(); } }, t('apply'))];
|
|
26
|
+
}
|
|
27
|
+
}
|