@evolu/common 6.0.1-preview.9 → 7.0.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.
Files changed (184) hide show
  1. package/README.md +2 -2
  2. package/dist/src/Array.d.ts +256 -12
  3. package/dist/src/Array.d.ts.map +1 -1
  4. package/dist/src/Array.js +215 -9
  5. package/dist/src/Assert.d.ts +0 -13
  6. package/dist/src/Assert.d.ts.map +1 -1
  7. package/dist/src/Assert.js +0 -15
  8. package/dist/src/Brand.d.ts +75 -0
  9. package/dist/src/Brand.d.ts.map +1 -0
  10. package/dist/src/Brand.js +1 -0
  11. package/dist/src/Buffer.d.ts +1 -1
  12. package/dist/src/Buffer.d.ts.map +1 -1
  13. package/dist/src/Buffer.js +8 -7
  14. package/dist/src/Cache.d.ts +44 -0
  15. package/dist/src/Cache.d.ts.map +1 -0
  16. package/dist/src/Cache.js +52 -0
  17. package/dist/src/Callbacks.d.ts +45 -12
  18. package/dist/src/Callbacks.d.ts.map +1 -1
  19. package/dist/src/Callbacks.js +14 -7
  20. package/dist/src/Console.d.ts +31 -6
  21. package/dist/src/Console.d.ts.map +1 -1
  22. package/dist/src/Console.js +72 -9
  23. package/dist/src/Crypto.d.ts +56 -42
  24. package/dist/src/Crypto.d.ts.map +1 -1
  25. package/dist/src/Crypto.js +40 -53
  26. package/dist/src/Evolu/Db.d.ts +162 -74
  27. package/dist/src/Evolu/Db.d.ts.map +1 -1
  28. package/dist/src/Evolu/Db.js +284 -702
  29. package/dist/src/Evolu/Diff.d.ts +3 -3
  30. package/dist/src/Evolu/Diff.d.ts.map +1 -1
  31. package/dist/src/Evolu/Diff.js +7 -5
  32. package/dist/src/Evolu/Evolu.d.ts +213 -133
  33. package/dist/src/Evolu/Evolu.d.ts.map +1 -1
  34. package/dist/src/Evolu/Evolu.js +189 -180
  35. package/dist/src/Evolu/Internal.d.ts +0 -2
  36. package/dist/src/Evolu/Internal.d.ts.map +1 -1
  37. package/dist/src/Evolu/Internal.js +0 -2
  38. package/dist/src/Evolu/LocalAuth.d.ts +150 -0
  39. package/dist/src/Evolu/LocalAuth.d.ts.map +1 -0
  40. package/dist/src/Evolu/LocalAuth.js +174 -0
  41. package/dist/src/Evolu/Owner.d.ts +273 -120
  42. package/dist/src/Evolu/Owner.d.ts.map +1 -1
  43. package/dist/src/Evolu/Owner.js +130 -104
  44. package/dist/src/Evolu/Platform.d.ts +9 -7
  45. package/dist/src/Evolu/Platform.d.ts.map +1 -1
  46. package/dist/src/Evolu/Protocol.d.ts +268 -240
  47. package/dist/src/Evolu/Protocol.d.ts.map +1 -1
  48. package/dist/src/Evolu/Protocol.js +595 -447
  49. package/dist/src/Evolu/Public.d.ts +6 -8
  50. package/dist/src/Evolu/Public.d.ts.map +1 -1
  51. package/dist/src/Evolu/Public.js +2 -3
  52. package/dist/src/Evolu/PublicKysely.d.ts.map +1 -1
  53. package/dist/src/Evolu/PublicKysely.js +3 -4
  54. package/dist/src/Evolu/Query.d.ts +2 -1
  55. package/dist/src/Evolu/Query.d.ts.map +1 -1
  56. package/dist/src/Evolu/Query.js +1 -1
  57. package/dist/src/Evolu/Relay.d.ts +91 -8
  58. package/dist/src/Evolu/Relay.d.ts.map +1 -1
  59. package/dist/src/Evolu/Relay.js +214 -88
  60. package/dist/src/Evolu/Schema.d.ts +125 -47
  61. package/dist/src/Evolu/Schema.d.ts.map +1 -1
  62. package/dist/src/Evolu/Schema.js +175 -31
  63. package/dist/src/Evolu/Storage.d.ts +249 -27
  64. package/dist/src/Evolu/Storage.d.ts.map +1 -1
  65. package/dist/src/Evolu/Storage.js +198 -92
  66. package/dist/src/Evolu/Sync.d.ts +68 -13
  67. package/dist/src/Evolu/Sync.d.ts.map +1 -1
  68. package/dist/src/Evolu/Sync.js +469 -20
  69. package/dist/src/Evolu/Timestamp.d.ts +83 -30
  70. package/dist/src/Evolu/Timestamp.d.ts.map +1 -1
  71. package/dist/src/Evolu/Timestamp.js +79 -34
  72. package/dist/src/Identicon.d.ts +35 -0
  73. package/dist/src/Identicon.d.ts.map +1 -0
  74. package/dist/src/Identicon.js +143 -0
  75. package/dist/src/Instances.d.ts +34 -0
  76. package/dist/src/Instances.d.ts.map +1 -0
  77. package/dist/src/Instances.js +44 -0
  78. package/dist/src/Number.d.ts +4 -3
  79. package/dist/src/Number.d.ts.map +1 -1
  80. package/dist/src/Number.js +5 -4
  81. package/dist/src/Object.d.ts +10 -4
  82. package/dist/src/Object.d.ts.map +1 -1
  83. package/dist/src/Object.js +9 -3
  84. package/dist/src/Platform.d.ts +20 -0
  85. package/dist/src/Platform.d.ts.map +1 -0
  86. package/dist/src/Platform.js +22 -0
  87. package/dist/src/Random.d.ts +3 -2
  88. package/dist/src/Random.d.ts.map +1 -1
  89. package/dist/src/Relation.d.ts +79 -0
  90. package/dist/src/Relation.d.ts.map +1 -0
  91. package/dist/src/Relation.js +127 -0
  92. package/dist/src/Resources.d.ts +118 -0
  93. package/dist/src/Resources.d.ts.map +1 -0
  94. package/dist/src/Resources.js +197 -0
  95. package/dist/src/Result.d.ts +184 -52
  96. package/dist/src/Result.d.ts.map +1 -1
  97. package/dist/src/Result.js +30 -241
  98. package/dist/src/Skiplist.js +2 -1
  99. package/dist/src/Sqlite.d.ts +89 -5
  100. package/dist/src/Sqlite.d.ts.map +1 -1
  101. package/dist/src/Sqlite.js +136 -9
  102. package/dist/src/Task.d.ts +586 -0
  103. package/dist/src/Task.d.ts.map +1 -0
  104. package/dist/src/Task.js +469 -0
  105. package/dist/src/Time.d.ts +66 -1
  106. package/dist/src/Time.d.ts.map +1 -1
  107. package/dist/src/Time.js +99 -5
  108. package/dist/src/Type.d.ts +676 -343
  109. package/dist/src/Type.d.ts.map +1 -1
  110. package/dist/src/Type.js +718 -467
  111. package/dist/src/Types.d.ts +1 -75
  112. package/dist/src/Types.d.ts.map +1 -1
  113. package/dist/src/WebSocket.d.ts +5 -2
  114. package/dist/src/WebSocket.d.ts.map +1 -1
  115. package/dist/src/WebSocket.js +12 -18
  116. package/dist/src/Worker.d.ts +39 -11
  117. package/dist/src/Worker.d.ts.map +1 -1
  118. package/dist/src/Worker.js +22 -4
  119. package/dist/src/index.d.ts +8 -3
  120. package/dist/src/index.d.ts.map +1 -1
  121. package/dist/src/index.js +8 -3
  122. package/package.json +14 -13
  123. package/src/Array.ts +301 -19
  124. package/src/Assert.ts +0 -21
  125. package/src/Brand.ts +75 -0
  126. package/src/Buffer.ts +7 -7
  127. package/src/Cache.ts +85 -0
  128. package/src/Callbacks.ts +62 -22
  129. package/src/Console.ts +91 -11
  130. package/src/Crypto.ts +94 -90
  131. package/src/Evolu/Db.ts +519 -1026
  132. package/src/Evolu/Diff.ts +7 -5
  133. package/src/Evolu/Evolu.ts +476 -360
  134. package/src/Evolu/Internal.ts +0 -2
  135. package/src/Evolu/LocalAuth.ts +463 -0
  136. package/src/Evolu/Owner.ts +355 -228
  137. package/src/Evolu/Platform.ts +9 -9
  138. package/src/Evolu/Protocol.ts +846 -742
  139. package/src/Evolu/Public.ts +7 -14
  140. package/src/Evolu/PublicKysely.ts +4 -5
  141. package/src/Evolu/Query.ts +3 -2
  142. package/src/Evolu/Relay.ts +406 -103
  143. package/src/Evolu/Schema.ts +323 -91
  144. package/src/Evolu/Storage.ts +559 -137
  145. package/src/Evolu/Sync.ts +819 -36
  146. package/src/Evolu/Timestamp.ts +90 -58
  147. package/src/Identicon.ts +197 -0
  148. package/src/Instances.ts +90 -0
  149. package/src/Number.ts +6 -10
  150. package/src/Object.ts +13 -5
  151. package/src/Platform.ts +26 -0
  152. package/src/Random.ts +3 -2
  153. package/src/Relation.ts +234 -0
  154. package/src/Resources.ts +367 -0
  155. package/src/Result.ts +191 -54
  156. package/src/Skiplist.ts +1 -1
  157. package/src/Sqlite.ts +152 -17
  158. package/src/Task.ts +901 -0
  159. package/src/Time.ts +180 -5
  160. package/src/Type.ts +1135 -730
  161. package/src/Types.ts +1 -77
  162. package/src/WebSocket.ts +27 -25
  163. package/src/Worker.ts +72 -23
  164. package/src/index.ts +8 -3
  165. package/dist/src/Evolu/Config.d.ts +0 -69
  166. package/dist/src/Evolu/Config.d.ts.map +0 -1
  167. package/dist/src/Evolu/Config.js +0 -9
  168. package/dist/src/Evolu/Kysely.d.ts +0 -6
  169. package/dist/src/Evolu/Kysely.d.ts.map +0 -1
  170. package/dist/src/Evolu/Kysely.js +0 -21
  171. package/dist/src/ManyToManyMap.d.ts +0 -26
  172. package/dist/src/ManyToManyMap.d.ts.map +0 -1
  173. package/dist/src/ManyToManyMap.js +0 -92
  174. package/dist/src/NanoId.d.ts +0 -27
  175. package/dist/src/NanoId.d.ts.map +0 -1
  176. package/dist/src/NanoId.js +0 -6
  177. package/dist/src/Promise.d.ts +0 -180
  178. package/dist/src/Promise.d.ts.map +0 -1
  179. package/dist/src/Promise.js +0 -176
  180. package/src/Evolu/Config.ts +0 -83
  181. package/src/Evolu/Kysely.ts +0 -38
  182. package/src/ManyToManyMap.ts +0 -140
  183. package/src/NanoId.ts +0 -39
  184. package/src/Promise.ts +0 -295
