local-lite 0.1.2 → 0.1.4
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/README.md +9 -1
- package/bin/local-lite.mjs +1 -1
- package/dist/auth/apple.js +6 -2
- package/dist/auth/github.js +6 -2
- package/dist/auth/google.js +6 -2
- package/dist/auth/index.d.ts +1 -0
- package/dist/auth/index.js +1 -0
- package/dist/auth/local/index.d.ts +1 -0
- package/dist/auth/local/index.js +17 -0
- package/dist/auth/local.d.ts +285 -0
- package/dist/auth/local.js +709 -0
- package/dist/auth/microsoft.js +7 -2
- package/dist/backups/onedrive.d.ts +2 -1
- package/dist/backups/onedrive.js +6 -2
- package/dist/config/index.js +1 -0
- package/dist/config/types.d.ts +7 -0
- package/dist/core/client.d.ts +4 -0
- package/dist/core/client.js +6 -1
- package/dist/keys/generator.js +12 -3
- package/dist/react/auth.d.ts +21 -0
- package/dist/react/auth.js +121 -0
- package/dist/utils/dynamic.js +0 -6
- package/dist/utils/uuid.d.ts +3 -4
- package/dist/utils/uuid.js +40 -10
- package/docs/auth.md +85 -2
- package/package.json +6 -1
- package/skills/local-lite-auth/SKILL.md +189 -0
- package/skills/local-lite-backups/SKILL.md +164 -0
- package/skills/local-lite-offline-actions/SKILL.md +122 -0
- package/skills/local-lite-react/SKILL.md +124 -0
- package/skills/local-lite-schema/SKILL.md +171 -0
- package/skills/local-lite-setup/SKILL.md +203 -21
- package/skills/local-lite-storage/SKILL.md +116 -0
- package/skills/local-lite-upgrade/SKILL.md +45 -16
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-auth
|
|
3
|
+
description: Implement authentication and session management in local-lite. Use when setting up zero-backend local SQLite authentication (LocalAuthEngine, useLocalAuth), configuring PBKDF2 crypto, brute-force lockout, single-use reset tokens, or integrating OAuth providers (Google, Microsoft, GitHub, Apple) and offline sessions.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Authentication
|
|
7
|
+
|
|
8
|
+
Comprehensive guide for implementing zero-backend local SQLite authentication and OAuth integrations in `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Zero-Backend Local SQLite Auth (`LocalAuthEngine`)
|
|
13
|
+
|
|
14
|
+
`LocalAuthEngine` provides fully local, client-side authentication stored directly in private SQLite tables (`_local_users` and `_local_user_tokens`). It requires no remote servers or cloud accounts.
|
|
15
|
+
|
|
16
|
+
### Features
|
|
17
|
+
* **PBKDF2-SHA256 Cryptography**: Fast, unboxed 32-bit integer arithmetic optimized for mobile (Hermes) and hardware-accelerated WebCrypto on Web.
|
|
18
|
+
* **Cryptographic Salting**: 16-byte (128-bit) secure random salt per user to prevent rainbow table attacks.
|
|
19
|
+
* **Timing-Attack Protection**: Constant-time byte comparisons (`timingSafeEqual`) and dummy verification for non-existent accounts.
|
|
20
|
+
* **Brute-Force Lockout**: Automatically locks accounts after consecutive failed attempts for a configurable duration.
|
|
21
|
+
* **Single-Use Reset Tokens**: 32-byte high-entropy tokens with SHA-256 storage and automated expiration.
|
|
22
|
+
* **Offline Sessions**: Integrated with `SessionManager` for persistent multi-device or single-device offline session lifecycles.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 2. Configuration
|
|
27
|
+
|
|
28
|
+
Configure local auth directly in `defineSyncConfig`:
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { defineSyncConfig } from 'local-lite/config';
|
|
32
|
+
|
|
33
|
+
export const syncConfig = defineSyncConfig({
|
|
34
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
35
|
+
tables: ['tasks'],
|
|
36
|
+
localAuth: {
|
|
37
|
+
// Optional table names (defaults: '_local_users', '_local_user_tokens')
|
|
38
|
+
usersTable: '_local_users',
|
|
39
|
+
tokensTable: '_local_user_tokens',
|
|
40
|
+
|
|
41
|
+
// Password requirements & validation
|
|
42
|
+
minPasswordLength: 8,
|
|
43
|
+
validatePassword: (password: string) => {
|
|
44
|
+
if (!/[0-9]/.test(password)) return 'Password must include at least one number.';
|
|
45
|
+
return true;
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
// Brute-force lockout protection
|
|
49
|
+
maxFailedAttempts: 5, // Set to 0 to disable
|
|
50
|
+
lockoutDurationMs: 15 * 60 * 1000, // 15 minutes
|
|
51
|
+
|
|
52
|
+
// Password reset token expiration
|
|
53
|
+
resetTokenExpiryMs: 60 * 60 * 1000, // 1 hour
|
|
54
|
+
|
|
55
|
+
// Tuning (defaults: 'PBKDF2-SHA256' with 1,000 rounds)
|
|
56
|
+
algorithm: 'PBKDF2-SHA256',
|
|
57
|
+
iterations: 1_000,
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 3. Using `useLocalAuth` in React / React Native
|
|
65
|
+
|
|
66
|
+
The `useLocalAuth` hook exposes reactive user state, active session info, and authentication actions:
|
|
67
|
+
|
|
68
|
+
```tsx
|
|
69
|
+
import React, { useState } from 'react';
|
|
70
|
+
import { View, Text, TextInput, Button, Alert } from 'react-native';
|
|
71
|
+
import { useLocalAuth } from 'local-lite/react';
|
|
72
|
+
import { getSyncClient } from './sync.config';
|
|
73
|
+
|
|
74
|
+
export function AuthScreen() {
|
|
75
|
+
const [client, setClient] = useState(null);
|
|
76
|
+
React.useEffect(() => { getSyncClient().then(setClient); }, []);
|
|
77
|
+
|
|
78
|
+
const {
|
|
79
|
+
user,
|
|
80
|
+
session,
|
|
81
|
+
isSignedIn,
|
|
82
|
+
loading,
|
|
83
|
+
error,
|
|
84
|
+
signIn,
|
|
85
|
+
signUp,
|
|
86
|
+
signOut,
|
|
87
|
+
refetchUser,
|
|
88
|
+
} = useLocalAuth(client?.auth);
|
|
89
|
+
|
|
90
|
+
const [email, setEmail] = useState('');
|
|
91
|
+
const [password, setPassword] = useState('');
|
|
92
|
+
|
|
93
|
+
if (isSignedIn && user) {
|
|
94
|
+
return (
|
|
95
|
+
<View>
|
|
96
|
+
<Text>Welcome, {user.displayName || user.email}!</Text>
|
|
97
|
+
<Text>Role: {user.role}</Text>
|
|
98
|
+
<Text>Session ID: {session?.id}</Text>
|
|
99
|
+
<Button title="Sign Out" onPress={() => signOut()} />
|
|
100
|
+
</View>
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return (
|
|
105
|
+
<View>
|
|
106
|
+
<TextInput placeholder="Email" value={email} onChangeText={setEmail} autoCapitalize="none" />
|
|
107
|
+
<TextInput placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry />
|
|
108
|
+
|
|
109
|
+
<Button
|
|
110
|
+
title={loading ? 'Processing...' : 'Sign In'}
|
|
111
|
+
onPress={() => signIn(email, password).catch(err => Alert.alert('Error', err.message))}
|
|
112
|
+
disabled={loading}
|
|
113
|
+
/>
|
|
114
|
+
<Button
|
|
115
|
+
title="Register New Account"
|
|
116
|
+
onPress={() =>
|
|
117
|
+
signUp({
|
|
118
|
+
email,
|
|
119
|
+
password,
|
|
120
|
+
displayName: 'Alice',
|
|
121
|
+
role: 'admin',
|
|
122
|
+
metadata: { theme: 'dark' },
|
|
123
|
+
}).catch(err => Alert.alert('Error', err.message))
|
|
124
|
+
}
|
|
125
|
+
/>
|
|
126
|
+
</View>
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## 4. Password Management & Cryptographic Resets
|
|
134
|
+
|
|
135
|
+
### Changing Passwords (User Authenticated)
|
|
136
|
+
```typescript
|
|
137
|
+
await client.auth.changePassword({
|
|
138
|
+
userId: user.id,
|
|
139
|
+
oldPassword: 'OldPassword123!',
|
|
140
|
+
newPassword: 'NewPassword456!',
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Password Reset Flow (Forgot Password)
|
|
145
|
+
```typescript
|
|
146
|
+
// 1. Generate a single-use 32-byte reset token (expires in 1 hour)
|
|
147
|
+
const { token, expiresAt } = await client.auth.createPasswordResetToken('user@example.com');
|
|
148
|
+
|
|
149
|
+
// 2. Deliver token to user via local notification, SMS, or QR code
|
|
150
|
+
|
|
151
|
+
// 3. User submits the token with their new password
|
|
152
|
+
await client.auth.resetPasswordWithToken(token, 'NewStrongPassword789!');
|
|
153
|
+
// The token is permanently invalidated in SQLite and the account is unlocked.
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 5. OAuth Providers & Cloud Auth
|
|
159
|
+
|
|
160
|
+
`local-lite/auth` also includes standalone OAuth clients and hooks for external identity providers:
|
|
161
|
+
|
|
162
|
+
### Google OAuth
|
|
163
|
+
```typescript
|
|
164
|
+
import { GoogleAuthClient } from 'local-lite/auth';
|
|
165
|
+
import { useGoogleAuth } from 'local-lite/react';
|
|
166
|
+
|
|
167
|
+
const googleClient = new GoogleAuthClient({
|
|
168
|
+
clientId: 'YOUR_GOOGLE_CLIENT_ID',
|
|
169
|
+
redirectUri: 'YOUR_REDIRECT_URI',
|
|
170
|
+
scopes: ['openid', 'profile', 'email'],
|
|
171
|
+
authorize: async (req) => { /* invoke browser or WebBrowser.openAuthSessionAsync */ },
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Microsoft OAuth & OneDrive
|
|
176
|
+
```typescript
|
|
177
|
+
import { MicrosoftAuthClient } from 'local-lite/auth';
|
|
178
|
+
|
|
179
|
+
const msClient = new MicrosoftAuthClient({
|
|
180
|
+
clientId: 'YOUR_MS_CLIENT_ID',
|
|
181
|
+
redirectUri: 'YOUR_REDIRECT_URI',
|
|
182
|
+
scopes: ['openid', 'profile', 'User.Read', 'Files.ReadWrite.AppFolder'],
|
|
183
|
+
authorize: async (req) => { /* invoke browser */ },
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Apple & GitHub OAuth
|
|
188
|
+
Clients are available via `AppleAuthClient` and `GitHubAuthClient` with matching React hooks (`useAppleAuth`, `useGitHubAuth`).
|
|
189
|
+
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-backups
|
|
3
|
+
description: Implement cloud backups, AES-256-GCM database encryption, and restore operations in local-lite. Use when configuring OneDrive or Google Drive backups, encrypted SQLite backups with passphrases, backup progress hooks, or useCloudBackup / useOneDriveBackup.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Backups & Encryption
|
|
7
|
+
|
|
8
|
+
Comprehensive guide for creating, encrypting, and restoring SQLite database backups to Microsoft OneDrive and Google Drive.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Cloud Backup Providers
|
|
13
|
+
|
|
14
|
+
`local-lite/backups` provides dedicated clients for user-owned cloud drives. Backups are stored in an application-scoped folder (`approot:/backups/` on OneDrive, `appDataFolder` on Google Drive), so the user retains full ownership of their data.
|
|
15
|
+
|
|
16
|
+
### Supported Providers
|
|
17
|
+
* **Microsoft OneDrive**: `OneDriveBackupClient` (uses Microsoft Graph API).
|
|
18
|
+
* **Google Drive**: `GoogleDriveBackupClient` (uses Google Drive v3 REST API).
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 2. Setting Up Cloud Backups
|
|
23
|
+
|
|
24
|
+
### OneDrive Backup Setup
|
|
25
|
+
```typescript
|
|
26
|
+
import { OneDriveBackupClient } from 'local-lite/backups';
|
|
27
|
+
import { MicrosoftAuthClient } from 'local-lite/auth';
|
|
28
|
+
|
|
29
|
+
// 1. Create or reuse your Microsoft Auth Client
|
|
30
|
+
const authClient = new MicrosoftAuthClient({
|
|
31
|
+
clientId: process.env.EXPO_PUBLIC_MS_CLIENT_ID!,
|
|
32
|
+
redirectUri: 'myapp://auth',
|
|
33
|
+
scopes: ['openid', 'profile', 'Files.ReadWrite.AppFolder'],
|
|
34
|
+
authorize: async (req) => { /* Expo WebBrowser session */ },
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// 2. Instantiate OneDriveBackupClient
|
|
38
|
+
export const oneDriveClient = new OneDriveBackupClient({
|
|
39
|
+
authClient,
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Google Drive Backup Setup
|
|
44
|
+
```typescript
|
|
45
|
+
import { GoogleDriveBackupClient } from 'local-lite/backups';
|
|
46
|
+
import { GoogleAuthClient } from 'local-lite/auth';
|
|
47
|
+
|
|
48
|
+
const authClient = new GoogleAuthClient({
|
|
49
|
+
clientId: process.env.EXPO_PUBLIC_GOOGLE_CLIENT_ID!,
|
|
50
|
+
redirectUri: 'myapp://auth',
|
|
51
|
+
scopes: ['https://www.googleapis.com/auth/drive.appdata'],
|
|
52
|
+
authorize: async (req) => { /* Expo WebBrowser session */ },
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
export const googleDriveClient = new GoogleDriveBackupClient({
|
|
56
|
+
authClient,
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 3. Creating & Restoring Backups
|
|
63
|
+
|
|
64
|
+
### Manual Backup Operation
|
|
65
|
+
```typescript
|
|
66
|
+
import { getSyncClient } from './sync.config';
|
|
67
|
+
|
|
68
|
+
const client = await getSyncClient();
|
|
69
|
+
|
|
70
|
+
// Upload current database snapshot to cloud
|
|
71
|
+
const result = await oneDriveClient.backup(client.db, {
|
|
72
|
+
fileName: `backup-${Date.now()}.db`,
|
|
73
|
+
});
|
|
74
|
+
console.log('Uploaded backup:', result.name, result.size);
|
|
75
|
+
|
|
76
|
+
// List available cloud backups
|
|
77
|
+
const files = await oneDriveClient.list();
|
|
78
|
+
|
|
79
|
+
// Restore from a specific backup file
|
|
80
|
+
await oneDriveClient.restore(client.db, files[0].id);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 4. End-to-End Database Encryption (AES-256-GCM)
|
|
86
|
+
|
|
87
|
+
For maximum privacy, encrypt the SQLite database snapshot with an end-user passphrase before it leaves the device:
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
// 1. Encrypted Backup
|
|
91
|
+
await oneDriveClient.backup(client.db, {
|
|
92
|
+
fileName: `encrypted-backup-${Date.now()}.db`,
|
|
93
|
+
passphrase: 'UserSecretPassphrase123!',
|
|
94
|
+
// Uses PBKDF2 key derivation and AES-256-GCM authenticated encryption
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// 2. Encrypted Restore
|
|
98
|
+
await oneDriveClient.restore(client.db, files[0].id, {
|
|
99
|
+
passphrase: 'UserSecretPassphrase123!',
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
If the passphrase is incorrect or the backup payload has been tampered with, AES-256-GCM authentication fails immediately and protects the local database from corruption.
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## 5. React Integration (`useCloudBackup`)
|
|
108
|
+
|
|
109
|
+
Use the `useCloudBackup` (or `useOneDriveBackup` / `useGoogleDriveBackup`) hook for reactive backup management:
|
|
110
|
+
|
|
111
|
+
```tsx
|
|
112
|
+
import React from 'react';
|
|
113
|
+
import { View, Text, Button, ActivityIndicator } from 'react-native';
|
|
114
|
+
import { useOneDriveBackup } from 'local-lite/react';
|
|
115
|
+
import { oneDriveClient } from './backup.config';
|
|
116
|
+
import { getSyncClient } from './sync.config';
|
|
117
|
+
|
|
118
|
+
export function BackupScreen() {
|
|
119
|
+
const [client, setClient] = React.useState(null);
|
|
120
|
+
React.useEffect(() => { getSyncClient().then(setClient); }, []);
|
|
121
|
+
|
|
122
|
+
const {
|
|
123
|
+
connected,
|
|
124
|
+
files,
|
|
125
|
+
isBackingUp,
|
|
126
|
+
isRestoring,
|
|
127
|
+
progress,
|
|
128
|
+
backup,
|
|
129
|
+
restore,
|
|
130
|
+
refreshFiles,
|
|
131
|
+
connect,
|
|
132
|
+
} = useOneDriveBackup(oneDriveClient, client?.db);
|
|
133
|
+
|
|
134
|
+
if (!connected) {
|
|
135
|
+
return <Button title="Connect to OneDrive" onPress={() => connect()} />;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return (
|
|
139
|
+
<View>
|
|
140
|
+
<Text>Cloud Backups ({files.length} available)</Text>
|
|
141
|
+
|
|
142
|
+
{isBackingUp && <Text>Backing up: {progress}%</Text>}
|
|
143
|
+
{isRestoring && <Text>Restoring: {progress}%</Text>}
|
|
144
|
+
|
|
145
|
+
<Button
|
|
146
|
+
title="Create Encrypted Backup"
|
|
147
|
+
onPress={() => backup({ passphrase: 'MySecretPassphrase!' })}
|
|
148
|
+
disabled={isBackingUp || isRestoring}
|
|
149
|
+
/>
|
|
150
|
+
|
|
151
|
+
{files.map((file) => (
|
|
152
|
+
<View key={file.id}>
|
|
153
|
+
<Text>{file.name} ({(file.size / 1024).toFixed(1)} KB)</Text>
|
|
154
|
+
<Button
|
|
155
|
+
title="Restore"
|
|
156
|
+
onPress={() => restore(file.id, { passphrase: 'MySecretPassphrase!' })}
|
|
157
|
+
/>
|
|
158
|
+
</View>
|
|
159
|
+
))}
|
|
160
|
+
</View>
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-offline-actions
|
|
3
|
+
description: Queue offline actions, schedule background jobs, store key-value preferences, and track sync telemetry in local-lite. Use when using client.actions, client.scheduler, client.kv, client.getMetrics(), or handling offline mutation retries.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Offline Actions, KV & Scheduler
|
|
7
|
+
|
|
8
|
+
Guide for executing queued actions, running background jobs, persisting key-value pairs, and inspecting sync telemetry with `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Action Manager & Outbox (`client.actions`)
|
|
13
|
+
|
|
14
|
+
The Action Manager handles complex business logic mutations that must be queued offline and executed reliably when connectivity is restored:
|
|
15
|
+
|
|
16
|
+
### Enqueueing an Action
|
|
17
|
+
```typescript
|
|
18
|
+
import { getSyncClient } from './sync.config';
|
|
19
|
+
|
|
20
|
+
const client = await getSyncClient();
|
|
21
|
+
|
|
22
|
+
// Enqueue an action (e.g. sending an email, processing a payment, or syncing with third-party API)
|
|
23
|
+
const action = await client.actions.enqueue({
|
|
24
|
+
type: 'SEND_INVITATION',
|
|
25
|
+
payload: {
|
|
26
|
+
inviteeEmail: 'colleague@example.com',
|
|
27
|
+
teamId: 'team_xyz',
|
|
28
|
+
},
|
|
29
|
+
maxRetries: 5,
|
|
30
|
+
retryDelayMs: 2000,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
console.log('Queued action:', action.id, action.status);
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Registering Action Handlers
|
|
37
|
+
Register handlers that execute when the device is online:
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
client.actions.registerHandler('SEND_INVITATION', async (payload) => {
|
|
41
|
+
const res = await fetch('https://api.example.com/invites', {
|
|
42
|
+
method: 'POST',
|
|
43
|
+
headers: { 'Content-Type': 'application/json' },
|
|
44
|
+
body: JSON.stringify(payload),
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
if (!res.ok) {
|
|
48
|
+
throw new Error(`Invitation failed with status ${res.status}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return await res.json();
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## 2. Key-Value Store & Secret Preferences (`client.kv`)
|
|
58
|
+
|
|
59
|
+
`client.kv` provides lightweight key-value storage directly within SQLite with optional TTL expiration and AES-256-GCM encryption.
|
|
60
|
+
|
|
61
|
+
### Basic KV Usage
|
|
62
|
+
```typescript
|
|
63
|
+
// Store with optional TTL (expires in 24 hours)
|
|
64
|
+
await client.kv.set('last_viewed_tab', 'dashboard', { ttlMs: 24 * 60 * 60 * 1000 });
|
|
65
|
+
|
|
66
|
+
// Read value (returns null if expired or missing)
|
|
67
|
+
const tab = await client.kv.get('last_viewed_tab');
|
|
68
|
+
|
|
69
|
+
// Delete value
|
|
70
|
+
await client.kv.delete('last_viewed_tab');
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Encrypted Secrets (AES-256-GCM)
|
|
74
|
+
Store sensitive API tokens or user secrets securely:
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
// Encrypt and persist
|
|
78
|
+
await client.kv.setSecret('api_token', 'sk-live-secret-token-12345', 'PassphraseOrHardwareKey');
|
|
79
|
+
|
|
80
|
+
// Decrypt
|
|
81
|
+
const token = await client.kv.getSecret('api_token', 'PassphraseOrHardwareKey');
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 3. Background Job Scheduler (`client.scheduler`)
|
|
87
|
+
|
|
88
|
+
Schedule recurring cron-style or interval jobs that run within your application:
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
// Register a recurring maintenance task
|
|
92
|
+
client.scheduler.registerJob({
|
|
93
|
+
name: 'CLEANUP_OLD_LOGS',
|
|
94
|
+
intervalMs: 60 * 60 * 1000, // Run every hour
|
|
95
|
+
runImmediately: false,
|
|
96
|
+
handler: async () => {
|
|
97
|
+
const oneWeekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
|
|
98
|
+
await client.db.execute('DELETE FROM activity_logs WHERE created_at < ?;', [oneWeekAgo]);
|
|
99
|
+
console.log('Old activity logs purged.');
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// Start scheduler execution
|
|
104
|
+
client.scheduler.start();
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## 4. Sync Telemetry & Health Metrics (`client.getMetrics()`)
|
|
110
|
+
|
|
111
|
+
Monitor the health of your local-first sync pipeline in real time:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
const metrics = await client.getMetrics();
|
|
115
|
+
|
|
116
|
+
console.log('Outbox Queue Size:', metrics.outboxPendingCount);
|
|
117
|
+
console.log('Total Pushes Succeeded:', metrics.pushesSuccessCount);
|
|
118
|
+
console.log('Total Pushes Failed:', metrics.pushesFailedCount);
|
|
119
|
+
console.log('Average Push Latency:', metrics.avgPushDurationMs, 'ms');
|
|
120
|
+
console.log('Last Sync Timestamp:', new Date(metrics.lastSyncAt).toLocaleTimeString());
|
|
121
|
+
```
|
|
122
|
+
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-react
|
|
3
|
+
description: Master reactive patterns, hooks, live queries, and optimistic state in React and React Native with local-lite. Use when writing useLiveQuery, useSyncStatus, useLocalAuth, useKV, useSearch, useQueryBuilder, or optimizing component re-renders.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite React & React Native Integration
|
|
7
|
+
|
|
8
|
+
Comprehensive guide to building reactive, offline-first user interfaces using `local-lite/react`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Core Hooks Overview
|
|
13
|
+
|
|
14
|
+
| Hook | Purpose |
|
|
15
|
+
| :--- | :--- |
|
|
16
|
+
| `useLiveQuery(client, sql, params, deps)` | Reactive SQLite query. Auto-re-runs whenever relevant tables mutate. |
|
|
17
|
+
| `useSyncStatus(client)` | Tracks online/offline status, sync worker state, and outbox changes. |
|
|
18
|
+
| `useLocalAuth(client.auth)` | Manages zero-backend SQLite authentication, user profiles, and sessions. |
|
|
19
|
+
| `useKV(client.kv, key, default)` | Reactive key-value store for preferences and application state. |
|
|
20
|
+
| `useEncryptedKV(client.kv, key, pass)` | End-to-end encrypted secret preferences with AES-256-GCM. |
|
|
21
|
+
| `useSearch(client, ftsTable, query)` | Real-time full-text search powered by SQLite FTS5. |
|
|
22
|
+
| `useQueryBuilder(client, table, filter)` | Declarative MongoDB-style query filters. |
|
|
23
|
+
| `useCloudBackup(backupClient, db)` | Cloud backups (OneDrive / Google Drive) with live progress. |
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 2. Live Queries (`useLiveQuery`)
|
|
28
|
+
|
|
29
|
+
`useLiveQuery` executes raw SQLite queries and re-runs them reactively when affected tables change:
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
import React, { useMemo } from 'react';
|
|
33
|
+
import { FlatList, Text, View } from 'react-native';
|
|
34
|
+
import { useLiveQuery } from 'local-lite/react';
|
|
35
|
+
import type { LocalFirstClient } from 'local-lite/config';
|
|
36
|
+
|
|
37
|
+
interface Todo {
|
|
38
|
+
id: string;
|
|
39
|
+
title: string;
|
|
40
|
+
completed: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function TodoList({ client, projectId }: { client: LocalFirstClient; projectId: string }) {
|
|
44
|
+
// Always memoize params to prevent unnecessary query executions
|
|
45
|
+
const params = useMemo(() => [projectId], [projectId]);
|
|
46
|
+
|
|
47
|
+
const { data: todos, loading, error, refetch } = useLiveQuery<Todo>(
|
|
48
|
+
client,
|
|
49
|
+
'SELECT * FROM todos WHERE project_id = ? ORDER BY updated_at DESC;',
|
|
50
|
+
params
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
if (loading) return <Text>Loading...</Text>;
|
|
54
|
+
if (error) return <Text>Query error: {error.message}</Text>;
|
|
55
|
+
|
|
56
|
+
return (
|
|
57
|
+
<FlatList
|
|
58
|
+
data={todos}
|
|
59
|
+
keyExtractor={(item) => item.id}
|
|
60
|
+
renderItem={({ item }) => (
|
|
61
|
+
<Text style={{ textDecorationLine: item.completed ? 'line-through' : 'none' }}>
|
|
62
|
+
{item.title}
|
|
63
|
+
</Text>
|
|
64
|
+
)}
|
|
65
|
+
/>
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 3. Optimistic 0ms Writes (`client.mutate`)
|
|
73
|
+
|
|
74
|
+
For zero-latency user experiences, perform writes using `client.mutate()`. This writes directly to local SQLite in an atomic transaction and automatically triggers all matching `useLiveQuery` hooks across the UI:
|
|
75
|
+
|
|
76
|
+
```tsx
|
|
77
|
+
import { generateUUID } from 'local-lite';
|
|
78
|
+
|
|
79
|
+
async function addTodo(client: LocalFirstClient, title: string, projectId: string) {
|
|
80
|
+
const newTodo = {
|
|
81
|
+
id: generateUUID(),
|
|
82
|
+
project_id: projectId,
|
|
83
|
+
title,
|
|
84
|
+
completed: 0,
|
|
85
|
+
updated_at: Date.now(),
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// 1. Dual-writes to local SQLite and queues in outbox for sync
|
|
89
|
+
await client.mutate('todos', 'INSERT', newTodo);
|
|
90
|
+
// All useLiveQuery hooks listening to 'todos' update instantly (0ms)!
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## 4. Reactive Preferences & Encrypted KV
|
|
97
|
+
|
|
98
|
+
```tsx
|
|
99
|
+
import { useKV, useEncryptedKV } from 'local-lite/react';
|
|
100
|
+
|
|
101
|
+
export function SettingsScreen({ client }) {
|
|
102
|
+
// 1. Plain reactive setting
|
|
103
|
+
const [theme, setTheme] = useKV<'light' | 'dark'>(client?.kv, 'app_theme', 'light');
|
|
104
|
+
|
|
105
|
+
// 2. Encrypted setting (AES-256-GCM)
|
|
106
|
+
const [apiKey, setApiKey] = useEncryptedKV(client?.kv, 'openai_key', 'UserPassphrase!');
|
|
107
|
+
|
|
108
|
+
return (
|
|
109
|
+
<View>
|
|
110
|
+
<Text>Theme: {theme}</Text>
|
|
111
|
+
<Button title="Toggle Theme" onPress={() => setTheme(theme === 'light' ? 'dark' : 'light')} />
|
|
112
|
+
</View>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## 5. Performance Best Practices
|
|
120
|
+
|
|
121
|
+
1. **Memoize Query Parameters**: Pass memoized arrays or primitives to `useLiveQuery` to avoid re-triggering queries on every parent component render.
|
|
122
|
+
2. **Selective Column Projections**: In high-frequency queries, select only required columns (`SELECT id, title FROM ...`) instead of `SELECT *` to reduce SQLite serialization overhead.
|
|
123
|
+
3. **Batch Mutations**: Wrap bulk inserts in transactions or `client.mutateBatch()` rather than issuing individual `INSERT` statements in loops.
|
|
124
|
+
|