local-lite 0.1.4 → 0.2.2

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 (48) hide show
  1. package/README.md +5 -2
  2. package/bin/local-lite.mjs +65 -61
  3. package/dist/auth/apple.d.ts +3 -4
  4. package/dist/auth/apple.js +26 -3
  5. package/dist/auth/github.d.ts +3 -5
  6. package/dist/auth/github.js +18 -4
  7. package/dist/auth/google.d.ts +3 -6
  8. package/dist/auth/google.js +19 -5
  9. package/dist/auth/identity.d.ts +42 -0
  10. package/dist/auth/identity.js +63 -0
  11. package/dist/auth/index.d.ts +2 -0
  12. package/dist/auth/index.js +2 -0
  13. package/dist/auth/local.d.ts +33 -1
  14. package/dist/auth/local.js +94 -13
  15. package/dist/auth/microsoft.d.ts +3 -5
  16. package/dist/auth/microsoft.js +16 -3
  17. package/dist/auth/session.d.ts +4 -0
  18. package/dist/auth/session.js +19 -1
  19. package/dist/auth/unified.d.ts +73 -0
  20. package/dist/auth/unified.js +188 -0
  21. package/package.json +1 -2
  22. package/skills/local-lite-auth/SKILL.md +67 -27
  23. package/skills/local-lite-server/SKILL.md +127 -0
  24. package/docs/.nojekyll +0 -1
  25. package/docs/README.md +0 -108
  26. package/docs/_sidebar.md +0 -22
  27. package/docs/actions-email.md +0 -222
  28. package/docs/adapters-local.md +0 -272
  29. package/docs/adapters-remote.md +0 -291
  30. package/docs/api-keys.md +0 -114
  31. package/docs/architecture.md +0 -106
  32. package/docs/auth.md +0 -342
  33. package/docs/backups.md +0 -214
  34. package/docs/breaking-changes.md +0 -147
  35. package/docs/client-api.md +0 -412
  36. package/docs/configuration.md +0 -228
  37. package/docs/conflict-resolution.md +0 -78
  38. package/docs/getting-started.md +0 -190
  39. package/docs/google-auth.md +0 -234
  40. package/docs/index.html +0 -166
  41. package/docs/kv.md +0 -89
  42. package/docs/maintenance-portability.md +0 -133
  43. package/docs/react-hooks.md +0 -457
  44. package/docs/scheduler.md +0 -81
  45. package/docs/search.md +0 -71
  46. package/docs/server.md +0 -101
  47. package/docs/session.md +0 -129
  48. package/docs/storage.md +0 -265