@@ -1,302 +1,429 @@
1
- /**
2
- * TODO:
3
- *
4
- * @module
5
- */
6
-
7
- import { assert } from "../Assert.js";
1
+ import * as bip39 from "@scure/bip39";
2
+ import { wordlist } from "@scure/bip39/wordlists/english.js";
3
+ import { NonEmptyReadonlyArray } from "../Array.js";
8
4
  import {
9
- createEncryptionKey,
10
- CreateMnemonicDep,
11
- CreateRandomBytesDep,
12
5
  createSlip21,
13
- createSlip21Id,
14
6
  EncryptionKey,
15
- MnemonicSeed,
16
- mnemonicToMnemonicSeed,
7
+ Entropy16,
8
+ Entropy32,
9
+ RandomBytesDep,
17
10
  } from "../Crypto.js";
18
- import { NanoIdLibDep } from "../NanoId.js";
19
- import { TimeDep } from "../Time.js";
11
+ import { getOrNull } from "../Result.js";
20
12
  import {
21
- Base64Url,
22
13
  brand,
23
- DateIso,
24
- DateIsoString,
25
14
  Id,
26
- length,
15
+ IdBytes,
16
+ idBytesToId,
17
+ idToIdBytes,
27
18
  Mnemonic,
28
19
  NonNegativeInt,
29
- Uint8Array,
30
20
  } from "../Type.js";
