@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
package/README.md
CHANGED
|
@@ -1,3 +1,184 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mistvault
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Browser-encrypted distributed vaults for TypeScript applications. Compatible with the `tc-escrow v1` protocol served by mistl. The portable core has no runtime dependencies; the settings panel optionally uses Preact 10.
|
|
4
|
+
|
|
5
|
+
[日本語](README.ja.md) · [中文](README.zh.md)
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @tik-choco/mistvault
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Generated `dist/` files are excluded from Git. For development, run `npm install`, `npm run build`, and `npm test`.
|
|
14
|
+
|
|
15
|
+
## Connect an application
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createVault, createMistVaultTransport } from '@tik-choco/mistvault'
|
|
19
|
+
import type { VaultAdapter, MistNodeLike } from '@tik-choco/mistvault'
|
|
20
|
+
|
|
21
|
+
type Entry = { updatedAt: number; text: string }
|
|
22
|
+
type State = { entries: Record<string, Entry>; deleted: Record<string, number> }
|
|
23
|
+
|
|
24
|
+
function merge(local: State, remote: State): State {
|
|
25
|
+
const entries = { ...remote.entries }
|
|
26
|
+
const deleted = { ...remote.deleted }
|
|
27
|
+
for (const [id, at] of Object.entries(local.deleted)) {
|
|
28
|
+
deleted[id] = Math.max(deleted[id] ?? 0, at)
|
|
29
|
+
}
|
|
30
|
+
for (const [id, entry] of Object.entries(local.entries)) {
|
|
31
|
+
const previous = entries[id]
|
|
32
|
+
if (!previous || entry.updatedAt > previous.updatedAt ||
|
|
33
|
+
entry.updatedAt === previous.updatedAt && entry.text > previous.text) entries[id] = entry
|
|
34
|
+
}
|
|
35
|
+
for (const [id, entry] of Object.entries(entries)) {
|
|
36
|
+
if ((deleted[id] ?? -1) >= entry.updatedAt) delete entries[id]
|
|
37
|
+
}
|
|
38
|
+
return { entries, deleted }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function connectVault(
|
|
42
|
+
adapter: VaultAdapter<State>,
|
|
43
|
+
createNode: () => MistNodeLike,
|
|
44
|
+
storageAdd: (name: string, bytes: Uint8Array) => Promise<string>,
|
|
45
|
+
storageGet: (cid: string) => Promise<Uint8Array>,
|
|
46
|
+
) {
|
|
47
|
+
return createVault({ adapter: { ...adapter, merge }, transport: () =>
|
|
48
|
+
createMistVaultTransport({ createNode, storageAdd, storageGet }) })
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Implement `snapshot`, `parse`, `apply`, and `subscribe` against your application's stores. Use a stable `app` ID and a versioned `schema`. `parse` must validate untrusted remote JSON and throw on invalid input. `merge` must be deterministic, idempotent and preserve newer records from both sides, including deletion tombstones. `apply` persists the merged result and refreshes the application. Only notifications emitted synchronously by the call to `apply` are suppressed; edits during an asynchronous apply remain dirty. Before writing each record, `apply` must compare its current revision with the revision captured by `snapshot` and skip records that changed. Keep the check and write in one synchronous block or one IndexedDB readwrite transaction, and preserve local tombstones. The controller retries a merge if edits arrive before apply and checks the resulting snapshot afterwards. Keep tombstones long enough to cover offline devices; 90 days is a useful starting point.
|
|
53
|
+
|
|
54
|
+
Both code-based and scoped vaults accept the current `adapter.schema` and any versions listed in the optional `adapter.legacySchemas`. The vault passes the checkpoint's schema to `parse(value, schema)` so the adapter can validate each supported version and convert it to its current state format. Other schemas are rejected before parsing. Restoring a legacy checkpoint schedules a save, and every save writes the current schema.
|
|
55
|
+
|
|
56
|
+
Only include application data. Exclude API keys, service settings, access tokens, identity private keys, the vault code, and disposable caches. Arrays that represent sets should have a stable order to avoid unnecessary saves.
|
|
57
|
+
|
|
58
|
+
Pass a `createNode` factory that returns a fresh handle from your application's existing shared node scope on each call. The transport creates one handle per joined room, initializes it lazily, uses reliable delivery `0`, and releases it with `leaveRoom(room)`. Events without a room argument belong to that handle's room; explicitly tagged events from other rooms are ignored. Sharing the underlying scope with other network features is supported. `joinRoomAsync` is preferred when present; otherwise `joinRoom` is awaited. The default event numbers are raw `0`, connected `2`, disconnected `3`; override `events` for other bindings. The transport bounds control messages at 16 KiB and its pre-join queue at 64, and shares concurrent downloads for the same CID when handles use the same `storageGet` function.
|
|
59
|
+
|
|
60
|
+
## Preact settings
|
|
61
|
+
|
|
62
|
+
```tsx
|
|
63
|
+
import { VaultPanel } from '@tik-choco/mistvault/preact'
|
|
64
|
+
import type { VaultController } from '@tik-choco/mistvault'
|
|
65
|
+
import '@tik-choco/mistvault/ui.css'
|
|
66
|
+
|
|
67
|
+
export const Settings = ({ vault }: { vault: VaultController }) =>
|
|
68
|
+
<VaultPanel controller={vault} locale="ja" appName="Notebook" />
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`useVault(controller)` provides the current `VaultView` for a custom interface. `VaultPanel` includes setup actions, an app switch, status, save and restore actions, room configuration, masked code controls, confirmed imports, device links and attachment counts. The interface supports English, Japanese, Simplified Chinese and Traditional Chinese. An omitted locale uses `navigator.language`, with English as the fallback.
|
|
72
|
+
|
|
73
|
+
If the application consumes a device link before mounting the panel, pass its privately retained code as `pendingCode`. The panel asks for confirmation, then calls `onPendingHandled(result)` with `"imported"` or `"cancelled"`; clear `pendingCode` in that callback. Invalid supplied codes can be dismissed and report `"cancelled"`. A failed import remains available for retry. Importing a code while the vault is off turns it on in automatic mode after confirmation.
|
|
74
|
+
|
|
75
|
+
Set `--mv-fg`, `--mv-muted`, `--mv-border`, `--mv-accent`, and `--mv-bg` to match your application. Controls wrap at narrow widths and follow the system color scheme. Multiple panels can coexist without duplicate control IDs.
|
|
76
|
+
|
|
77
|
+
## Personal code and provider room
|
|
78
|
+
|
|
79
|
+
The default is **off**. Enabling generates a random 128-bit code and selects automatic mode. All applications on one origin share `tc-vault:settings-v1`; storage events update other tabs. Each application has separate encryption and signing keys and its own `tc-vault:app:<app>:v1` metadata. Importing another code resets every stored application's sequence, hashes and part inventory while retaining local application data and app preferences.
|
|
80
|
+
|
|
81
|
+
Automatic mode uses `deriveAutoRoom('tc-vault', code)` so one room serves all applications for a person. Add the displayed room in **mistl → Storage → Distributed vault**, or run:
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
mistl escrow rooms add <room>
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Watermarks and attachment inventories belong to the combination of code and effective room. Changing either resets that metadata before restore; local application data remains available to merge.
|
|
88
|
+
|
|
89
|
+
Anyone holding the code can read and write the vault. Store it securely. Device links place it in the URL fragment, never in a query parameter. `VaultPanel` removes the fragment when mounted and asks for confirmation before importing. Applications that mount settings later should call `consumeVaultLink()` on load, retain its returned code privately, and pass it as `pendingCode` or offer their own confirmation before calling `importCode`; consuming a link does not import it.
|
|
90
|
+
|
|
91
|
+
Code helpers accept uppercase and grouped input, then return lowercase canonical base32. Invalid trailing bits are rejected. `vaultLink(url, code)` creates a device link; `revealCode()` returns the current secret only on demand.
|
|
92
|
+
|
|
93
|
+
## Controller behavior
|
|
94
|
+
|
|
95
|
+
`createVault({ adapter, transport, storage?, now?, partGcGraceMs? })` returns:
|
|
96
|
+
|
|
97
|
+
| Method | Purpose |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `getView()`, `subscribe(cb)` | Observe mode, app preference, rooms, status, errors, timestamps, sequence and part counts. Subscription returns an unsubscribe function. |
|
|
100
|
+
| `enable()`, `disable()` | Set the shared personal vault to automatic mode or off. |
|
|
101
|
+
| `setAppEnabled(on)` | Change only this application's participation. |
|
|
102
|
+
| `configure(mode, room?)` | Select `auto`, `custom` or `off`; invalid rooms return `false`. |
|
|
103
|
+
| `importCode(code)`, `revealCode()` | Switch codes after caller confirmation, or read the current code. Invalid imports return `false`. |
|
|
104
|
+
| `saveNow()`, `restoreNow()` | Flush dirty data or explicitly restore and merge. Errors appear in the view. |
|
|
105
|
+
| `dispose()` | Stop networking, subscriptions, locks and timers. |
|
|
106
|
+
|
|
107
|
+
No node is created while inactive. Startup waits up to 20 seconds for a provider, then continues listening if none is available. Every session completes a restore attempt before uploading. Local changes persist a dirty flag and save after 8 seconds of quiet, with a 60-second maximum delay. Hidden-page and pagehide events attempt a flush. A save uses the preceding signed head's hash and next sequence; conflicts trigger restore, merge and retry, up to three attempts. Errors use a 60-second retry delay and may also be retried by another edit or manual action.
|
|
108
|
+
|
|
109
|
+
Join failures and provider loss trigger rejoining while visible, starting after five seconds and doubling up to sixty seconds. Returning online or making the page visible also retries discovery.
|
|
110
|
+
|
|
111
|
+
Where available, `navigator.locks` elects one writer per application. Followers publish edits through shared dirty metadata; the writer reads it before saving and on each visible poll. An ACK clears dirty only if the shared edit version and token still match the saved snapshot. Followers restore when the writer publishes local metadata and also check the remote head every 60 seconds while visible. A new lock holder restores before writing. Without that API, compare-and-swap and merge handle concurrent writes. Browser shutdown can interrupt best-effort flushing; local application persistence remains the adapter's responsibility.
|
|
112
|
+
|
|
113
|
+
Storage reads and writes tolerate unavailable or full localStorage. In that case the running controller retains its settings in memory, but cannot share or retain them across reloads.
|
|
114
|
+
|
|
115
|
+
## Per-scope vaults
|
|
116
|
+
|
|
117
|
+
A folder, ledger, or other shared item can have its own vault. Generate a random room ID with at least 128 bits of entropy for each item. Participants use that ID to join the application's realtime room and derive the item's main and attachment keys. Anyone who knows it can read and write the item's vault. Register the separate mistl room shown by the panel with the escrow provider.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { createScopeVaultManager, defaultScopeConfig } from '@tik-choco/mistvault'
|
|
121
|
+
|
|
122
|
+
const manager = createScopeVaultManager<FolderState>({ app: 'notes', nodeId, transportFor, storage })
|
|
123
|
+
manager.sync(folders.map(folder => ({
|
|
124
|
+
roomId: folder.roomId,
|
|
125
|
+
adapter: folder.adapter,
|
|
126
|
+
isWriter: () => [nodeId, ...livePeerIds(folder.roomId)].sort()[0] === nodeId,
|
|
127
|
+
defaultConfig: () => defaultScopeConfig(storage),
|
|
128
|
+
})))
|
|
129
|
+
|
|
130
|
+
const vault = manager.get(roomId)!
|
|
131
|
+
const unsubscribe = vault.onConfig(cfg => broadcast('vault-cfg', cfg))
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Pass the complete current scope list to `sync` after items change. Keep each item's adapter instance stable while it uses the same local store. The manager keeps one joined transport per effective mistl room and releases it after the last scope leaves. `manager.subscribe(cb)` reports scope and room changes. `manager.rooms()` returns the distinct active room names. Call `unsubscribe()` when detaching the realtime handler and `manager.dispose()` when closing the application.
|
|
135
|
+
|
|
136
|
+
For one item, call `createScopeVault({ app, roomId, adapter, transport, nodeId, isWriter?, defaultConfig?, storage?, now?, partGcGraceMs? })`. The transport can be an instance or a factory. The scope uses `deriveEscrowKeys(app, roomId)` and `derivePartKeys(app, roomId, part)`. Its local metadata and browser lock names use a hash of the app and room ID.
|
|
137
|
+
|
|
138
|
+
| Scope vault API | Behavior |
|
|
139
|
+
| --- | --- |
|
|
140
|
+
| `configure(mode, room?)` | Make a local default explicit or change the mode or room. Each accepted configuration advances the revision. A destination change resets its sequence, hashes and part inventory. Returns whether the change was accepted. |
|
|
141
|
+
| `materializeDefault()` | Wait for the local default to resolve, then persist and broadcast it as an explicit config. Resolves to `true` when it authors the config, or `false` if an explicit or adopted config already exists or the vault is disposed. |
|
|
142
|
+
| `getView()`, `subscribe(cb)` | Read or observe status, effective room, timestamps, parts, `providerSeen` and the current `config`. |
|
|
143
|
+
| `onConfig(cb)`, `receiveConfig(cfg, from)` | Broadcast explicit and adopted configurations over the realtime room. On peer hello, send `getView().config` only if `config.by` is nonempty. Local defaults have an empty author, including while the personal room resolves. `receiveConfig` accepts authored configurations by revision, then by author, and returns true on adoption. |
|
|
144
|
+
| `changed()`, `saveNow()`, `restoreNow()` | Signal an edit, flush pending edits, or restore and merge. Adapter change notifications also schedule saves. |
|
|
145
|
+
| `dispose()` | Detach immediately. On disposal or removal, an elected writer with pending edits attempts a final save in the background. The scope releases its lease when the attempt finishes or after 10 seconds. |
|
|
146
|
+
|
|
147
|
+
Automatic mode uses `deriveAutoRoom(app, roomId)`. Custom mode selects a provider room shared by any number of scopes. Off disables networking. `defaultScopeConfig(storage?)` resolves to a custom setting using the active personal vault's provider room, or to automatic when the personal vault is inactive. A scope uses this helper by default. A supplied `defaultConfig` may return a setting or a promise. Stored and shared configuration take precedence. For invite links, `scopeInviteParam(cfg)` returns `'auto'` for automatic (always explicit, because a joiner's own default may differ), `'off'` for off, or `c:<room>` for custom (the prefix keeps rooms named `auto` or `off` unambiguous; a bare room is still accepted). `parseScopeInviteParam(value)` returns the corresponding setting or `null` for an absent or invalid parameter.
|
|
148
|
+
|
|
149
|
+
The first restore precedes uploads. Startup waits up to 20 seconds for a provider in custom mode or after this scope has seen a provider. A new automatic scope keeps listening and retries discovery in the background. Saves use the same 8-second debounce and 60-second maximum delay as personal vaults. The controller checks `isWriter()` before writing. Followers retain pending edits for a later writer. Omitting `isWriter` allows this node to write.
|
|
150
|
+
|
|
151
|
+
Call `await vault.materializeDefault()` after registering `onConfig` when creating a scope locally or migrating an existing item. When rotating the room ID to stop sharing, use `configure` to carry over the old scope's effective mode and custom room. When joining via an invite or room ID, adopt the creator's config or use the invite's `mistl` setting.
|
|
152
|
+
|
|
153
|
+
Render `<ScopeVaultPanel vault={vault} />` from `@tik-choco/mistvault/preact` for an item's room settings, status, copy, save and restore controls. Pass `extraRooms={manager.rooms()}` to the personal `VaultPanel` to list and copy the additional rooms. Both panels accept `locale` and use the same stylesheet.
|
|
154
|
+
|
|
155
|
+
## Attachments
|
|
156
|
+
|
|
157
|
+
Add `adapter.parts` with `list(state)`, `read(id)`, `has(id)`, `write(id, bytes)` and optional `maxBytes`. IDs must match `[A-Za-z0-9_.:-]{1,128}`; content-addressed IDs such as `f:` plus a SHA-256 hex digest are recommended. Report the actual uncompressed size in `list`.
|
|
158
|
+
|
|
159
|
+
Parts derive distinct slot, AES-GCM and Ed25519 keys from the application's cached PBKDF2 master, without extra PBKDF2 work. New or changed attachments upload before the main checkpoint. Missing attachments download after restore with concurrency limited to two. The default maximum is 32 MiB minus 64 KiB. Oversized, locally missing and provider-quota-limited attachments are listed as omitted; the main checkpoint still saves. Omission metadata is local to each app and device.
|
|
160
|
+
|
|
161
|
+
Save and restore check provider heads even when bytes are available locally. A missing or deleted part invalidates its uploaded cache entry and is uploaded again from local bytes. Saves also recheck parts after the main ACK. If a restore cannot obtain bytes, the part stays pending and retries on later restores and visible polls; no placeholder bytes are written.
|
|
162
|
+
|
|
163
|
+
A part becomes eligible for collection only after every acknowledged or observed current main state has left it unreferenced for at least 24 hours. The per-part `unreferencedSince` timestamp persists across reloads and resets whenever references return. Set `partGcGraceMs` to a nonnegative duration in milliseconds to configure this grace. Collection verifies the tracked part's exact generation and rechecks the current main head immediately before deletion. A changed main head defers collection. Grace and repair mitigate delayed deletion races; excluding them completely requires provider-side reference counting. The uploaded cache entry is removed before DELETE, and a separate pending deletion record supports retries even if the ACK is lost. Collection runs in the background and requires providers supporting the `delete` feature. Providers supporting `delete-continue` can recreate a deleted slot using its next sequence and deleted-head parent. Collection concerns this application's previously recorded part slots only.
|
|
164
|
+
|
|
165
|
+
## Portable API
|
|
166
|
+
|
|
167
|
+
The root entry exports the controller, adapter, settings, code, transport and attachment interfaces above, plus:
|
|
168
|
+
|
|
169
|
+
- `EscrowClient`, `EscrowRequestError`; client methods `join`, `onProvider`, `waitForProvider`, `getHead`, `put`, `fetchLatest`, `saveCheckpoint`, `deleteSlot`, `dispose`, and the `providers` getter. Part methods are `fetchLatestWithKeys`, `saveWithKeys`, and `deleteWithKeys`.
|
|
170
|
+
- Keys and blob utilities: `deriveEscrowKeys`, `derivePartKeys`, `deriveAutoRoom`, `blobAAD`, `encryptBlob`, `decryptBlob`, `gzip`, `gunzip`, `supportsGzip`, `sha256`, `hex`, `fromHex`, `utf8`, `base64url`, `fromBase64url`.
|
|
171
|
+
- Signed heads and protocol: `parseHead`, `buildHead`, `signHead`, `verifyHead`, `headHash`, `signingPayload`, `stableStringify`, `parseDelete`, `signDelete`, `deleteSigningPayload`, `parseEscrowMessage`, `encodeEscrowMessage`, `ERROR_CODES`, `MAX_MESSAGE_BYTES`, `DEFAULT_MAX_BLOB`, `DEFAULT_MAX_PLAINTEXT`, `MAX_CID_BYTES`, `MAX_SCHEMA_BYTES`, `SLOT_RE`, `HASH_RE`, `safeInt`, `boundedText`, `isRecord`.
|
|
172
|
+
- Codes and settings: `generateVaultCode`, `parseVaultCode`, `canonicalizeVaultCode`, `vaultLink`, `consumeVaultLink`, `VAULT_CODE_RE`, `loadSettings`, `saveSettings`, `loadAppState`, `saveAppState`, `subscribeSettings`, `defaultSettings`, `defaultAppState`, `browserStorage`, `SETTINGS_KEY`, `appStateKey`, `validVaultRoom`.
|
|
173
|
+
- Attachments: `PART_ID_RE`, `PART_SCHEMA`, `DEFAULT_MAX_PART_BYTES`, `DEFAULT_PART_GC_GRACE_MS`, `observePartReferences`, `listedParts`, `mapParts`, `uploadParts`, `fetchParts`, `collectParts`.
|
|
174
|
+
- Localization: `messages`, `en`, `ja`, `zhCN`, `zhTW`, `resolveLocale`, `vaultMessage`.
|
|
175
|
+
|
|
176
|
+
Associated TypeScript types include `VaultOptions`, `VaultAdapter`, `VaultController`, `VaultView`, `VaultParts`, `PartContext`, `VaultMode`, `VaultSettings`, `VaultAppState`, `PartState`, `MistNodeLike`, `MistVaultTransportOptions`, `VaultLocale`, `VaultMessages`, `EscrowKeys`, `UnsignedHead`, `EscrowHead`, `HeadValidation`, `DeleteFields`, `SignedDelete`, `EscrowTransport`, `Unsubscribe`, `ClientErrorCode`, `PutResult`, `DeleteResult`, `EscrowClientOptions`, `CheckpointOptions`, `ProtocolLimits`, and all `EscrowMessage` variants. Scoped vault types include `ScopeConfig`, `ScopeVaultOptions`, `ScopeVaultView`, `ScopeVault`, `ManagedScope`, `ScopeVaultManagerOptions`, and `ScopeVaultManager`. The Preact entry exports `VaultPanel`, `ScopeVaultPanel`, their prop types, and `useVault`.
|
|
177
|
+
|
|
178
|
+
`EscrowClient.join(true)` reacquires membership when no providers remain; ordinary `join()` keeps its existing behavior. `onProvider` also signals departures, so listeners should read `providers` to determine availability. Deletion returns the existing `error` result with code `transport` when evicted provenance prevents confirming every copy was removed. The wire protocol is unchanged. Optional app metadata fields `scope`, `editVersion`, `editToken`, `pendingDeletes`, `partsObservedSeq`, `PartState.headHash`, and `PartState.unreferencedSince` are managed by the controller and remain compatible with older stored state.
|
|
179
|
+
|
|
180
|
+
Web Crypto with Ed25519, AES-GCM, PBKDF2 and HKDF is required. Compression uses browser streams when available. Provider ACKs confirm persistence at the accepting provider; replication proceeds according to mistl's configuration. Keep independent backups for data you cannot replace.
|
|
181
|
+
|
|
182
|
+
## License
|
|
183
|
+
|
|
184
|
+
MPL-2.0. See [LICENSE](LICENSE).
|
package/README.zh.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# mistvault
|
|
2
|
+
|
|
3
|
+
面向 TypeScript 应用的分布式保管库。数据在浏览器中加密,通过 mistl 的 `tc-escrow v1` 协议保存。核心没有运行时依赖;可选的设置面板使用 Preact 10。
|
|
4
|
+
|
|
5
|
+
[English / 完整 API](README.md) · [日本語](README.ja.md)
|
|
6
|
+
|
|
7
|
+
## 安装
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @tik-choco/mistvault
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`dist/` 不纳入版本控制。开发时运行 `npm install`、`npm run build` 和 `npm test`。
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createVault, createMistVaultTransport } from '@tik-choco/mistvault'
|
|
17
|
+
|
|
18
|
+
const vault = createVault({
|
|
19
|
+
adapter,
|
|
20
|
+
transport: () => createMistVaultTransport({ createNode, storageAdd, storageGet }),
|
|
21
|
+
})
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
为 `adapter` 设置稳定的 `app` 标识和带版本的 `schema`,并实现 `snapshot`、`parse`、`merge`、`apply`、`subscribe`。`parse` 必须验证远程 JSON,无效时抛出异常。`merge` 必须具有确定性和幂等性,保留双方较新的记录与删除标记;时间相同时也应使用固定的决胜规则。删除标记应保留足够长的离线同步时间,例如 90 天。`apply` 保存合并结果并刷新界面,仅抑制调用同步触发的通知,异步应用期间的编辑仍记为待保存。逐条写入前,应比较当前版本与快照捕获的版本,跳过已变化的记录;比较和写入须在同一同步代码段或 IndexedDB readwrite 事务内完成,并保留本地删除标记。控制器也会在应用前检测编辑并重新合并,完成后再次检查本地状态。
|
|
25
|
+
|
|
26
|
+
使用保管库代码连接的保管库和按项目划分的保管库都支持恢复当前 `adapter.schema` 以及可选的 `adapter.legacySchemas` 所列的旧版。`parse(value, schema)` 的第二个参数是检查点的模式版本,适配器可据此验证数据并转换为当前格式。其他版本会在解析前被拒绝。恢复旧版检查点后会安排一次保存,每次保存都使用当前模式版本。
|
|
27
|
+
|
|
28
|
+
快照仅包含应用数据。不要包含 API 密钥、服务设置、令牌、身份私钥、保管库代码或可重新生成的缓存。
|
|
29
|
+
|
|
30
|
+
`createNode` 每次调用应从应用现有的共享节点作用域返回一个新句柄。传输层为每个房间创建一个句柄,以 `leaveRoom(room)` 释放。不带房间参数的事件归属该句柄的房间,明确标记为其他房间的事件会被忽略。节点按需初始化。传入现有的 `storageAdd` 和 `storageGet` 函数即可。可靠传输编号为 `0`,控制消息最大 16 KiB,加入房间前的队列最多 64 条。默认事件编号为 `raw: 0`、`peerConnected: 2`、`peerDisconnected: 3`,可通过 `events` 调整。使用相同 `storageGet` 函数的句柄会共享同一 CID 的并发下载。
|
|
31
|
+
|
|
32
|
+
## 设置面板
|
|
33
|
+
|
|
34
|
+
```tsx
|
|
35
|
+
import { VaultPanel } from '@tik-choco/mistvault/preact'
|
|
36
|
+
import '@tik-choco/mistvault/ui.css'
|
|
37
|
+
|
|
38
|
+
<VaultPanel controller={vault} locale="zh-CN" appName="笔记本" />
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
面板包含启用与导入操作、应用开关、状态、保存与恢复按钮、房间配置、隐藏的代码、复制、其他设备链接、确认导入及附件统计。自定义界面可使用 `useVault(vault)`。支持英语、日语、简体中文和繁体中文;繁体中文使用 `locale="zh-TW"`,省略时使用浏览器语言,未知语言回退到英语。
|
|
42
|
+
|
|
43
|
+
如果应用在面板挂载前读取了设备链接,可将私下保存的代码传给 `pendingCode`。确认导入或取消后,`onPendingHandled(result)` 会收到 `"imported"` 或 `"cancelled"`;请在回调中清除 `pendingCode`。关闭无效代码提示也会返回 `"cancelled"`。保管库关闭时确认导入,会以自动模式启用保管库。
|
|
44
|
+
|
|
45
|
+
通过 `--mv-fg`、`--mv-muted`、`--mv-border`、`--mv-accent` 和 `--mv-bg` 调整颜色。布局会在窄屏换行,并遵循系统的明暗主题。
|
|
46
|
+
|
|
47
|
+
## 个人代码与房间
|
|
48
|
+
|
|
49
|
+
默认关闭。启用时生成随机的 128 位保管库代码并切换到自动模式。同一来源的应用共享 `tc-vault:settings-v1`,通过存储事件跟随其他标签页的修改。每个应用的元数据保存在 `tc-vault:app:<app>:v1`。导入其他代码会重置所有已存应用的序列、哈希和附件记录,但保留本地应用数据及各应用开关。
|
|
50
|
+
|
|
51
|
+
自动房间由 `deriveAutoRoom('tc-vault', code)` 计算,所有应用共用一个个人房间。将显示的房间添加到 mistl 的“存储 → 分布式保管库”,或运行:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
mistl escrow rooms add <room>
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
持有代码的人可以读写整个保管库,请妥善保密。设备链接将代码放在 URL 片段中。面板挂载时移除该片段,只有明确确认后才导入。如果应用稍后才显示设置面板,应在启动时调用 `consumeVaultLink()`,私下保留返回的代码,然后传给 `pendingCode`,或在用户确认后调用 `importCode`。读取并移除链接本身不会导入代码。
|
|
58
|
+
|
|
59
|
+
## 控制器
|
|
60
|
+
|
|
61
|
+
序列与附件缓存属于代码和实际房间的组合,任一变化都会重置。加入失败或提供者离开后,可见页面会从 5 秒开始重试加入,等待时间逐次翻倍,最多 60 秒;online 事件也触发重试。跟随标签页将编辑写入共享的待保存标志与编辑版本,写入标签页在保存前及轮询时读取,只有快照之后没有新编辑才清除标志。
|
|
62
|
+
|
|
63
|
+
- `getView()` / `subscribe(cb)`:读取或订阅模式、房间、状态、错误、时间、序列和附件统计。
|
|
64
|
+
- `enable()` / `disable()`:将共享保管库设为自动模式或关闭。
|
|
65
|
+
- `setAppEnabled(on)`:仅切换当前应用。
|
|
66
|
+
- `configure(mode, room?)`:配置 `auto` / `custom` / `off`;房间无效时返回 `false`。
|
|
67
|
+
- `importCode(code)` / `revealCode()`:导入已确认的代码或读取当前代码;无效导入返回 `false`。
|
|
68
|
+
- `saveNow()` / `restoreNow()`:保存待同步数据,或恢复并合并远程数据。
|
|
69
|
+
- `dispose()`:清理计时器、订阅、锁和网络连接。
|
|
70
|
+
|
|
71
|
+
未启用时不创建节点。启动后最多等待提供者 20 秒,超时后继续监听。首次成功尝试恢复前不会上传。变更后静默 8 秒保存,连续变更最多延迟 60 秒。页面隐藏或离开时尽力刷新。冲突会触发获取、合并和重试,最多尝试 3 次;错误显示在状态中,并在 60 秒后、下一次变更或手动操作时重试。
|
|
72
|
+
|
|
73
|
+
可用时通过 `navigator.locks` 为每个应用保留一个写入标签页。其他标签页收到本地保存通知后恢复,并在可见时每 60 秒检查远程头。锁交接后也先恢复再写入。不支持锁时通过协议的比较交换和合并处理并发。浏览器关闭可能中断刷新,因此应用仍需自行持久化本地数据。localStorage 不可用或已满时,当前控制器仍保留内存设置,但无法跨刷新保留或跨标签页共享。
|
|
74
|
+
|
|
75
|
+
## 按项目划分的保管库
|
|
76
|
+
|
|
77
|
+
每个文件夹或账本都可以有独立的保管库。为每个项目生成至少 128 位的随机房间 ID。参与者使用该 ID 加入应用的实时房间,并派生主数据和附件的密钥。持有 ID 的人可以读写该项目的保管库。在 mistl 托管设置中注册面板显示的另一个房间。
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { createScopeVaultManager, defaultScopeConfig } from '@tik-choco/mistvault'
|
|
81
|
+
|
|
82
|
+
const manager = createScopeVaultManager<FolderState>({ app: 'notes', nodeId, transportFor, storage })
|
|
83
|
+
manager.sync(folders.map(folder => ({
|
|
84
|
+
roomId: folder.roomId,
|
|
85
|
+
adapter: folder.adapter,
|
|
86
|
+
isWriter: () => [nodeId, ...livePeerIds(folder.roomId)].sort()[0] === nodeId,
|
|
87
|
+
defaultConfig: () => defaultScopeConfig(storage),
|
|
88
|
+
})))
|
|
89
|
+
|
|
90
|
+
const vault = manager.get(roomId)!
|
|
91
|
+
const unsubscribe = vault.onConfig(cfg => broadcast('vault-cfg', cfg))
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
项目增删后,将当前所有项目传给 `manager.sync`。使用同一本地存储时,请复用各项目的适配器实例。管理器为每个实际使用的 mistl 房间共享一个连接,最后一个项目离开时释放连接。`manager.get(roomId)` 返回对应的保管库,`manager.rooms()` 列出所有正在使用的房间,`manager.subscribe(cb)` 通知项目和房间变化。解除订阅时调用返回的函数,关闭应用时调用 `manager.dispose()`。
|
|
95
|
+
|
|
96
|
+
单个项目可使用 `createScopeVault({ app, roomId, adapter, transport, nodeId, isWriter?, defaultConfig?, storage?, now?, partGcGraceMs? })`。`transport` 可传实例或工厂。主数据使用 `deriveEscrowKeys(app, roomId)`,附件使用 `derivePartKeys(app, roomId, part)`。本地存储键和浏览器锁名称使用应用标识与房间 ID 的哈希。
|
|
97
|
+
|
|
98
|
+
通过 `configure(mode, room?)` 显式选用当前默认配置或更改模式、房间后,版本号会递增。保存目标变更时会重置序列、哈希和附件清单。通过 `onConfig(cb)` 广播显式设置或已采纳的共享配置。新成员加入时,仅当 `getView().config` 的 `by` 非空时才发送该配置。个人房间推导期间和完成后,本地默认配置的 `by` 均为空。收到配置后调用 `receiveConfig(cfg, from)`,采纳时返回 `true`。采纳首份共享配置后,版本号较大者优先,同版本时按作者节点 ID 的字典顺序取较大者。`getView()` 和 `subscribe(cb)` 可读取或订阅配置、状态、房间、时间、附件统计以及 `providerSeen`。
|
|
99
|
+
|
|
100
|
+
自动模式使用 `deriveAutoRoom(app, roomId)`,自定义模式使用指定房间,关闭模式停用网络。默认的异步函数 `defaultScopeConfig(storage?)` 在个人保管库启用时返回其 mistl 房间对应的自定义配置,停用时返回自动配置。可通过 `defaultConfig` 提供返回配置或 Promise 的函数。已有的本地配置和共享配置优先。生成邀请链接时,`scopeInviteParam(cfg)` 在自动模式下返回 `'auto'`(参与者的默认值可能不同,因此始终显式写出),关闭时返回 `'off'`,自定义模式下返回 `c:<房间名>`(用于区分名为 `auto` 或 `off` 的房间;也接受不带前缀的房间名)。`parseScopeInviteParam(value)` 返回相应配置,参数缺失或无效时返回 `null`。
|
|
101
|
+
|
|
102
|
+
首次恢复后才开始上传。在自定义模式下,或该项目曾发现提供者时,启动时最多等待 20 秒。首次使用自动模式会在后台继续发现提供者。适配器的变更通知或 `changed()` 会安排保存,静默 8 秒后写入,连续编辑最多延迟 60 秒。`isWriter()` 为假时保留待保存的编辑,取得写入资格后再保存。省略时允许当前节点写入。`saveNow()` 立即保存待处理编辑,`restoreNow()` 恢复并合并数据,`dispose()` 立即返回。关闭或移除项目时,有待保存编辑的写入节点会在后台尝试最后一次保存,完成后或满 10 秒时释放连接。
|
|
103
|
+
|
|
104
|
+
在本地创建或迁移项目时,先注册 `onConfig`,再调用 `await vault.materializeDefault()`。该方法等待本地默认配置就绪,将其保存并广播为显式配置,成功时返回 `true`。如果已有显式配置或已采纳共享配置,或者保管库已经释放,则返回 `false`。停止共享并更换房间 ID 时,用 `configure` 继承原项目的模式及自定义房间。通过邀请或房间 ID 加入时,采纳创建者的配置或使用邀请中的 `mistl` 设置。
|
|
105
|
+
|
|
106
|
+
使用 `@tik-choco/mistvault/preact` 的 `<ScopeVaultPanel vault={vault} />` 显示项目设置、状态以及房间复制、保存和恢复操作。为个人 `VaultPanel` 传入 `extraRooms={manager.rooms()}`,即可列出并一键复制其他房间。两个面板共用样式表,均支持 `locale`。
|
|
107
|
+
|
|
108
|
+
## 附件
|
|
109
|
+
|
|
110
|
+
在 `adapter.parts` 中提供 `list(state)`、`read(id)`、`has(id)`、`write(id, bytes)`,以及可选的 `maxBytes`。ID 必须符合 `[A-Za-z0-9_.:-]{1,128}`,大小是未压缩的实际字节数。建议使用 `f:` 加内容 SHA-256 的标识。
|
|
111
|
+
|
|
112
|
+
附件复用应用已缓存的 PBKDF2 主密钥,通过 HKDF 派生独立槽位、加密和签名密钥,不会为每个附件重复执行 PBKDF2。新增或变化的附件先上传,然后保存主快照。恢复后以最多两个并发下载缺少的附件。默认上限为 32 MiB − 64 KiB。过大的、本地缺少的或因提供者配额受限的附件记为省略,主快照仍会保存。省略记录属于当前设备的应用元数据。
|
|
113
|
+
|
|
114
|
+
保存和恢复时,即使本地已有附件也会检查提供者头;若附件缺失或已删除,会使上传缓存失效并使用本地字节重新上传。主快照确认后也会再次检查。无法获取的附件保持待处理,在后续恢复和页面可见时的定期检查中重试,不写入占位字节。
|
|
115
|
+
|
|
116
|
+
只有在所有已确认或已观察到的当前主快照中持续至少24小时未被引用的附件,才会成为删除候选。每个附件的 `unreferencedSince` 会持久保存,引用重新出现时重置。可通过 `partGcGraceMs` 指定非负的毫秒数来调整宽限期。宽限期和修复可缓解延迟删除的竞态,完全排除竞态需要提供者端的引用计数。删除前验证附件的确切版本,并再次确认主快照的头未改变;若已改变则推迟删除。发送删除前先清除上传缓存,将重试信息另存,因此确认丢失后仍能重新引入附件。此操作需要提供者支持 `delete`。支持 `delete-continue` 的提供者允许以删除头的下一序列重新创建槽位。
|
|
117
|
+
|
|
118
|
+
## 核心与许可
|
|
119
|
+
|
|
120
|
+
`EscrowClient.join(true)` 在没有提供者时重新取得房间成员资格。`onProvider` 也通知离开事件,监听者应读取 `providers` 判断当前状态。头的来源记录被淘汰后,无法保证所有副本均已删除,删除操作返回现有的 `error` 结果及 `transport` 代码。通信格式与适配器必需 API 保持兼容。
|
|
121
|
+
|
|
122
|
+
还公开 `EscrowClient`、`deriveEscrowKeys`、`derivePartKeys`、`deriveAutoRoom`、签名与验证、协议解析及各项限制。附件密钥可通过 `fetchLatestWithKeys`、`saveWithKeys`、`deleteWithKeys` 使用。完整符号与类型列表见 [英文 README](README.md#portable-api)。
|
|
123
|
+
|
|
124
|
+
需要 Web Crypto 支持 Ed25519、AES-GCM、PBKDF2 和 HKDF。可用时使用浏览器压缩流。确认表示接收提供者已经持久保存,副本同步遵循 mistl 的配置。不可替代的数据仍应保留独立备份。
|
|
125
|
+
|
|
126
|
+
MPL-2.0,详见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface PartState {
|
|
2
|
+
seq: number;
|
|
3
|
+
hash: string;
|
|
4
|
+
headHash?: string;
|
|
5
|
+
unreferencedSince?: number;
|
|
6
|
+
}
|
|
7
|
+
export interface VaultAppState {
|
|
8
|
+
v: 1;
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
lastSeq: number;
|
|
11
|
+
lastHash: string | null;
|
|
12
|
+
dirty: boolean;
|
|
13
|
+
savedAt: number;
|
|
14
|
+
restoredAt: number;
|
|
15
|
+
parts: Record<string, PartState>;
|
|
16
|
+
omitted: string[];
|
|
17
|
+
scope?: string;
|
|
18
|
+
editVersion?: number;
|
|
19
|
+
editToken?: string;
|
|
20
|
+
pendingDeletes?: Record<string, PartState>;
|
|
21
|
+
partsObservedSeq?: number;
|
|
22
|
+
}
|
|
23
|
+
export declare const defaultAppState: () => VaultAppState;
|
|
24
|
+
export declare function parseAppState(v: unknown): VaultAppState;
|
package/dist/appState.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { isRecord, safeInt, HASH_RE } from './core/head.js';
|
|
2
|
+
import { PART_ID_RE } from './core/crypto.js';
|
|
3
|
+
export const defaultAppState = () => ({ v: 1, enabled: true, lastSeq: 0, lastHash: null,
|
|
4
|
+
dirty: false, savedAt: 0, restoredAt: 0, parts: {}, omitted: [] });
|
|
5
|
+
export function parseAppState(v) {
|
|
6
|
+
const validParts = (parts) => isRecord(parts) && Object.entries(parts).every(([id, p]) => PART_ID_RE.test(id) && isRecord(p) && safeInt(p.seq, 1) && typeof p.hash === 'string' && HASH_RE.test(p.hash) &&
|
|
7
|
+
(p.headHash === undefined || typeof p.headHash === 'string' && HASH_RE.test(p.headHash)) &&
|
|
8
|
+
(p.unreferencedSince === undefined || safeInt(p.unreferencedSince, 0)));
|
|
9
|
+
if (!isRecord(v) || v.v !== 1 || typeof v.enabled !== 'boolean' || typeof v.dirty !== 'boolean' ||
|
|
10
|
+
!safeInt(v.lastSeq, 0) || !(v.lastHash === null || typeof v.lastHash === 'string' && HASH_RE.test(v.lastHash)) ||
|
|
11
|
+
(v.lastSeq === 0) !== (v.lastHash === null) || !safeInt(v.savedAt, 0) || !safeInt(v.restoredAt, 0) ||
|
|
12
|
+
!validParts(v.parts) || (v.pendingDeletes !== undefined && !validParts(v.pendingDeletes)) ||
|
|
13
|
+
(v.partsObservedSeq !== undefined && !safeInt(v.partsObservedSeq, 0)) ||
|
|
14
|
+
(v.scope !== undefined && typeof v.scope !== 'string') ||
|
|
15
|
+
(v.editVersion !== undefined && !safeInt(v.editVersion, 0)) ||
|
|
16
|
+
(v.editToken !== undefined && typeof v.editToken !== 'string') ||
|
|
17
|
+
!Array.isArray(v.omitted) || !v.omitted.every(id => typeof id === 'string' && PART_ID_RE.test(id)))
|
|
18
|
+
return defaultAppState();
|
|
19
|
+
return v;
|
|
20
|
+
}
|
package/dist/code.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const VAULT_CODE_RE: RegExp;
|
|
2
|
+
export declare function generateVaultCode(): string;
|
|
3
|
+
export declare function parseVaultCode(input: unknown): string | null;
|
|
4
|
+
export declare function canonicalizeVaultCode(input: string): string;
|
|
5
|
+
export declare function vaultLink(url: string, code: string): string;
|
|
6
|
+
/** Removes a device-link secret immediately; callers must ask before importing it. */
|
|
7
|
+
export declare function consumeVaultLink(location?: Pick<Location, 'href'>, history?: Pick<History, 'replaceState' | 'state'>): string | null;
|
package/dist/code.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';
|
|
2
|
+
export const VAULT_CODE_RE = /^tcv1-[a-z2-7]{26}$/;
|
|
3
|
+
export function generateVaultCode() {
|
|
4
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
5
|
+
let value = 0, bits = 0, result = 'tcv1-';
|
|
6
|
+
for (const byte of bytes) {
|
|
7
|
+
value = (value << 8) | byte;
|
|
8
|
+
bits += 8;
|
|
9
|
+
while (bits >= 5) {
|
|
10
|
+
bits -= 5;
|
|
11
|
+
result += alphabet[(value >>> bits) & 31];
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
if (bits)
|
|
15
|
+
result += alphabet[(value << (5 - bits)) & 31];
|
|
16
|
+
return result;
|
|
17
|
+
}
|
|
18
|
+
export function parseVaultCode(input) {
|
|
19
|
+
if (typeof input !== 'string')
|
|
20
|
+
return null;
|
|
21
|
+
const text = input.trim().toLowerCase();
|
|
22
|
+
if (!text.startsWith('tcv1-'))
|
|
23
|
+
return null;
|
|
24
|
+
const code = 'tcv1-' + text.slice(5).replace(/[\s-]/g, '');
|
|
25
|
+
// 128 bits use only the top three bits of the final base32 character.
|
|
26
|
+
return VAULT_CODE_RE.test(code) && (alphabet.indexOf(code.at(-1)) & 3) === 0 ? code : null;
|
|
27
|
+
}
|
|
28
|
+
export function canonicalizeVaultCode(input) {
|
|
29
|
+
const code = parseVaultCode(input);
|
|
30
|
+
if (!code)
|
|
31
|
+
throw new Error('Invalid vault code');
|
|
32
|
+
return code;
|
|
33
|
+
}
|
|
34
|
+
export function vaultLink(url, code) {
|
|
35
|
+
const target = new URL(url);
|
|
36
|
+
target.hash = 'tc-vault=' + canonicalizeVaultCode(code);
|
|
37
|
+
return target.href;
|
|
38
|
+
}
|
|
39
|
+
/** Removes a device-link secret immediately; callers must ask before importing it. */
|
|
40
|
+
export function consumeVaultLink(location = window.location, history = window.history) {
|
|
41
|
+
const url = new URL(location.href), params = new URLSearchParams(url.hash.slice(1));
|
|
42
|
+
if (!params.has('tc-vault'))
|
|
43
|
+
return null;
|
|
44
|
+
const code = parseVaultCode(params.get('tc-vault'));
|
|
45
|
+
params.delete('tc-vault');
|
|
46
|
+
url.hash = params.toString();
|
|
47
|
+
history.replaceState(history.state, '', url.href);
|
|
48
|
+
return code;
|
|
49
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { EscrowTransport } from './core/client.js';
|
|
2
|
+
import type { VaultMode } from './settings.js';
|
|
3
|
+
import type { VaultParts } from './parts.js';
|
|
4
|
+
export interface VaultAdapter<S> {
|
|
5
|
+
app: string;
|
|
6
|
+
schema: string;
|
|
7
|
+
legacySchemas?: readonly string[];
|
|
8
|
+
snapshot(): S | Promise<S>;
|
|
9
|
+
/** `schema` is the restored head's schema (adapter.schema or one of legacySchemas); optional for callers written before it existed. */
|
|
10
|
+
parse(value: unknown, schema?: string): S;
|
|
11
|
+
merge(local: S, remote: S): S;
|
|
12
|
+
apply(next: S): void | Promise<void>;
|
|
13
|
+
subscribe(onChange: () => void): () => void;
|
|
14
|
+
parts?: VaultParts<S>;
|
|
15
|
+
}
|
|
16
|
+
export interface VaultView {
|
|
17
|
+
mode: VaultMode;
|
|
18
|
+
appEnabled: boolean;
|
|
19
|
+
room: string;
|
|
20
|
+
autoRoom: string;
|
|
21
|
+
hasCode: boolean;
|
|
22
|
+
status: 'off' | 'searching' | 'noProvider' | 'restoring' | 'saving' | 'saved' | 'restored' | 'upToDate' | 'error';
|
|
23
|
+
error?: string;
|
|
24
|
+
savedAt: number;
|
|
25
|
+
restoredAt: number;
|
|
26
|
+
lastSeq: number;
|
|
27
|
+
parts: {
|
|
28
|
+
stored: number;
|
|
29
|
+
pending: number;
|
|
30
|
+
omitted: number;
|
|
31
|
+
};
|
|
32
|
+
hasParts?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface VaultController {
|
|
35
|
+
getView(): VaultView;
|
|
36
|
+
subscribe(cb: (view: VaultView) => void): () => void;
|
|
37
|
+
enable(): void;
|
|
38
|
+
disable(): void;
|
|
39
|
+
setAppEnabled(on: boolean): void;
|
|
40
|
+
configure(mode: VaultMode, room?: string): boolean;
|
|
41
|
+
importCode(code: string): boolean;
|
|
42
|
+
revealCode(): string | null;
|
|
43
|
+
saveNow(): Promise<void>;
|
|
44
|
+
restoreNow(): Promise<void>;
|
|
45
|
+
dispose(): void;
|
|
46
|
+
}
|
|
47
|
+
export interface VaultOptions<S> {
|
|
48
|
+
adapter: VaultAdapter<S>;
|
|
49
|
+
transport: EscrowTransport | (() => EscrowTransport);
|
|
50
|
+
storage?: Storage;
|
|
51
|
+
now?: () => number;
|
|
52
|
+
/** Minimum observed time without main references before collecting a part. Defaults to 24 hours. */
|
|
53
|
+
partGcGraceMs?: number;
|
|
54
|
+
}
|
|
55
|
+
export declare function createVault<S>(o: VaultOptions<S>): VaultController;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { generateVaultCode, parseVaultCode } from './code.js';
|
|
2
|
+
import { browserStorage, defaultAppState, loadAppState, loadSettings, saveAppState, saveSettings, subscribeSettings, validVaultRoom } from './settings.js';
|
|
3
|
+
import { createVaultSession } from './session.js';
|
|
4
|
+
export function createVault(o) {
|
|
5
|
+
const app = o.adapter.app, storage = o.storage ?? browserStorage();
|
|
6
|
+
let settings = loadSettings(storage), writing = false, disposed = false;
|
|
7
|
+
const core = createVaultSession({
|
|
8
|
+
...o, app, autoRoomApp: 'tc-vault', lockName: 'tc-vault:' + app,
|
|
9
|
+
loadState: () => loadAppState(app, storage), saveState: state => saveAppState(app, state, storage),
|
|
10
|
+
acquire: () => ({ transport: typeof o.transport === 'function' ? o.transport() : o.transport }),
|
|
11
|
+
});
|
|
12
|
+
function start(next, enabled) {
|
|
13
|
+
const codeChanged = settings.code !== next.code;
|
|
14
|
+
settings = next;
|
|
15
|
+
if (codeChanged)
|
|
16
|
+
core.resetState({ ...defaultAppState(), enabled, dirty: core.state.dirty });
|
|
17
|
+
else
|
|
18
|
+
core.state.enabled = enabled;
|
|
19
|
+
core.start(settings);
|
|
20
|
+
if (codeChanged)
|
|
21
|
+
core.persist();
|
|
22
|
+
}
|
|
23
|
+
function readSettings() {
|
|
24
|
+
if (disposed || writing || core.writing)
|
|
25
|
+
return;
|
|
26
|
+
const next = loadSettings(storage), shared = loadAppState(app, storage), old = settings;
|
|
27
|
+
const codeChanged = next.code !== old.code, enableChanged = shared.enabled !== core.state.enabled;
|
|
28
|
+
if (codeChanged || enableChanged || next.mode !== old.mode || next.room !== old.room)
|
|
29
|
+
start(next, shared.enabled);
|
|
30
|
+
else {
|
|
31
|
+
settings = next;
|
|
32
|
+
core.sharedStateChanged(shared);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function applySettings(next) {
|
|
36
|
+
writing = true;
|
|
37
|
+
try {
|
|
38
|
+
saveSettings(next, storage);
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
writing = false;
|
|
42
|
+
}
|
|
43
|
+
start(next, core.state.enabled);
|
|
44
|
+
}
|
|
45
|
+
function configure(mode, room = '') {
|
|
46
|
+
if (disposed || !['auto', 'custom', 'off'].includes(mode) || mode === 'custom' && !validVaultRoom(room))
|
|
47
|
+
return false;
|
|
48
|
+
applySettings({ ...settings, mode, room: mode === 'custom' ? room : '',
|
|
49
|
+
code: settings.code || (mode !== 'off' ? generateVaultCode() : '') });
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
const offSettings = subscribeSettings(readSettings, storage, globalThis.window, app);
|
|
53
|
+
core.start(settings);
|
|
54
|
+
return {
|
|
55
|
+
getView: core.getView, subscribe: core.subscribe,
|
|
56
|
+
enable: () => { configure('auto'); }, disable: () => { configure('off'); }, configure,
|
|
57
|
+
setAppEnabled(on) { if (!disposed) {
|
|
58
|
+
core.state.enabled = on;
|
|
59
|
+
core.persist();
|
|
60
|
+
core.start(settings);
|
|
61
|
+
} },
|
|
62
|
+
importCode(input) {
|
|
63
|
+
const code = parseVaultCode(input);
|
|
64
|
+
if (!code || disposed)
|
|
65
|
+
return false;
|
|
66
|
+
if (code !== settings.code)
|
|
67
|
+
applySettings({ ...settings, code });
|
|
68
|
+
return true;
|
|
69
|
+
},
|
|
70
|
+
revealCode: () => settings.code || null,
|
|
71
|
+
saveNow: core.saveNow, restoreNow: core.restoreNow,
|
|
72
|
+
dispose() { disposed = true; offSettings(); core.dispose(); },
|
|
73
|
+
};
|
|
74
|
+
}
|