local-lite 0.1.3 → 0.2.1
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/dist/auth/apple.d.ts +3 -4
- package/dist/auth/apple.js +26 -3
- package/dist/auth/github.d.ts +3 -5
- package/dist/auth/github.js +18 -4
- package/dist/auth/google.d.ts +3 -6
- package/dist/auth/google.js +19 -5
- package/dist/auth/identity.d.ts +42 -0
- package/dist/auth/identity.js +63 -0
- package/dist/auth/index.d.ts +2 -0
- package/dist/auth/index.js +2 -0
- package/dist/auth/microsoft.d.ts +3 -5
- package/dist/auth/microsoft.js +16 -3
- package/dist/auth/session.d.ts +4 -0
- package/dist/auth/session.js +19 -1
- package/dist/auth/unified.d.ts +73 -0
- package/dist/auth/unified.js +188 -0
- package/dist/utils/dynamic.js +0 -3
- package/package.json +1 -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,188 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UnifiedAuthManager = void 0;
|
|
4
|
+
const identity_js_1 = require("./identity.js");
|
|
5
|
+
/**
|
|
6
|
+
* High-level orchestrator that unifies multiple OAuth providers (Google, GitHub,
|
|
7
|
+
* Microsoft, Apple) and local auth into a single consistent user identity model.
|
|
8
|
+
*/
|
|
9
|
+
class UnifiedAuthManager {
|
|
10
|
+
google;
|
|
11
|
+
github;
|
|
12
|
+
microsoft;
|
|
13
|
+
apple;
|
|
14
|
+
local;
|
|
15
|
+
sessionManager;
|
|
16
|
+
unifyByEmail;
|
|
17
|
+
emailNamespace;
|
|
18
|
+
listeners = new Set();
|
|
19
|
+
unsubscribers = [];
|
|
20
|
+
constructor(config) {
|
|
21
|
+
this.google = config.google;
|
|
22
|
+
this.github = config.github;
|
|
23
|
+
this.microsoft = config.microsoft;
|
|
24
|
+
this.apple = config.apple;
|
|
25
|
+
this.local = config.local;
|
|
26
|
+
this.sessionManager = config.sessionManager;
|
|
27
|
+
this.unifyByEmail = config.unifyByEmail !== false;
|
|
28
|
+
this.emailNamespace = config.emailNamespace || identity_js_1.DEFAULT_UNIFIED_EMAIL_NAMESPACE;
|
|
29
|
+
this.bindProviderListeners();
|
|
30
|
+
}
|
|
31
|
+
bindProviderListeners() {
|
|
32
|
+
if (this.google) {
|
|
33
|
+
this.unsubscribers.push(this.google.onAuthStateChange(user => {
|
|
34
|
+
if (!user)
|
|
35
|
+
return;
|
|
36
|
+
const unified = (0, identity_js_1.createUnifiedAuthUser)(user, 'google', {
|
|
37
|
+
namespace: this.emailNamespace,
|
|
38
|
+
requireVerifiedEmail: this.unifyByEmail,
|
|
39
|
+
});
|
|
40
|
+
this.notify(unified);
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
notify(user) {
|
|
45
|
+
for (const listener of this.listeners) {
|
|
46
|
+
try {
|
|
47
|
+
listener(user);
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
console.warn('[UnifiedAuthManager] Error in auth state listener:', err);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Subscribes to global unified authentication state changes.
|
|
56
|
+
*/
|
|
57
|
+
onAuthStateChange(listener) {
|
|
58
|
+
this.listeners.add(listener);
|
|
59
|
+
return () => {
|
|
60
|
+
this.listeners.delete(listener);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Authenticates using the specified provider and automatically establishes a unified session.
|
|
65
|
+
*/
|
|
66
|
+
async signIn(provider, credentials) {
|
|
67
|
+
let rawUser = null;
|
|
68
|
+
let token = null;
|
|
69
|
+
let refreshToken = null;
|
|
70
|
+
if (provider === 'google') {
|
|
71
|
+
if (!this.google)
|
|
72
|
+
throw new Error('GoogleAuthClient is not configured on UnifiedAuthManager.');
|
|
73
|
+
rawUser = await this.google.signIn();
|
|
74
|
+
token = await this.google.getValidAccessToken().catch(() => null);
|
|
75
|
+
}
|
|
76
|
+
else if (provider === 'github') {
|
|
77
|
+
if (!this.github)
|
|
78
|
+
throw new Error('GitHubAuthClient is not configured on UnifiedAuthManager.');
|
|
79
|
+
rawUser = await this.github.signIn();
|
|
80
|
+
token = await this.github.getValidAccessToken().catch(() => null);
|
|
81
|
+
}
|
|
82
|
+
else if (provider === 'microsoft') {
|
|
83
|
+
if (!this.microsoft)
|
|
84
|
+
throw new Error('MicrosoftAuthClient is not configured on UnifiedAuthManager.');
|
|
85
|
+
rawUser = await this.microsoft.signIn();
|
|
86
|
+
token = await this.microsoft.getValidAccessToken().catch(() => null);
|
|
87
|
+
}
|
|
88
|
+
else if (provider === 'apple') {
|
|
89
|
+
if (!this.apple)
|
|
90
|
+
throw new Error('AppleAuthClient is not configured on UnifiedAuthManager.');
|
|
91
|
+
rawUser = await this.apple.signIn();
|
|
92
|
+
}
|
|
93
|
+
else if (provider === 'local') {
|
|
94
|
+
if (!this.local)
|
|
95
|
+
throw new Error('LocalAuthEngine is not configured on UnifiedAuthManager.');
|
|
96
|
+
const identifier = credentials?.email || credentials?.identifier;
|
|
97
|
+
const password = credentials?.password;
|
|
98
|
+
if (!identifier || !password) {
|
|
99
|
+
throw new Error('Local authentication requires identifier/email and password credentials.');
|
|
100
|
+
}
|
|
101
|
+
const result = await this.local.signIn({ identifier, password });
|
|
102
|
+
rawUser = result.user;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
throw new Error(`Unsupported auth provider: ${provider}`);
|
|
106
|
+
}
|
|
107
|
+
if (!rawUser) {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
const unifiedUser = (0, identity_js_1.createUnifiedAuthUser)(rawUser, provider, {
|
|
111
|
+
namespace: this.emailNamespace,
|
|
112
|
+
requireVerifiedEmail: this.unifyByEmail,
|
|
113
|
+
});
|
|
114
|
+
if (this.sessionManager) {
|
|
115
|
+
await this.sessionManager.createSession({
|
|
116
|
+
userId: unifiedUser.userId,
|
|
117
|
+
user: unifiedUser,
|
|
118
|
+
provider,
|
|
119
|
+
token,
|
|
120
|
+
refreshToken,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
this.notify(unifiedUser);
|
|
124
|
+
return unifiedUser;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Retrieves the currently authenticated unified user.
|
|
128
|
+
*/
|
|
129
|
+
async getUser() {
|
|
130
|
+
if (this.sessionManager) {
|
|
131
|
+
const session = await this.sessionManager.getActiveSession();
|
|
132
|
+
if (session?.user)
|
|
133
|
+
return session.user;
|
|
134
|
+
}
|
|
135
|
+
if (this.google && (await this.google.isSignedIn())) {
|
|
136
|
+
const gUser = await this.google.getUser();
|
|
137
|
+
if (gUser) {
|
|
138
|
+
return (0, identity_js_1.createUnifiedAuthUser)(gUser, 'google', {
|
|
139
|
+
namespace: this.emailNamespace,
|
|
140
|
+
requireVerifiedEmail: this.unifyByEmail,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Retrieves the active SQLite session record.
|
|
148
|
+
*/
|
|
149
|
+
async getSession() {
|
|
150
|
+
if (!this.sessionManager)
|
|
151
|
+
return null;
|
|
152
|
+
return await this.sessionManager.getActiveSession();
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Checks whether there is an active session or signed-in provider.
|
|
156
|
+
*/
|
|
157
|
+
async isAuthenticated() {
|
|
158
|
+
const user = await this.getUser();
|
|
159
|
+
return user !== null;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Signs out of the active session and all configured providers.
|
|
163
|
+
*/
|
|
164
|
+
async signOut() {
|
|
165
|
+
if (this.sessionManager) {
|
|
166
|
+
await this.sessionManager.clearSession();
|
|
167
|
+
}
|
|
168
|
+
await this.google?.signOut().catch(() => { });
|
|
169
|
+
await this.github?.signOut().catch(() => { });
|
|
170
|
+
await this.microsoft?.signOut().catch(() => { });
|
|
171
|
+
await this.apple?.signOut().catch(() => { });
|
|
172
|
+
this.notify(null);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Cleans up all event listeners.
|
|
176
|
+
*/
|
|
177
|
+
destroy() {
|
|
178
|
+
for (const unsub of this.unsubscribers) {
|
|
179
|
+
try {
|
|
180
|
+
unsub();
|
|
181
|
+
}
|
|
182
|
+
catch { }
|
|
183
|
+
}
|
|
184
|
+
this.unsubscribers = [];
|
|
185
|
+
this.listeners.clear();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
exports.UnifiedAuthManager = UnifiedAuthManager;
|
package/dist/utils/dynamic.js
CHANGED
package/package.json
CHANGED
|
@@ -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
|
+
|