31
- import {
32
- createInitialTimestamp,
33
- TimestampString,
34
- timestampToTimestampString,
35
- } from "./Timestamp.js";
36
-
37
- // TODO: Clean API
38
- // - createOwner should be createAppOwner
39
- // - Docs mention WriteKey is optional but it's required in Owner.
40
- // - For Protocol, we need only ownerId, encryptionKey, and writeKey.
41
- // - Not sure whether we need JSDoc for this module, and we don't
42
- // use modules for Evolu internal API yet.
43
- // It's not single responsibility API.
21
+ import type { EncryptedDbChange, Storage } from "./Storage.js";
22
+ import { TimestampBytes } from "./Timestamp.js";
44
23
 
45
24
  /**
46
- * `Owner` is an entity in Evolu that owns data, meaning it is locally stored on
47
- * a device under the user’s control. Data can be personal private, peer-to-peer
48
- * shared, or aggregated from multiple owners.
49
- *
50
- * An owner has a {@link Mnemonic} from which {@link OwnerId} and
51
- * {@link EncryptionKey} are deterministically derived using SLIP-21, and an
52
- * optional {@link WriteKey} that, when present, enables writing to the Evolu
53
- * Relay or peers. The {@link WriteKey} can be rotated.
54
- *
55
- * Variants include {@link AppOwner}, {@link ShardOwner}, {@link SharedOwner}, and
56
- * {@link SharedReadonlyOwner}, each with specific roles and properties detailed
57
- * in their respective definitions.
58
- *
59
- * Public-key cryptography isn’t included here as it belongs to app and varies
60
- * by use case. An Evolu app without collaboration doesn’t need it, while a
61
- * Nostr-like app can leverage Nostr NIPs, or a super-safe app can use
62
- * post-quantum cryptography.
25
+ * The Owner represents ownership of data in Evolu. Every database change is
26
+ * assigned to an owner, enabling sync functionality and access control.
27
+ *
28
+ * Owners enable **partial sync** - applications can choose which owners to
29
+ * sync, allowing selective data synchronization based on specific needs.
30
+ *
31
+ * Owners also provide **real data deletion** - while individual changes in
32
+ * local-first/distributed systems can only be marked as deleted, entire owners
33
+ * can be completely deleted from both relays and devices (except for
34
+ * {@link AppOwner}, which must be preserved for sync coordination).
35
+ *
36
+ * Evolu provides different owner types depending on their use case:
37
+ *
38
+ * - **Coordination**: {@link AppOwner} for sync coordination and long-term
39
+ * persistence
40
+ * - **Data partitioning**: {@link ShardOwner} for partitioning application data
41
+ * - **Collaboration**: {@link SharedOwner} for collaborative write access
42
+ * - **Data sharing**: {@link SharedReadonlyOwner} for read-only access to shared
43
+ * data
44
+ *
45
+ * Owners are cryptographically derived from an {@link OwnerSecret} using
46
+ * SLIP-21, ensuring secure and deterministic key generation:
47
+ *
48
+ * - {@link OwnerId}: Globally unique public identifier
49
+ * - {@link EncryptionKey}: Symmetric encryption key for data protection
50
+ * - {@link OwnerWriteKey}: Authentication token for write operations (rotatable)
51
+ *
52
+ * @see {@link createOwner}
63
53
  */