@@ -1,106 +0,0 @@
1
- # 🏛️ Architecture & Concepts
2
-
3
- `local-lite` is designed around the **Transactional Outbox Pattern**, a proven distributed systems architecture adapted for client applications.
4
-
5
- ---
6
-
7
- ## The System Architecture
8
-
9
- ```
10
- ┌─────────────────────────────────────────────────────────────┐
11
- │ React / React Native UI │
12
- │ │
13
- │ useLiveQuery() useSyncStatus() │
14
- └────────▲──────────────────────────────────────────▲─────────┘
15
- │ (Events: change:table) │ (Events: sync:status)
16
- ┌────────┴──────────────────────────────────────────┴─────────┐
17
- │ EventEmitter │
18
- └────────▲──────────────────────────────────────────▲─────────┘
19
- │ (Emit) │ (Emit)
20
- ┌────────┴──────────────────────────────────────────┴─────────┐
21
- │ LocalFirstClient │
22
- │ │
23
- │ insert() / update() / delete() / mutate() │
24
- └────────┬──────────────────────────────────────────┬─────────┘
25
- │ (Atomic Transaction) │ (Wakeup)
26
- ▼ ▼
27
- ┌─────────────────────────┐ ┌──────────────────────┐
28
- │ Local SQLite Engine │ │ SyncWorker │
29
- │ │ │ │
30
- │ ┌─────────────────────┐ │ │ 1. Push Outbox items │
31
- │ │ User Table (todos) │ │ │ 2. Fetch remote logs │
32
- │ ├─────────────────────┤ │ │ 3. Resolve conflicts │
33
- │ │ sync_outbox (queue) │◄┼────────────┤ 4. Update Meta Store │
34
- │ ├─────────────────────┤ │ └──────────┬───────────┘
35
- │ │ sync_meta (state) │ │ │
36
- │ └─────────────────────┘ │ │
37
- └─────────────────────────┘ ▼
38
- ┌──────────────────────┐
39
- │ Remote Adapter │
40
- │ (Supabase / Convex) │
41
- └──────────────────────┘
42
- ```
43
-
44
- ---
45
-
46
- ## 1. Atomic Dual-Write (The Transactional Outbox)
47
-
48
- In standard apps, if an API call fails after a state update, or if the user closes the app mid-flight, local state and remote state become desynchronized.
49
-
50
- `local-lite` solves this by executing a single SQLite atomic transaction whenever `client.mutate()` is called:
51
- 1. **User Table Update:** Writes the record to the table (e.g. `INSERT INTO todos ...`).
52
- 2. **Outbox Entry:** Simultaneously appends a log to the internal `sync_outbox` table:
53
- - `id`: Unique mutation UUID
54
- - `tableName`: Table modified
55
- - `rowId`: Primary key affected
56
- - `operation`: `'INSERT'`, `'UPDATE'`, or `'DELETE'`
57
- - `payload`: JSON data
58
- - `timestamp`: Mutation timestamp
59
-
60
- Because both operations occur inside the same SQLite transaction:
61
- - If the app crashes or the battery dies, both commit or both roll back together.
62
- - Pending mutations remain safely in SQLite until successfully acknowledged by the server.
63
-
64
- ---
65
-
66
- ## 2. The SyncWorker Pipeline
67
-
68
- The `SyncWorker` is a background coordination engine that executes two main loops:
69
-
70
- ### Push Loop
71
- 1. Reads pending records from `sync_outbox` sorted by timestamp.
72
- 2. Formats mutations into a batch.
73
- 3. Invokes `remoteAdapter.pushChanges(batch)`.
74
- 4. Upon successful server acknowledgment, deletes the processed records from `sync_outbox`.
75
- 5. If the server fails or returns a network error, applies exponential backoff and leaves the outbox untouched.
76
-
77
- ### Pull Loop
78
- 1. Reads the latest sync watermark timestamp from the internal `sync_meta` table.
79
- 2. Calls `remoteAdapter.fetchChanges(tables, sinceTimestamp)`.
80
- 3. For each delta received from the server:
81
- - Evaluates the configured **ConflictResolver**.
82
- - If the server change wins, writes the delta into local SQLite.
83
- 4. Updates the high-watermark timestamp in `sync_meta`.
84
- 5. Emits table change events to re-render any active `useLiveQuery()` components.
85
-
86
- ---
87
-
88
- ## 3. Infinite-Loop Prevention
89
-
90
- A common bug in bidirectional sync engines is "mutation echo":
91
- `Remote pull -> Writes to local DB -> Outbox mistakenly thinks user created a new record -> Pushes back to remote`.
92
-
93
- `local-lite` avoids this entirely:
94
- - **Direct internal writes:** When `SyncWorker` applies incoming deltas, it bypasses the `client.mutate()` outbox pathway and executes direct SQLite SQL updates.
95
- - **Event firing:** It triggers `events.emit('change:tableName')` so your UI updates reactively, without appending any records to `sync_outbox`.
96
-
97
- ---
98
-
99
- ## 4. Offline Resilience & Network Awareness
100
-
101
- - `local-lite` ships with a network listener (`DefaultNetworkStatusProvider` or `@react-native-community/netinfo`).
102
- - When offline:
103
- - Local queries and mutations execute with **0ms latency**.
104
- - Periodic network calls are paused to conserve battery and CPU.
105
- - When connectivity restores:
106
- - The network listener detects the change and triggers an **immediate outbox flush**.
package/docs/auth.md DELETED
@@ -1,342 +0,0 @@
1
- # 🔑 Authentication (Local SQLite, Google, Microsoft / OneDrive, GitHub & Apple)
2
-
3
- `local-lite` provides zero-backend, PKCE-secured authentication clients and React hooks out of the box for the four most popular identity providers, plus a **fully local SQLite authentication engine**:
4
- * **Local SQLite Auth Engine** (`LocalAuthEngine`, `useLocalAuth`) — 100% offline, PBKDF2-SHA512 password crypto, account lockout, tokens, and users table
5
- * **Google** (`GoogleAuthClient`, `useGoogleAuth`)
6
- * **Microsoft / OneDrive** (`MicrosoftAuthClient`, `OneDriveAuthClient`, `useMicrosoftAuth`, `useOneDriveAuth`)
7
- * **GitHub** (`GitHubAuthClient`, `useGitHubAuth`)
8
- * **Apple** (`AppleAuthClient`, `useAppleAuth`)
9
-
10
- Built specifically for local-first architectures, these clients allow your Expo, React Native, Web, or Desktop application to authenticate users directly without requiring an intermediate backend auth server.
11
-
12
- ```typescript
13
- import {
14
- GoogleAuthClient,
15
- MicrosoftAuthClient,
16
- OneDriveAuthClient,
17
- GitHubAuthClient,
18
- AppleAuthClient,
19
- } from 'local-lite/auth';
20
-
21
- import {
22
- useGoogleAuth,
23
- useMicrosoftAuth,
24
- useOneDriveAuth,
25
- useGitHubAuth,
26
- useAppleAuth,
27
- } from 'local-lite/react';
28
- ```
29
-
30
- ---
31
-
32
- ## 🌟 Common Architecture & Security
33
-
34
- * **🛡️ PKCE Security (RFC 7636):** Automatic cryptographically secure 32-byte `code_verifier`, SHA-256 (`S256`) code challenge generation, and CSRF state validation.
35
- * **👤 Direct Profile Fetching:** Retrieves verified user profile (`id`, `name`, `email`, `picture`) directly from the provider's standard UserInfo / Graph / API endpoints.
36
- * **🔄 Transparent Token Refreshing:** Inspects token expiration and uses `refresh_token` automatically when within 60 seconds of expiry.
37
- * **💾 Pluggable Storage:** Use in-memory stores by default or pass any key-value storage adapter (AsyncStorage, SQLite kv-store, SecureStore, etc.) to keep sessions across app restarts.
38
- * **⚛️ Reactive React Hooks:** Hooks provide reactive user state, sign-in, sign-out, and auto-subscriptions.
39
-
40
- ---
41
-
42
- ## 1. Google Authentication
43
-
44
- ### Setup in Expo / React Native:
45
- ```typescript
46
- import * as WebBrowser from 'expo-web-browser';
47
- import * as Linking from 'expo-linking';
48
- import { GoogleAuthClient, createGoogleAuthTokenStore } from 'local-lite/auth';
49
-
50
- export const googleAuth = new GoogleAuthClient({
51
- clientId: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com',
52
- redirectUri: Linking.createURL('oauth'),
53
- scopes: ['openid', 'email', 'profile'],
54
- authorize: async ({ authorizationUrl, redirectUri }) => {
55
- const result = await WebBrowser.openAuthSessionAsync(authorizationUrl, redirectUri);
56
- if (result.type !== 'success' || !result.url) return null;
57
- const url = new URL(result.url);
58
- return {
59
- code: url.searchParams.get('code') ?? '',
60
- state: url.searchParams.get('state') ?? '',
61
- };
62
- },
63
- });
64
- ```
65
-
66
- ---
67
-
68
- ## 2. Microsoft & OneDrive Authentication
69
-
70
- The Microsoft Identity Platform (v2.0) supports OAuth 2.0 PKCE for public clients without a client secret.
71
-
72
- ### Setup in Expo / React Native:
73
- ```typescript
74
- import * as WebBrowser from 'expo-web-browser';
75
- import * as Linking from 'expo-linking';
76
- import { MicrosoftAuthClient, OneDriveAuthClient } from 'local-lite/auth';
77
-
78
- export const oneDriveAuth = new OneDriveAuthClient({
79
- clientId: 'YOUR_AZURE_APPLICATION_CLIENT_ID',
80
- redirectUri: Linking.createURL('oauth'),
81
- // 'Files.ReadWrite.AppFolder' grants access to dedicated OneDrive app storage
82
- scopes: ['openid', 'profile', 'email', 'User.Read', 'Files.ReadWrite.AppFolder'],
83
- authorize: async ({ authorizationUrl, redirectUri }) => {
84
- const result = await WebBrowser.openAuthSessionAsync(authorizationUrl, redirectUri);
85
- if (result.type !== 'success' || !result.url) return null;
86
- const url = new URL(result.url);
87
- return {
88
- code: url.searchParams.get('code') ?? '',
89
- state: url.searchParams.get('state') ?? '',
90
- };
91
- },
92
- });
93
- ```
94
-
95
- ### Profile Returned (`MicrosoftUser` / `OneDriveUser`):
96
- ```typescript
97
- export interface MicrosoftUser {
98
- id: string;
99
- email: string;
100
- name: string;
101
- givenName?: string;
102
- familyName?: string;
103
- picture?: string;
104
- userPrincipalName?: string;
105
- }
106
- ```
107
-
108
- ---
109
-
110
- ## 3. GitHub Authentication
111
-
112
- Authenticates users via GitHub OAuth and automatically fetches the user's profile and primary verified email address (handling private email profiles seamlessly).
113
-
114
- ### Setup in Expo / React Native:
115
- ```typescript
116
- import * as WebBrowser from 'expo-web-browser';
117
- import * as Linking from 'expo-linking';
118
- import { GitHubAuthClient } from 'local-lite/auth';
119
-
120
- export const gitHubAuth = new GitHubAuthClient({
121
- clientId: 'YOUR_GITHUB_CLIENT_ID',
122
- clientSecret: process.env.GITHUB_CLIENT_SECRET, // Optional if using tokenExchangeUrl proxy
123
- redirectUri: Linking.createURL('oauth'),
124
- scopes: ['read:user', 'user:email'],
125
- authorize: async ({ authorizationUrl, redirectUri }) => {
126
- const result = await WebBrowser.openAuthSessionAsync(authorizationUrl, redirectUri);
127
- if (result.type !== 'success' || !result.url) return null;
128
- const url = new URL(result.url);
129
- return {
130
- code: url.searchParams.get('code') ?? '',
131
- state: url.searchParams.get('state') ?? '',
132
- };
133
- },
134
- });
135
- ```
136
-
137
- ### Profile Returned (`GitHubUser`):
138
- ```typescript
139
- export interface GitHubUser {
140
- id: string;
141
- login: string;
142
- name: string;
143
- email: string;
144
- avatarUrl?: string;
145
- bio?: string;
146
- company?: string;
147
- location?: string;
148
- }
149
- ```
150
-
151
- ---
152
-
153
- ## ⚛️ React Hooks Usage
154
-
155
- ```tsx
156
- import React from 'react';
157
- import { View, Text, Button, Image } from 'react-native';
158
- import { useGoogleAuth, useMicrosoftAuth, useGitHubAuth } from 'local-lite/react';
159
- import { googleAuth, oneDriveAuth, gitHubAuth } from './auth';
160
-
161
- export function LoginButtons() {
162
- const google = useGoogleAuth(googleAuth);
163
- const ms = useMicrosoftAuth(oneDriveAuth);
164
- const github = useGitHubAuth(gitHubAuth);
165
-
166
- return (
167
- <View style={{ gap: 10 }}>
168
- <Button title="Continue with Google" onPress={google.signIn} />
169
- <Button title="Continue with Microsoft / OneDrive" onPress={ms.signIn} />
170
- <Button title="Continue with GitHub" onPress={github.signIn} />
171
- </View>
172
- );
173
- }
174
- ```
175
-
176
- ---
177
-
178
- ## 4. Sign in with Apple
179
-
180
- `AppleAuthClient` supports both native iOS credentials (`expo-apple-authentication` / `ASAuthorizationAppleIDCredential`) and OAuth authorization flows. Because Apple provides full name and email **only on the very first sign-in**, `AppleAuthClient` automatically caches and preserves user details across sessions.
181
-
182
- ### Setup with `expo-apple-authentication`:
183
- ```typescript
184
- import * as AppleAuthentication from 'expo-apple-authentication';
185
- import { AppleAuthClient } from 'local-lite/auth';
186
-
187
- export const appleAuth = new AppleAuthClient({
188
- clientId: 'com.yourcompany.app',
189
- nativeSignIn: async () => {
190
- const cred = await AppleAuthentication.signInAsync({
191
- requestedScopes: [
192
- AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
193
- AppleAuthentication.AppleAuthenticationScope.EMAIL,
194
- ],
195
- });
196
- return {
197
- user: cred.user,
198
- identityToken: cred.identityToken,
199
- authorizationCode: cred.authorizationCode,
200
- email: cred.email,
201
- fullName: cred.fullName,
202
- };
203
- },
204
- });
205
- ```
206
-
207
- ### React Hook Example:
208
- ```tsx
209
- import { useAppleAuth } from 'local-lite/react';
210
- import { appleAuth } from './auth';
211
-
212
- export function AppleLoginButton() {
213
- const { user, isSignedIn, signIn, signOut } = useAppleAuth(appleAuth);
214
-
215
- if (isSignedIn && user) {
216
- return (
217
- <View>
218
- <Text>Welcome {user.name ?? user.email}!</Text>
219
- <Button title="Sign Out" onPress={signOut} />
220
- </View>
221
- );
222
- }
223
-
224
- return <Button title="Sign in with Apple" onPress={() => signIn()} />;
225
- }
226
- ```
227
-
228
- ---
229
-
230
- ## 💾 Session Persistence Adapters
231
-
232
- All auth clients accept a `storage` option compatible with any key-value store (AsyncStorage, SQLite kv-store, MMKV, or SecureStore):
233
-
234
- ```typescript
235
- import AsyncStorage from 'expo-sqlite/kv-store';
236
- import {
237
- createGoogleAuthTokenStore,
238
- createMicrosoftAuthTokenStore,
239
- createGitHubAuthTokenStore,
240
- createAppleAuthTokenStore,
241
- } from 'local-lite/auth';
242
-
243
- const storage = {
244
- getItem: async (key: string) => {
245
- const val = await AsyncStorage.getItem(key);
246
- return val ? JSON.parse(val) : null;
247
- },
248
- setItem: async (key: string, value: unknown) => {
249
- await AsyncStorage.setItem(key, JSON.stringify(value));
250
- },
251
- removeItem: async (key: string) => {
252
- await AsyncStorage.removeItem(key);
253
- },
254
- };
255
-
256
- const googleTokenStore = createGoogleAuthTokenStore(storage);
257
- const msTokenStore = createMicrosoftAuthTokenStore(storage);
258
- const ghTokenStore = createGitHubAuthTokenStore(storage);
259
- const appleTokenStore = createAppleAuthTokenStore(storage);
260
- ```
261
-
262
- ---
263
-
264
- ## 🔒 5. Fully Local Authentication Engine (`auth/local`)
265
-
266
- For standalone offline-first apps, local-only modes, or self-contained credentials without third-party OAuth, `local-lite` provides a zero-backend **LocalAuthEngine** storing credentials directly in SQLite.
267
-
268
- ```typescript
269
- import { LocalAuthEngine } from 'local-lite/auth/local';
270
- // or access client.auth directly on LocalFirstClient:
271
- import { useLocalAuth } from 'local-lite/react';
272
- ```
273
-
274
- ### Features & Security:
275
- * **🛡️ High-Level Crypto Credentials:** PBKDF2 with SHA-512 key derivation, 100,000 iterations by default, and distinct cryptographically secure 16-byte random salts.
276
- * **⏱️ Constant-Time Verification:** Password comparison uses timing-safe XOR operations to defeat side-channel timing attacks.
277
- * **🚫 Brute-Force & Lockout Protection:** Automatically tracks consecutive failed login attempts and locks accounts temporarily (default: 5 failed attempts locks for 15 minutes).
278
- * **🔑 Single-Use Password Reset Tokens:** Cryptographically secure 32-byte tokens stored only as SHA-256 hashes with configurable expiry.
279
- * **👤 SQLite `_local_users` Table:** Stores sanitized user profiles, usernames, case-insensitive emails, roles, JSON metadata, and status (`active`, `suspended`, `locked`).
280
- * **📱 Integrated Offline Sessions:** Automatically creates and persists sessions in `SessionManager` so users stay logged in offline.
281
-
282
- ### Basic Usage:
283
-
284
- ```typescript
285
- // Standalone or via client.auth:
286
- const { user, session } = await client.auth.signUp({
287
- email: 'alice@example.com',
288
- username: 'alice',
289
- password: 'SuperSecretPassword123!',
290
- displayName: 'Alice Wonderland',
291
- metadata: { role: 'admin' },
292
- });
293
-
294
- // Sign In with email or username:
295
- const { user, session } = await client.auth.signIn({
296
- identifier: 'alice@example.com', // or username 'alice'
297
- password: 'SuperSecretPassword123!',
298
- });
299
-
300
- // Password Change:
301
- await client.auth.changePassword({
302
- userId: user.id,
303
- oldPassword: 'SuperSecretPassword123!',
304
- newPassword: 'BrandNewPassword456!',
305
- });
306
-
307
- // Password Reset Flow:
308
- const { token } = await client.auth.createPasswordResetToken('alice@example.com');
309
- await client.auth.resetPasswordWithToken(token, 'BrandNewPassword456!');
310
-
311
- // Sign Out:
312
- await client.auth.signOut();
313
- ```
314
-
315
- ### React Hook (`useLocalAuth`):
316
-
317
- ```tsx
318
- import { useLocalAuth } from 'local-lite/react';
319
-
320
- export function AuthScreen({ client }) {
321
- const { user, isSignedIn, loading, signIn, signUp, signOut } = useLocalAuth(client.auth);
322
-
323
- if (loading) return <Text>Loading user state...</Text>;
324
-
325
- if (isSignedIn) {
326
- return (
327
- <View>
328
- <Text>Welcome back, {user.displayName || user.email}!</Text>
329
- <Button title="Sign Out" onPress={() => signOut()} />
330
- </View>
331
- );
332
- }
333
-
334
- return (
335
- <LoginForm
336
- onLogin={(email, password) => signIn(email, password)}
337
- onRegister={(email, password) => signUp({ email, password })}
338
- />
339
- );
340
- }
341
- ```
342
-
package/docs/backups.md DELETED
@@ -1,214 +0,0 @@
1
- # 📦 Cloud Backups & Zero-Knowledge Encryption
2
-
3
- `local-lite` includes zero-backend cloud backup and client-side zero-knowledge database encryption out of the box.
4
-
5
- ```typescript
6
- import {
7
- GoogleDriveBackupClient,
8
- OneDriveBackupClient,
9
- performBackup,
10
- performRestore,
11
- createDatabaseBackup,
12
- restoreDatabaseBackup,
13
- createEncryptedDatabaseBackup,
14
- restoreEncryptedDatabaseBackup,
15
- } from 'local-lite/backups';
16
-
17
- import {
18
- useCloudBackup,
19
- useGoogleDriveBackup,
20
- useOneDriveBackup,
21
- } from 'local-lite/react';
22
- ```
23
-
24
- ---
25
-
26
- ## ☁️ 1. Supported Cloud Storage Providers
27
-
28
- SQLite snapshots are exported directly to user personal cloud storage in secure, application-sandboxed directories without requiring full drive access:
29
- * **Google Drive** (`GoogleDriveBackupClient`, `GoogleDriveBackupStorage` using the sandboxed `appDataFolder`)
30
- * **Microsoft OneDrive** (`OneDriveBackupClient`, `OneDriveBackupStorage` using the sandboxed `special/approot` directory)
31
-
32
- ---
33
-
34
- ## 🚀 2. Setting Up Backup Clients
35
-
36
- ### Google Drive Client:
37
- ```typescript
38
- import * as WebBrowser from 'expo-web-browser';
39
- import * as Linking from 'expo-linking';
40
- import { GoogleDriveBackupClient, createGoogleDriveTokenStore } from 'local-lite/backups';
41
-
42
- export const googleDriveBackup = new GoogleDriveBackupClient({
43
- clientId: process.env.EXPO_PUBLIC_GOOGLE_CLIENT_ID!,
44
- redirectUri: Linking.createURL('oauth'),
45
- tokenStore: createGoogleDriveTokenStore(secureStorage),
46
- authorize: async ({ authorizationUrl, redirectUri }) => {
47
- const res = await WebBrowser.openAuthSessionAsync(authorizationUrl, redirectUri);
48
- if (res.type !== 'success' || !res.url) return null;
49
- const url = new URL(res.url);
50
- return {
51
- code: url.searchParams.get('code') ?? '',
52
- state: url.searchParams.get('state') ?? '',
53
- };
54
- },
55
- });
56
- ```
57
-
58
- ### OneDrive Client:
59
- ```typescript
60
- import * as WebBrowser from 'expo-web-browser';
61
- import * as Linking from 'expo-linking';
62
- import { OneDriveBackupClient, createOneDriveTokenStore } from 'local-lite/backups';
63
-
64
- export const oneDriveBackup = new OneDriveBackupClient({
65
- clientId: process.env.EXPO_PUBLIC_AZURE_CLIENT_ID!,
66
- redirectUri: Linking.createURL('oauth'),
67
- tokenStore: createOneDriveTokenStore(secureStorage),
68
- authorize: async ({ authorizationUrl, redirectUri }) => {
69
- const res = await WebBrowser.openAuthSessionAsync(authorizationUrl, redirectUri);
70
- if (res.type !== 'success' || !res.url) return null;
71
- const url = new URL(res.url);
72
- return {
73
- code: url.searchParams.get('code') ?? '',
74
- state: url.searchParams.get('state') ?? '',
75
- };
76
- },
77
- });
78
- ```
79
-
80
- ---
81
-
82
- ## 💾 3. Backing Up and Restoring via `client`
83
-
84
- You can create and restore backups directly through your initialized `LocalFirstClient`:
85
-
86
- ```typescript
87
- // Connect user session
88
- await googleDriveBackup.connect();
89
-
90
- // 1. Create backup snapshot
91
- const fileName = await client.backup(googleDriveBackup, {
92
- fileName: 'my-app-backup.db', // optional
93
- });
94
- console.log('Backup created:', fileName);
95
-
96
- // 2. List backups
97
- const backups = await googleDriveBackup.list();
98
-
99
- // 3. Restore snapshot
100
- await client.restore(googleDriveBackup, backups[0].name);
101
- ```
102
-
103
- ---
104
-
105
- ## 🔐 4. Zero-Knowledge Encryption (AES-256-GCM + PBKDF2)
106
-
107
- For sensitive applications (medical records, finances, personal notes), data can be encrypted on-device before uploading to the cloud. Neither Google, Microsoft, nor anyone intercepting the file can read the snapshot.
108
-
109
- ### Security Specifications:
110
- * **Key Derivation:** PBKDF2 with SHA-256, 50,000 iterations, and a unique 16-byte cryptographic salt per backup.
111
- * **Authenticated Encryption:** AES-256-GCM with a unique 12-byte initialization vector (IV) and 16-byte authentication tag preventing tampering.
112
- * **Header Structure:** Self-describing `LLENC1` magic bytes header packing the salt, IV, and iteration count for automatic decryption validation.
113
-
114
- ### Usage:
115
- ```typescript
116
- // Create encrypted backup with passphrase:
117
- const encryptedFileName = await client.backup(googleDriveBackup, {
118
- passphrase: 'user-chosen-secret-passphrase',
119
- fileName: 'medical-snapshot.enc.db',
120
- });
121
-
122
- // Restore encrypted backup:
123
- await client.restore(googleDriveBackup, encryptedFileName, {
124
- passphrase: 'user-chosen-secret-passphrase',
125
- });
126
- ```
127
-
128
- If the passphrase is incorrect or the file was modified in transit, decryption immediately rejects with:
129
- `Backup decryption failed: Incorrect passphrase or corrupted database backup.`
130
-
131
- ---
132
-
133
- ## ⚛️ 5. React Hooks for Cloud Backups
134
-
135
- Use `useGoogleDriveBackup` or `useOneDriveBackup` to manage cloud backups reactively in your UI:
136
-
137
- ```tsx
138
- import React from 'react';
139
- import { View, Text, Button, FlatList, ActivityIndicator } from 'react-native';
140
- import { useGoogleDriveBackup } from 'local-lite/react';
141
- import { googleDriveBackup } from './backup';
142
-
143
- export function CloudBackupScreen({ client }) {
144
- const {
145
- isConnected,
146
- isLoading,
147
- isBackingUp,
148
- isRestoring,
149
- backups,
150
- connect,
151
- disconnect,
152
- backup,
153
- restore,
154
- deleteBackup,
155
- } = useGoogleDriveBackup(googleDriveBackup, client, {
156
- passphrase: 'optional-user-passphrase',
157
- autoRefresh: true,
158
- });
159
-
160
- if (isLoading) return <ActivityIndicator />;
161
-
162
- if (!isConnected) {
163
- return (
164
- <View>
165
- <Text>Connect your Google Drive to enable cloud backups.</Text>
166
- <Button title="Connect Google Drive" onPress={() => connect()} />
167
- </View>
168
- );
169
- }
170
-
171
- return (
172
- <View style={{ padding: 16 }}>
173
- <Button
174
- title={isBackingUp ? 'Creating Backup...' : 'Create New Backup'}
175
- disabled={isBackingUp}
176
- onPress={() => backup()}
177
- />
178
-
179
- <FlatList
180
- data={backups}
181
- keyExtractor={(item) => item.id}
182
- renderItem={({ item }) => (
183
- <View style={{ flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 8 }}>
184
- <View>
185
- <Text style={{ fontWeight: '600' }}>{item.name}</Text>
186
- <Text style={{ color: '#666' }}>{new Date(item.createdAt).toLocaleString()}</Text>
187
- </View>
188
- <View style={{ flexDirection: 'row', gap: 8 }}>
189
- <Button title="Restore" onPress={() => restore(item.name)} disabled={isRestoring} />
190
- <Button title="Delete" color="#ef4444" onPress={() => deleteBackup(item.id)} />
191
- </View>
192
- </View>
193
- )}
194
- />
195
-
196
- <Button title="Disconnect" color="#64748b" onPress={() => disconnect()} />
197
- </View>
198
- );
199
- }
200
- ```
201
-
202
- ---
203
-
204
- ## 🗄️ 6. Universal Database Snapshots (`exportDatabase` & `importDatabase`)
205
-
206
- `LocalFirstClient` includes built-in methods to export and import portable binary snapshots independently of any cloud service (e.g. for local file system saves, air-gapped USB transfers, or diagnostic dumps):
207
-
208
- ```typescript
209
- // 1. Export entire SQLite state as Uint8Array bytes
210
- const snapshotBytes = await client.exportDatabase();
211
-
212
- // 2. Restore database from snapshot bytes
213
- await client.importDatabase(snapshotBytes);
214
- ```