64
54
  export interface Owner {
65
- readonly mnemonic: Mnemonic;
66
- readonly createdAt: DateIsoString;
67
55
  readonly id: OwnerId;
68
- readonly encryptionKey: EncryptionKey;
69
- readonly writeKey: WriteKey;
70
- }
71
-
72
- export interface OwnerWithWriteAccess {
73
- readonly id: OwnerId;
74
- readonly encryptionKey: EncryptionKey;
75
- readonly writeKey: WriteKey;
56
+ readonly encryptionKey: OwnerEncryptionKey;
57
+ readonly writeKey: OwnerWriteKey;
76
58
  }
77
59
 
78
60
  /**
79
- * The unique identifier of {@link Owner} derived from the {@link Mnemonic}.
80
- *
81
- * This branded {@link Id} type, generated by {@link createSlip21Id}, is a
82
- * 21-character {@link Base64Url} string (126 bits of entropy), providing a
83
- * compact, shareable, and secure identifier for UI use, tied to the owner's
84
- * mnemonic and derivation path.
61
+ * OwnerId is a branded {@link Id} that uniquely identifies an {@link Owner}.
62
+ * Branded from {@link Id} to leverage existing helpers like {@link idToIdBytes}.
85
63
  */
86
64
  export const OwnerId = brand("OwnerId", Id);
87
65
  export type OwnerId = typeof OwnerId.Type;
88
66
 
89
- export const writeKeyLength = 16 as NonNegativeInt;
67
+ /** Bytes representation of {@link OwnerId}. */
68
+ export const OwnerIdBytes = brand("OwnerIdBytes", IdBytes);
69
+ export type OwnerIdBytes = typeof OwnerIdBytes.Type;
70
+
71
+ export const ownerIdToOwnerIdBytes = (ownerId: OwnerId): OwnerIdBytes =>
72
+ idToIdBytes(ownerId) as OwnerIdBytes;
73
+
74
+ export const ownerIdBytesToOwnerId = (ownerIdBytes: OwnerIdBytes): OwnerId =>
75
+ idBytesToId(ownerIdBytes as IdBytes) as OwnerId;
76
+
77
+ export const ownerWriteKeyLength = NonNegativeInt.orThrow(16);
78
+
79
+ export const OwnerEncryptionKey = brand("OwnerEncryptionKey", EncryptionKey);
80
+ export type OwnerEncryptionKey = typeof OwnerEncryptionKey.Type;
90
81
 
91
82
  /**
92
- * A secure token proving the initiator can write changes. Derived from a
93
- * mnemonic or randomly generated. It's rotatable.
83
+ * A secure token for write operations. It's derived from {@link OwnerSecret} by
84
+ * default and can be rotated via {@link createOwnerWriteKey}.
94
85
  */
95
- export const WriteKey = brand("WriteKey", length(writeKeyLength)(Uint8Array));
96
- export type WriteKey = typeof WriteKey.Type;
86
+ export const OwnerWriteKey = brand("OwnerWriteKey", Entropy16);
87
+ export type OwnerWriteKey = typeof OwnerWriteKey.Type;
97
88
 
98
89
  /**
99
- * The root owner of an Evolu app, created from a mnemonic safely generated on a
100
- * device when the app is initialized or restored on another device using an
101
- * existing mnemonic. It manages the app's core data, including the storage of
102
- * other owners' mnemonics in an encrypted app table. Its `writeKey` is
103
- * deterministic and rotatable. Never share the AppOwner mnemonic with anyone.
90
+ * 32 bytes of cryptographic entropy used to derive {@link Owner} keys.
91
+ *
92
+ * Can be created using {@link createOwnerSecret} or converted from a
93
+ * {@link Mnemonic} using {@link mnemonicToOwnerSecret}.
104
94
  */
105
- export interface AppOwner extends Owner {
106
- readonly type: "AppOwner";
107
- }
95
+ export const OwnerSecret = brand("OwnerSecret", Entropy32);
96
+ export type OwnerSecret = typeof OwnerSecret.Type;
97
+
98
+ /** Creates a {@link OwnerSecret}. */
99
+ export const createOwnerSecret = (deps: RandomBytesDep): OwnerSecret =>
100
+ deps.randomBytes.create(32) as OwnerSecret;
101
+
102
+ /** Converts an {@link OwnerSecret} to a {@link Mnemonic}. */
103
+ export const ownerSecretToMnemonic = (secret: OwnerSecret): Mnemonic =>
104
+ bip39.entropyToMnemonic(secret, wordlist) as Mnemonic;
105
+
106
+ /** Converts a {@link Mnemonic} to an {@link OwnerSecret}. */
107
+ export const mnemonicToOwnerSecret = (mnemonic: Mnemonic): OwnerSecret =>
108
+ bip39.mnemonicToEntropy(mnemonic, wordlist) as OwnerSecret;
109
+
110
+ /** Creates a randomly generated {@link OwnerWriteKey}. */
111
+ export const createOwnerWriteKey = (deps: RandomBytesDep): OwnerWriteKey =>
112
+ deps.randomBytes.create(16) as OwnerWriteKey;
108
113
 
109
114
  /**
110
- * Used to shard data within an app for partial or deferred sync. Created in the
111
- * Evolu `initialData` function or dynamically as needed. Its mnemonic is stored
112
- * in an app table (encrypted by `AppOwner`) and synced between devices. Its
113
- * `writeKey` is deterministic and rotatable, enabling selective syncing of data
114
- * subsets. Not intended for sharing outside the app.
115
- *
116
- * This type omits `id`, `encryptionKey`, and `createdAt` as they are derived by
117
- * Evolu from the `mnemonic`, reducing storage overhead.
115
+ * Creates an {@link Owner} from a {@link OwnerSecret} using SLIP-21 key
116
+ * derivation.
117
+ *
118
+ * This is an internal helper function, use:
119
+ *
120
+ * - {@link createAppOwner}
121
+ * - {@link createShardOwner}
122
+ * - {@link createSharedOwner}
123
+ * - {@link createSharedReadonlyOwner}
118
124
  */
119
- export interface ShardOwner {
120
- readonly type: "ShardOwner";
121
- readonly mnemonic: Mnemonic;
122
- readonly writeKey: WriteKey;
123
- }
125
+ export const createOwner = (secret: OwnerSecret): Owner => ({
126
+ id: ownerIdBytesToOwnerId(
127
+ OwnerIdBytes.orThrow(
128
+ createSlip21(secret, ["Evolu", "OwnerIdBytes"]).slice(0, 16),
129
+ ),
130
+ ),
131
+
132
+ encryptionKey: OwnerEncryptionKey.orThrow(
133
+ createSlip21(secret, ["Evolu", "OwnerEncryptionKey"]),
134
+ ),
135
+
136
+ writeKey: OwnerWriteKey.orThrow(
137
+ createSlip21(secret, ["Evolu", "OwnerWriteKey"]).slice(0, 16),
138
+ ),
139
+ });
124
140
 
125
141
  /**
126
- * Used to share data among one or more users, enabling collaboration or
127
- * controlled access. Its `writeKey` is random (not derived from the mnemonic,
128
- * stored alongside it in the app table) and rotatable, ensuring it cannot be
129
- * regenerated by others if shared. Share the `mnemonic` alone for read-only
130
- * access (as `SharedReadonlyOwner`) or share SharedOwner itself for write
131
- * access.
132
- *
133
- * This type omits `id`, `encryptionKey`, and `createdAt` as they are derived by
134
- * Evolu from the `mnemonic`, reducing storage overhead.
142
+ * The AppOwner represents the application owner. It's created using a
143
+ * cryptographically secure random generator or derived from an external source,
144
+ * e.g., mnemonic stored securely in a hardware device.
145
+ *
146
+ * While it's possible to store all application data in AppOwner, the better
147
+ * approach is to use it only for sync coordination. Storing all app data in
148
+ * AppOwner means that data will be stored/synced forever. And that's a problem
149
+ * if we want to provide real data deletion or in-app data migration without
150
+ * data duplication. In local-first apps/distributed systems, we can't delete
151
+ * individual changes, we only mark them as deleted, otherwise sync could not
152
+ * work.
153
+ *
154
+ * If we really want to delete data or at least avoid syncing it, we must store
155
+ * it using a different owner than AppOwner, e.g. {@link ShardOwner} or
156
+ * {@link SharedOwner}, and delete that owner. The AppOwner itself must be
157
+ * preserved because it coordinates deletion information across devices. Other
158
+ * devices need to sync the information that an owner was deleted so they can
159
+ * delete their local data as well.
160
+ *
161
+ * ### Privacy Considerations
162
+ *
163
+ * AppOwner must never be shared with anyone, except for its {@link OwnerId},
164
+ * which can be used for authorization with
165
+ * {@link createOwnerWebSocketTransport}. It's safe because OwnerId is
166
+ * pseudonymous (it can't be assigned to a specific person).
167
+ *
168
+ * For data sharing scenarios, use {@link SharedOwner} and
169
+ * {@link SharedReadonlyOwner} instead, which are designed specifically for
170
+ * collaborative access.
135
171
  */
136
- export interface SharedOwner {
137
- readonly type: "SharedOwner";
138
- readonly mnemonic: Mnemonic;
139
- readonly writeKey: WriteKey;
172
+ export interface AppOwner extends Owner {
173
+ readonly type: "AppOwner";
174
+
175
+ /**
176
+ * The mnemonic that was used to derive the AppOwner keys. Optional when the
177
+ * AppOwner is created from external keys to avoid sharing the mnemonic with
178
+ * the Evolu app.
179
+ */
180
+ readonly mnemonic?: Mnemonic | null;
140
181
  }
141
182
 
183
+ /** Creates an {@link AppOwner} from an {@link OwnerSecret}. */
184
+ export const createAppOwner = (secret: OwnerSecret): AppOwner => ({
185
+ type: "AppOwner",
186
+ mnemonic: ownerSecretToMnemonic(secret),
187
+ ...createOwner(secret),
188
+ });
189
+
142
190
  /**
143
- * Used for sharing data that can only be read, such as with followers or peers
144
- * in a read-only sync scenario. It lacks a `writeKey`, containing only the
145
- * `mnemonic` from which `id` and `encryptionKey` are derived by Evolu.
146
- * Typically derived from a `SharedOwner` by sharing its `mnemonic` without the
147
- * `writeKey`.
191
+ * An {@link Owner} for sharding data.
192
+ *
193
+ * ShardOwners are the recommended storage location for most application data
194
+ * because they can be completely deleted (both on relays and devices) and
195
+ * conditionally synced.
196
+ *
197
+ * Can be created from {@link OwnerSecret} via {@link createShardOwner} or
198
+ * deterministically derived from {@link AppOwner} using
199
+ * {@link deriveShardOwner}.
148
200
  */
149
- export interface SharedReadonlyOwner {
150
- readonly type: "SharedReadonlyOwner";
151
- readonly mnemonic: Mnemonic;
201
+ export interface ShardOwner extends Owner {
202
+ readonly type: "ShardOwner";
203
+ readonly transports?: ReadonlyArray<OwnerTransport>;
152
204
  }
153
205
 
154
- /**
155
- * Creates an {@link AppOwner}, optionally from an existing mnemonic to restore
156
- * it on another device; otherwise, generates a new mnemonic.
157
- */
158
- export const createAppOwner =
159
- (deps: TimeDep & CreateRandomBytesDep & CreateMnemonicDep) =>
160
- (mnemonic = deps.createMnemonic()): AppOwner => {
161
- const owner = createOwner(deps)(mnemonic);
162
- return { type: "AppOwner", ...owner };
206
+ /** Creates a {@link ShardOwner} from an {@link OwnerSecret}. */
207
+ export const createShardOwner = (
208
+ secret: OwnerSecret,
209
+ transports?: ReadonlyArray<OwnerTransport>,
210
+ ): ShardOwner => {
211
+ return {
212
+ type: "ShardOwner",
213
+ ...createOwner(secret),
214
+ ...(transports && { transports }),
163
215
  };
216
+ };
164
217
 
165
218
  /**
166
- * Creates a {@link ShardOwner} for sharding app data with a freshly generated
167
- * mnemonic. Unlike {@link createAppOwner}, it doesn’t accept an existing
168
- * mnemonic because ShardOwner mnemonics are always generated and restored
169
- * automatically via database sync.
219
+ * Derives a {@link ShardOwner} from an {@link AppOwner} using the specified path.
220
+ *
221
+ * **Advantages of derived owners:**
222
+ *
223
+ * - **Deterministic**: Same path always produces the same ShardOwner across all
224
+ * devices
225
+ * - **Immediate availability**: Can be hardcoded and used before sync occurs
226
+ * - **Consistent setup**: All devices start with identical data structure
227
+ * - **Lifecycle management**: Can implement epoch patterns for clean data
228
+ * deletion and recreation
229
+ *
230
+ * **Common patterns:**
231
+ *
232
+ * - Use paths like `["shard", 1]` for versioned data lifecycle
233
+ * - Use paths like `["project", "MyApp", 1]` for named partitions with versions
234
+ * - Each device can derive the same owners and set up initial structure
170
235
  */
171
- export const createShardOwner = (
172
- deps: TimeDep & CreateRandomBytesDep & CreateMnemonicDep,
236
+ export const deriveShardOwner = (
237
+ owner: AppOwner,
238
+ path: NonEmptyReadonlyArray<string | number>,
239
+ transports?: ReadonlyArray<OwnerTransport>,
173
240
  ): ShardOwner => {
174
- const owner = createOwner(deps)();
241
+ const secret = createSlip21(owner.encryptionKey, path) as OwnerSecret;
242
+
175
243
  return {
176
244
  type: "ShardOwner",
177
- mnemonic: owner.mnemonic,
178
- writeKey: owner.writeKey,
245
+ ...createOwner(secret),
246
+ ...(transports && { transports }),
179
247
  };
180
248
  };
181
249
 
250
+ /** An {@link Owner} for collaborative data with write access. */
251
+ export interface SharedOwner extends Owner {
252
+ readonly type: "SharedOwner";
253
+ readonly transports?: ReadonlyArray<OwnerTransport>;
254
+ }
255
+
182
256
  /**
183
- * Creates a fresh {@link SharedOwner} for sharing data with write access. Takes
184
- * no arguments as both `mnemonic` and rotatable `writeKey` are newly generated;
185
- * when shared, recipients use the provided `mnemonic` and `writeKey` directly
186
- * as a {@link SharedOwner} without needing to recreate it.
257
+ * Creates a {@link SharedOwner} from an {@link OwnerSecret} for collaborative
258
+ * write access.
259
+ *
260
+ * Use {@link createSharedReadonlyOwner} to create a read-only version for
261
+ * sharing.
187
262
  */
188
263
  export const createSharedOwner = (
189
- deps: CreateRandomBytesDep & CreateMnemonicDep,
264
+ secret: OwnerSecret,
265
+ transports?: ReadonlyArray<OwnerTransport>,
190
266
  ): SharedOwner => {
191
- const mnemonic = deps.createMnemonic();
192
- const writeKey = createWriteKey(deps)(); // Random, no seed
193
267
  return {
194
268
  type: "SharedOwner",
195
- mnemonic,
196
- writeKey,
269
+ ...createOwner(secret),
270
+ ...(transports && { transports }),
197
271
  };
198
272
  };
199
273
 
200
274
  /**
201
- * Creates a {@link SharedReadonlyOwner} from a {@link SharedOwner} for read-only
202
- * data sharing. Extracts the `mnemonic` from the provided {@link SharedOwner},
203
- * omitting its `writeKey` to ensure read-only access.
275
+ * Read-only version of a {@link SharedOwner} for data sharing. Contains only the
276
+ * {@link OwnerId} and {@link EncryptionKey} needed for others to read the shared
277
+ * data without write access.
204
278
  */
279
+ export interface SharedReadonlyOwner {
280
+ readonly type: "SharedReadonlyOwner";
281
+ readonly id: OwnerId;
282
+ readonly encryptionKey: EncryptionKey;
283
+ readonly transports?: ReadonlyArray<OwnerTransport>;
284
+ }
285
+
286
+ /** Creates a {@link SharedReadonlyOwner} from a {@link SharedOwner}. */
205
287
  export const createSharedReadonlyOwner = (
206
288
  sharedOwner: SharedOwner,
207
- ): SharedReadonlyOwner => {
208
- return {
209
- type: "SharedReadonlyOwner",
210
- mnemonic: sharedOwner.mnemonic,
211
- };
212
- };
213
-
214
- /** Creates an {@link Owner} with optional `mnemonic` and `writeKey`. */
215
- export const createOwner =
216
- (deps: TimeDep & CreateRandomBytesDep & CreateMnemonicDep) =>
217
- (mnemonic = deps.createMnemonic(), writeKey?: WriteKey): Owner => {
218
- const seed = mnemonicToMnemonicSeed(mnemonic);
219
-
220
- const id = createSlip21Id(seed, ["Evolu", "Owner Id"]) as OwnerId;
221
- const encryptionKey = createEncryptionKey(seed);
222
-
223
- const createdAt = DateIso.fromParent(new Date(deps.time.now()));
224
- assert(createdAt.ok, "Invalid DateIso: bad system clock");
225
-
226
- return {
227
- mnemonic,
228
- createdAt: createdAt.value,
229
- id,
230
- encryptionKey,
231
- writeKey: writeKey ?? createWriteKey(deps)(seed),
232
- };
233
- };
289
+ ): SharedReadonlyOwner => ({
290
+ type: "SharedReadonlyOwner",
291
+ id: sharedOwner.id,
292
+ encryptionKey: sharedOwner.encryptionKey,
293
+ ...(sharedOwner.transports && { transports: sharedOwner.transports }),
294
+ });
234
295
 
235
- export const createWriteKey =
236
- (deps: CreateRandomBytesDep) =>
237
- (seed?: MnemonicSeed): WriteKey => {
238
- const key = seed
239
- ? createSlip21(seed, ["Evolu", "Write Key"]).slice(0, 16)
240
- : deps.createRandomBytes(16);
241
-
242
- const writeKey = WriteKey.from(key);
243
- assert(writeKey.ok, "Ensure valid WriteKey");
296
+ /**
297
+ * Transport configuration for connecting to relays.
298
+ *
299
+ * Currently only WebSocket, in the future Bluetooth, LocalNetwork, etc.
300
+ */
301
+ export type OwnerTransport = OwnerWebSocketTransport;
244
302
 
245
- return writeKey.value;
246
- };
303
+ /**
304
+ * WebSocket transport configuration.
305
+ *
306
+ * ### Authentication via URL
307
+ *
308
+ * The {@link OwnerId} is passed as a URL query parameter. While this approach is
309
+ * generally discouraged for authentication tokens (they get logged), it's safe
310
+ * here because OwnerId is pseudonymous and used only for access verification -
311
+ * it provides no ability to read encrypted data or write changes.
312
+ *
313
+ * See: [HTTP headers in Websockets client
314
+ * API](https://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-api/74564827#74564827)
315
+ *
316
+ * ### Error Handling
317
+ *
318
+ * When a relay rejects a connection (invalid OwnerId, unauthorized owner, or
319
+ * server error), the browser WebSocket API does not expose the specific HTTP
320
+ * status code or reason - it only reports a generic connection failure. The
321
+ * client automatically retries with exponential backoff and jitter, eventually
322
+ * succeeding once the configuration or server issue is resolved.
323
+ *
324
+ * Legitimate clients will be properly configured with valid credentials, so
325
+ * automatic retry is OK.
326
+ *
327
+ * @see {@link createOwnerWebSocketTransport}
328
+ * @see {@link parseOwnerIdFromOwnerWebSocketTransportUrl}
329
+ */
330
+ export interface OwnerWebSocketTransport {
331
+ readonly type: "WebSocket";
332
+ readonly url: string;
333
+ }
247
334
 
248
335
  /**
249
- * An `OwnerRow` represents a row in the `evolu_owner` table, based on an
250
- * {@link Owner} with an added `timestamp` ({@link TimestampString}) for CRDT
251
- * sync. It supports all {@link Owner} variants with an optional `writeKey`; use
252
- * {@link createOwnerRow} to align it with a specific {@link Owner}.
336
+ * Creates an {@link OwnerWebSocketTransport} for the given relay URL and
337
+ * {@link OwnerId}.
338
+ *
339
+ * The URL must be a WebSocket base URL without query parameters or fragments
340
+ * (e.g., `wss://relay.evolu.dev`, not `wss://relay.evolu.dev?foo=bar`). The
341
+ * function appends the `ownerId` as a query parameter.
342
+ *
343
+ * ### Example
344
+ *
345
+ * ```ts
346
+ * // Create transport "wss://relay.evolu.dev?ownerId=..."
347
+ * const transport = createOwnerWebSocketTransport({
348
+ * url: "wss://relay.evolu.dev",
349
+ * ownerId: owner.id,
350
+ * });
351
+ *
352
+ * // Use with createEvolu
353
+ * const evolu = createEvolu(deps)(Schema, {
354
+ * transports: [transport],
355
+ * });
356
+ * ```
253
357
  */
254
- export type OwnerRow = Omit<Owner, "writeKey"> & {
255
- readonly writeKey: WriteKey | null;
256
- readonly timestamp: TimestampString;
257
- };
358
+ export const createOwnerWebSocketTransport = (config: {
359
+ readonly url: string;
360
+ readonly ownerId: OwnerId;
361
+ }): OwnerWebSocketTransport => ({
362
+ type: "WebSocket",
363
+ url: `${config.url}?ownerId=${config.ownerId}`,
364
+ });
258
365
 
259
366
  /**
260
- * Creates an {@link OwnerRow} from any {@link Owner} variant for the
261
- * `evolu_owner` table, adding a `timestamp` ({@link TimestampString}) for CRDT
262
- * sync.
367
+ * Extracts {@link OwnerId} from an {@link OwnerWebSocketTransport} URL query
368
+ * string.
369
+ *
370
+ * Parses the query string `?ownerId=...` and validates that the extracted value
371
+ * is a valid {@link OwnerId}.
372
+ *
373
+ * ### Example
374
+ *
375
+ * ```ts
376
+ * parseOwnerIdFromOwnerWebSocketTransportUrl(
377
+ * "/sync?ownerId=_12345678abcdefgh",
378
+ * );
379
+ * // Returns: OwnerId or null
380
+ * ```
263
381
  */
264
- export const createOwnerRow =
265
- (deps: TimeDep & CreateRandomBytesDep & CreateMnemonicDep & NanoIdLibDep) =>
266
- (
267
- owner: AppOwner | ShardOwner | SharedOwner | SharedReadonlyOwner,
268
- ): OwnerRow => {
269
- const timestamp = timestampToTimestampString(createInitialTimestamp(deps));
270
- switch (owner.type) {
271
- case "AppOwner": {
272
- const { type, ...rest } = owner;
273
- return { ...rest, timestamp };
274
- }
275
- case "ShardOwner":
276
- case "SharedOwner":
277
- return {
278
- ...createOwner(deps)(owner.mnemonic, owner.writeKey),
279
- timestamp,
280
- };
281
- case "SharedReadonlyOwner":
282
- return {
283
- ...createOwner(deps)(owner.mnemonic),
284
- writeKey: null,
285
- timestamp,
286
- };
287
- }
288
- };
382
+ export const parseOwnerIdFromOwnerWebSocketTransportUrl = (
383
+ url: string,
384
+ ): OwnerId | null => getOrNull(OwnerId.fromUnknown(url.split("=")[1]));
385
+
386
+ /** Base interface for all owner errors. */
387
+ export interface BaseOwnerError {
388
+ readonly ownerId: OwnerId;
389
+ }
289
390
 
290
391
  /**
291
- * Rotates the {@link WriteKey} for an {@link AppOwner}, {@link ShardOwner}, or
292
- * {@link SharedOwner}, returning a new instance with the updated key.
392
+ * Usage data for an {@link OwnerId}.
393
+ *
394
+ * Tracks storage usage to enforce quotas if needed, and some other stuff.
395
+ *
396
+ * TODO:
397
+ *
398
+ * - Add transferredBytes for billing and monitoring network usage.
293
399
  */
294
- export const rotateWriteKey = <T extends AppOwner | ShardOwner | SharedOwner>(
295
- owner: T,
296
- newWriteKey: WriteKey,
297
- ): T => {
298
- return {
299
- ...owner,
300
- writeKey: newWriteKey,
301
- } as T;
302
- };
400
+ export interface OwnerUsage {
401
+ /** The {@link Owner} this usage data belongs to. */
402
+ readonly ownerId: OwnerIdBytes;
403
+
404
+ /**
405
+ * Total logical data bytes stored.
406
+ *
407
+ * Measures the size of {@link EncryptedDbChange}s only, excluding
408
+ * {@link Storage} implementation overhead (with SqliteStorage: indexes,
409
+ * skiplist columns, etc.). This provides:
410
+ *
411
+ * - **Predictable measurement** - same data = same byte count across all
412
+ * instances
413
+ * - **Quota enforcement** - consistent billing/limits independent of storage
414
+ * implementation
415
+ * - **Overhead tracking** - actual Storage size can be compared against this to
416
+ * monitor efficiency
417
+ */
418
+ readonly storedBytes: NonNegativeInt;
419
+
420
+ /** Tracks the earliest timestamp for timestamp insertion strategies. */
421
+ readonly firstTimestamp: TimestampBytes | null;
422
+
423
+ /**
424
+ * Tracks the latest timestamp for timestamp insertion strategies.
425
+ *
426
+ * Free relays can use it to identify inactive accounts for cleanup.
427
+ */
428
+ readonly lastTimestamp: TimestampBytes | null;
429
+ }