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.
- package/README.md +5 -2
- package/bin/local-lite.mjs +65 -61
- 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/local.d.ts +33 -1
- package/dist/auth/local.js +94 -13
- 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/package.json +1 -2
- package/skills/local-lite-auth/SKILL.md +67 -27
- package/skills/local-lite-server/SKILL.md +127 -0
- package/docs/.nojekyll +0 -1
- package/docs/README.md +0 -108
- package/docs/_sidebar.md +0 -22
- package/docs/actions-email.md +0 -222
- package/docs/adapters-local.md +0 -272
- package/docs/adapters-remote.md +0 -291
- package/docs/api-keys.md +0 -114
- package/docs/architecture.md +0 -106
- package/docs/auth.md +0 -342
- package/docs/backups.md +0 -214
- package/docs/breaking-changes.md +0 -147
- package/docs/client-api.md +0 -412
- package/docs/configuration.md +0 -228
- package/docs/conflict-resolution.md +0 -78
- package/docs/getting-started.md +0 -190
- package/docs/google-auth.md +0 -234
- package/docs/index.html +0 -166
- package/docs/kv.md +0 -89
- package/docs/maintenance-portability.md +0 -133
- package/docs/react-hooks.md +0 -457
- package/docs/scheduler.md +0 -81
- package/docs/search.md +0 -71
- package/docs/server.md +0 -101
- package/docs/session.md +0 -129
- package/docs/storage.md +0 -265
package/docs/adapters-local.md
DELETED
|
@@ -1,272 +0,0 @@
|
|
|
1
|
-
# 💾 Local SQLite Adapters
|
|
2
|
-
|
|
3
|
-
`local-lite` supports any SQLite driver across mobile, desktop, and web environments.
|
|
4
|
-
|
|
5
|
-
The configuration helper automatically detects the driver passed to `config.database`. Alternatively, you can import and instantiate any adapter directly.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## 1. Expo SQLite (`expo-sqlite`)
|
|
10
|
-
|
|
11
|
-
Recommended for **Expo & React Native** apps.
|
|
12
|
-
|
|
13
|
-
```bash
|
|
14
|
-
npx expo install expo-sqlite
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
### Auto-Detection via `defineSyncConfig`:
|
|
18
|
-
```typescript
|
|
19
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
20
|
-
import * as SQLite from 'expo-sqlite';
|
|
21
|
-
|
|
22
|
-
export const config = defineSyncConfig({
|
|
23
|
-
database: () => SQLite.openDatabaseAsync('my_app.db'),
|
|
24
|
-
tables: ['todos'],
|
|
25
|
-
});
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
### Standalone Adapter:
|
|
29
|
-
```typescript
|
|
30
|
-
import { ExpoSQLiteAdapter } from 'local-lite/expo-sqlite';
|
|
31
|
-
import * as SQLite from 'expo-sqlite';
|
|
32
|
-
|
|
33
|
-
const db = await SQLite.openDatabaseAsync('my_app.db');
|
|
34
|
-
const adapter = new ExpoSQLiteAdapter(db);
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
---
|
|
38
|
-
|
|
39
|
-
## 2. OP-SQLite (`@op-engineering/op-sqlite`)
|
|
40
|
-
|
|
41
|
-
High-performance JSI SQLite driver for **bare React Native** apps.
|
|
42
|
-
|
|
43
|
-
```bash
|
|
44
|
-
npm install @op-engineering/op-sqlite
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
### Usage:
|
|
48
|
-
```typescript
|
|
49
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
50
|
-
import { open } from '@op-engineering/op-sqlite';
|
|
51
|
-
|
|
52
|
-
const db = open({ name: 'my_app.db' });
|
|
53
|
-
|
|
54
|
-
export const config = defineSyncConfig({
|
|
55
|
-
database: db,
|
|
56
|
-
tables: ['todos'],
|
|
57
|
-
});
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
---
|
|
61
|
-
|
|
62
|
-
## 3. Better-SQLite3 (`better-sqlite3`)
|
|
63
|
-
|
|
64
|
-
Synchronous, ultra-fast SQLite driver for **Node.js, Electron, Next.js, and server environments**.
|
|
65
|
-
|
|
66
|
-
```bash
|
|
67
|
-
npm install better-sqlite3
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
### Usage:
|
|
71
|
-
```typescript
|
|
72
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
73
|
-
import Database from 'better-sqlite3';
|
|
74
|
-
|
|
75
|
-
const db = new Database('my_app.db');
|
|
76
|
-
|
|
77
|
-
export const config = defineSyncConfig({
|
|
78
|
-
database: db,
|
|
79
|
-
tables: ['todos'],
|
|
80
|
-
});
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
---
|
|
84
|
-
|
|
85
|
-
## 4. Node.js 22+ Built-in (`node:sqlite`)
|
|
86
|
-
|
|
87
|
-
Zero-dependency SQLite bundled directly inside Node.js v22.5.0+.
|
|
88
|
-
|
|
89
|
-
### Usage:
|
|
90
|
-
```typescript
|
|
91
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
92
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
93
|
-
|
|
94
|
-
const db = new DatabaseSync('my_app.db');
|
|
95
|
-
|
|
96
|
-
export const config = defineSyncConfig({
|
|
97
|
-
database: db,
|
|
98
|
-
tables: ['todos'],
|
|
99
|
-
});
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
---
|
|
103
|
-
|
|
104
|
-
## 5. LibSQL / Turso (`@libsql/client`)
|
|
105
|
-
|
|
106
|
-
Supports edge workers, local files, and embedded replicas via Turso / LibSQL.
|
|
107
|
-
|
|
108
|
-
```bash
|
|
109
|
-
npm install @libsql/client
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
### Usage:
|
|
113
|
-
```typescript
|
|
114
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
115
|
-
import { createClient } from '@libsql/client';
|
|
116
|
-
|
|
117
|
-
const client = createClient({
|
|
118
|
-
url: 'file:my_app.db',
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
export const config = defineSyncConfig({
|
|
122
|
-
database: client,
|
|
123
|
-
tables: ['todos'],
|
|
124
|
-
});
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
---
|
|
128
|
-
|
|
129
|
-
## 6. Sql.js (WebAssembly / Browser)
|
|
130
|
-
|
|
131
|
-
Pure WebAssembly SQLite for client-side web applications and PWAs.
|
|
132
|
-
|
|
133
|
-
```bash
|
|
134
|
-
npm install sql.js
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
### Usage:
|
|
138
|
-
```typescript
|
|
139
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
140
|
-
import initSqlJs from 'sql.js';
|
|
141
|
-
|
|
142
|
-
const SQL = await initSqlJs();
|
|
143
|
-
const db = new SQL.Database();
|
|
144
|
-
|
|
145
|
-
export const config = defineSyncConfig({
|
|
146
|
-
database: db,
|
|
147
|
-
tables: ['todos'],
|
|
148
|
-
});
|
|
149
|
-
```
|
|
150
|
-
|
|
151
|
-
---
|
|
152
|
-
|
|
153
|
-
## Custom Local Database Adapters
|
|
154
|
-
|
|
155
|
-
If you use a custom or proprietary SQLite binding, implement the `LocalDBAdapter` interface:
|
|
156
|
-
|
|
157
|
-
```typescript
|
|
158
|
-
import { LocalDBAdapter, LocalTransaction } from 'local-lite';
|
|
159
|
-
|
|
160
|
-
export class CustomSQLiteAdapter implements LocalDBAdapter {
|
|
161
|
-
async execute(sql: string, params?: any[]): Promise<any> {
|
|
162
|
-
// Execute query and return result rows
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async transaction<T>(action: (tx: LocalTransaction) => Promise<T>): Promise<T> {
|
|
166
|
-
// Execute multiple statements atomically
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
async close(): Promise<void> {
|
|
170
|
-
// Optional cleanup
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
## Database Backups
|
|
176
|
-
|
|
177
|
-
The `local-lite/backups` entry point creates SQLite snapshots from database bytes supplied
|
|
178
|
-
by your platform adapter. Its Google Drive backup client handles OAuth authorization-code
|
|
179
|
-
+ PKCE, code exchange, token refresh, and file storage.
|
|
180
|
-
The app supplies its OAuth client ID, callback URI/browser authorization, and secure token
|
|
181
|
-
storage; these platform-specific capabilities cannot safely be assumed by a
|
|
182
|
-
framework-neutral package. Backups do not alter or replace the remote adapter used for
|
|
183
|
-
live synchronization.
|
|
184
|
-
|
|
185
|
-
```typescript
|
|
186
|
-
import {
|
|
187
|
-
createDatabaseBackup,
|
|
188
|
-
GoogleDriveBackupClient,
|
|
189
|
-
createGoogleDriveTokenStore,
|
|
190
|
-
} from 'local-lite/backups';
|
|
191
|
-
|
|
192
|
-
const tokenStore = createGoogleDriveTokenStore(secureKeyValueStorage);
|
|
193
|
-
const drive = new GoogleDriveBackupClient({
|
|
194
|
-
clientId: googleOAuthClientId,
|
|
195
|
-
redirectUri,
|
|
196
|
-
authorize: openAuthorizationUrlInSystemBrowser,
|
|
197
|
-
tokenStore,
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
await drive.connect();
|
|
201
|
-
await createDatabaseBackup(database, drive);
|
|
202
|
-
```
|
|
203
|
-
|
|
204
|
-
The `authorize` callback opens the supplied `authorizationUrl` and returns the
|
|
205
|
-
authorization `code` and `state` from the registered `redirectUri`, or `null` if the user
|
|
206
|
-
cancels. The client validates the OAuth state and performs the PKCE code exchange.
|
|
207
|
-
`tokenStore` implements `get`, `set`, and `remove`; use your platform's secure credential
|
|
208
|
-
storage, not plain preferences. The client refreshes expired tokens automatically, and its
|
|
209
|
-
`list()` method returns backup metadata for restore-selection screens. For apps that
|
|
210
|
-
already manage OAuth, `GoogleDriveBackupStorage` remains available and accepts an
|
|
211
|
-
access-token callback.
|
|
212
|
-
|
|
213
|
-
For example, an Expo app can provide the browser and secure-store bridges:
|
|
214
|
-
|
|
215
|
-
```typescript
|
|
216
|
-
const tokenStore = createGoogleDriveTokenStore(secureStorage, 'drive-backup-tokens');
|
|
217
|
-
const googleClientId = process.env.EXPO_PUBLIC_GOOGLE_DRIVE_CLIENT_ID;
|
|
218
|
-
if (!googleClientId) throw new Error('Google Drive OAuth client ID is required.');
|
|
219
|
-
|
|
220
|
-
const drive = new GoogleDriveBackupClient({
|
|
221
|
-
clientId: googleClientId,
|
|
222
|
-
redirectUri: makeRedirectUri({ scheme: 'myapp', path: 'oauth' }),
|
|
223
|
-
tokenStore,
|
|
224
|
-
authorize: async ({ authorizationUrl, redirectUri }) => {
|
|
225
|
-
const result = await WebBrowser.openAuthSessionAsync(
|
|
226
|
-
authorizationUrl,
|
|
227
|
-
redirectUri,
|
|
228
|
-
);
|
|
229
|
-
if (result.type !== 'success') return null;
|
|
230
|
-
|
|
231
|
-
const callback = new URL(result.url);
|
|
232
|
-
return {
|
|
233
|
-
code: callback.searchParams.get('code') ?? '',
|
|
234
|
-
state: callback.searchParams.get('state') ?? '',
|
|
235
|
-
};
|
|
236
|
-
},
|
|
237
|
-
});
|
|
238
|
-
```
|
|
239
|
-
|
|
240
|
-
Register the exact redirect URI with the Google OAuth client. OAuth client IDs and
|
|
241
|
-
redirect behavior differ by target platform; no generic library can register the app or
|
|
242
|
-
create those provider credentials on the developer's behalf.
|
|
243
|
-
|
|
244
|
-
```typescript
|
|
245
|
-
import {
|
|
246
|
-
createDatabaseBackup,
|
|
247
|
-
restoreDatabaseBackup,
|
|
248
|
-
type BackupDatabase,
|
|
249
|
-
type BackupStorage,
|
|
250
|
-
} from 'local-lite/backups';
|
|
251
|
-
|
|
252
|
-
const database: BackupDatabase = {
|
|
253
|
-
exportDatabase: () => sqliteDatabase.serializeAsync(),
|
|
254
|
-
importDatabase: async bytes => {
|
|
255
|
-
// Validate and restore using the SQLite driver's platform-specific backup APIs.
|
|
256
|
-
await restoreSQLiteSnapshot(sqliteDatabase, bytes);
|
|
257
|
-
},
|
|
258
|
-
};
|
|
259
|
-
|
|
260
|
-
const storage: BackupStorage = {
|
|
261
|
-
save: async (name, bytes) => writeIntoPrivateBackupsDirectory(name, bytes),
|
|
262
|
-
read: async name => readFromPrivateBackupsDirectory(name),
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
const name = await createDatabaseBackup(database, storage);
|
|
266
|
-
await restoreDatabaseBackup(database, storage, name);
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
Backups are stored as plain `.db` files, so anyone with access to the cloud file can read
|
|
270
|
-
the database. Use this only when that exposure is acceptable and protect access through
|
|
271
|
-
the cloud account. Stop concurrent writes and synchronization before restoring, and use
|
|
272
|
-
the platform's database backup API rather than replacing a live SQLite file directly.
|
package/docs/adapters-remote.md
DELETED
|
@@ -1,291 +0,0 @@
|
|
|
1
|
-
# 🌐 Remote Backend Adapters
|
|
2
|
-
|
|
3
|
-
`local-lite` supports multiple cloud synchronization backends out of the box.
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## 1. Supabase (Postgres + Realtime)
|
|
8
|
-
|
|
9
|
-
The Supabase adapter synchronizes local SQLite tables with Supabase Postgres tables in real time.
|
|
10
|
-
|
|
11
|
-
```bash
|
|
12
|
-
npm install @supabase/supabase-js
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
### 1.1 Postgres Setup (SQL Editor)
|
|
16
|
-
|
|
17
|
-
Run the following SQL in your Supabase SQL Editor to enable timestamp triggers and soft deletes:
|
|
18
|
-
|
|
19
|
-
```sql
|
|
20
|
-
-- Ensure every application table has the soft-delete column expected by local-lite.
|
|
21
|
-
DO $$
|
|
22
|
-
DECLARE
|
|
23
|
-
table_record RECORD;
|
|
24
|
-
BEGIN
|
|
25
|
-
FOR table_record IN
|
|
26
|
-
SELECT table_schema, table_name
|
|
27
|
-
FROM information_schema.tables
|
|
28
|
-
WHERE table_schema = 'public'
|
|
29
|
-
AND table_type = 'BASE TABLE'
|
|
30
|
-
LOOP
|
|
31
|
-
EXECUTE format(
|
|
32
|
-
'ALTER TABLE %I.%I ADD COLUMN IF NOT EXISTS deleted BOOLEAN',
|
|
33
|
-
table_record.table_schema,
|
|
34
|
-
table_record.table_name
|
|
35
|
-
);
|
|
36
|
-
EXECUTE format(
|
|
37
|
-
'UPDATE %I.%I SET deleted = FALSE WHERE deleted IS NULL',
|
|
38
|
-
table_record.table_schema,
|
|
39
|
-
table_record.table_name
|
|
40
|
-
);
|
|
41
|
-
EXECUTE format(
|
|
42
|
-
'ALTER TABLE %I.%I ALTER COLUMN deleted SET DEFAULT FALSE',
|
|
43
|
-
table_record.table_schema,
|
|
44
|
-
table_record.table_name
|
|
45
|
-
);
|
|
46
|
-
EXECUTE format(
|
|
47
|
-
'ALTER TABLE %I.%I ALTER COLUMN deleted SET NOT NULL',
|
|
48
|
-
table_record.table_schema,
|
|
49
|
-
table_record.table_name
|
|
50
|
-
);
|
|
51
|
-
END LOOP;
|
|
52
|
-
END $$;
|
|
53
|
-
|
|
54
|
-
-- 1. Automatic Timestamp Trigger
|
|
55
|
-
CREATE OR REPLACE FUNCTION public.set_sync_updated_at()
|
|
56
|
-
RETURNS TRIGGER AS $$
|
|
57
|
-
BEGIN
|
|
58
|
-
NEW.updated_at = NOW();
|
|
59
|
-
RETURN NEW;
|
|
60
|
-
END;
|
|
61
|
-
$$ LANGUAGE plpgsql;
|
|
62
|
-
|
|
63
|
-
-- 2. Create your table
|
|
64
|
-
CREATE TABLE IF NOT EXISTS public.todos (
|
|
65
|
-
id TEXT PRIMARY KEY,
|
|
66
|
-
title TEXT NOT NULL,
|
|
67
|
-
completed BOOLEAN DEFAULT false,
|
|
68
|
-
deleted BOOLEAN DEFAULT false,
|
|
69
|
-
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
-- 3. Attach trigger
|
|
73
|
-
CREATE TRIGGER tr_todos_updated_at
|
|
74
|
-
BEFORE UPDATE ON public.todos
|
|
75
|
-
FOR EACH ROW EXECUTE FUNCTION public.set_sync_updated_at();
|
|
76
|
-
|
|
77
|
-
-- 4. Enable Supabase Realtime
|
|
78
|
-
ALTER PUBLICATION supabase_realtime ADD TABLE public.todos;
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
### 1.2 Client Configuration
|
|
82
|
-
|
|
83
|
-
```typescript
|
|
84
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
85
|
-
|
|
86
|
-
export const config = defineSyncConfig({
|
|
87
|
-
tables: ['todos'],
|
|
88
|
-
supabase: {
|
|
89
|
-
url: process.env.EXPO_PUBLIC_SUPABASE_URL,
|
|
90
|
-
anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY,
|
|
91
|
-
updatedAtColumn: 'updated_at',
|
|
92
|
-
deletedColumn: 'deleted',
|
|
93
|
-
deletedValue: true,
|
|
94
|
-
},
|
|
95
|
-
});
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
---
|
|
99
|
-
|
|
100
|
-
## 2. Convex (Reactive Cloud Documents)
|
|
101
|
-
|
|
102
|
-
The Convex adapter coordinates with a live Convex backend via batch mutations and delta queries.
|
|
103
|
-
|
|
104
|
-
```bash
|
|
105
|
-
npm install convex
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
### 2.1 Convex Schema (`convex/schema.ts`)
|
|
109
|
-
|
|
110
|
-
```typescript
|
|
111
|
-
// convex/schema.ts
|
|
112
|
-
import { defineSchema, defineTable } from 'convex/server';
|
|
113
|
-
import { v } from 'convex/values';
|
|
114
|
-
|
|
115
|
-
export default defineSchema({
|
|
116
|
-
todos: defineTable({
|
|
117
|
-
id: v.string(),
|
|
118
|
-
title: v.string(),
|
|
119
|
-
completed: v.boolean(),
|
|
120
|
-
deleted: v.boolean(),
|
|
121
|
-
updatedAt: v.number(),
|
|
122
|
-
}).index('by_updatedAt', ['updatedAt']),
|
|
123
|
-
});
|
|
124
|
-
```
|
|
125
|
-
|
|
126
|
-
### 2.2 Convex Sync Functions (`convex/sync.ts`)
|
|
127
|
-
|
|
128
|
-
```typescript
|
|
129
|
-
// convex/sync.ts
|
|
130
|
-
import { mutationGeneric as mutation, queryGeneric as query } from 'convex/server';
|
|
131
|
-
import { v } from 'convex/values';
|
|
132
|
-
|
|
133
|
-
export const pushBatch = mutation({
|
|
134
|
-
args: {
|
|
135
|
-
operations: v.array(
|
|
136
|
-
v.object({
|
|
137
|
-
id: v.string(),
|
|
138
|
-
tableName: v.string(),
|
|
139
|
-
rowId: v.string(),
|
|
140
|
-
operation: v.string(),
|
|
141
|
-
payload: v.any(),
|
|
142
|
-
timestamp: v.number(),
|
|
143
|
-
})
|
|
144
|
-
),
|
|
145
|
-
},
|
|
146
|
-
handler: async (ctx, args) => {
|
|
147
|
-
for (const op of args.operations) {
|
|
148
|
-
const table = op.tableName as 'todos';
|
|
149
|
-
const existing = await ctx.db
|
|
150
|
-
.query(table)
|
|
151
|
-
.filter((q) => q.eq(q.field('id'), op.rowId))
|
|
152
|
-
.first();
|
|
153
|
-
|
|
154
|
-
if (op.operation === 'DELETE') {
|
|
155
|
-
if (existing) {
|
|
156
|
-
await ctx.db.patch(existing._id, { deleted: true, updatedAt: op.timestamp });
|
|
157
|
-
}
|
|
158
|
-
} else {
|
|
159
|
-
const doc = { ...(op.payload || {}), id: op.rowId, deleted: false, updatedAt: op.timestamp };
|
|
160
|
-
if (existing) {
|
|
161
|
-
await ctx.db.patch(existing._id, doc);
|
|
162
|
-
} else {
|
|
163
|
-
await ctx.db.insert(table, doc);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
return true;
|
|
168
|
-
},
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
export const pullDeltas = query({
|
|
172
|
-
args: {
|
|
173
|
-
sinceTimestamp: v.number(),
|
|
174
|
-
tables: v.array(v.string()),
|
|
175
|
-
},
|
|
176
|
-
handler: async (ctx, args) => {
|
|
177
|
-
const results: Record<string, any[]> = {};
|
|
178
|
-
for (const table of args.tables) {
|
|
179
|
-
const rows = await ctx.db
|
|
180
|
-
.query(table as 'todos')
|
|
181
|
-
.withIndex('by_updatedAt', (q) => q.gt('updatedAt', args.sinceTimestamp))
|
|
182
|
-
.collect();
|
|
183
|
-
results[table] = rows;
|
|
184
|
-
}
|
|
185
|
-
return results;
|
|
186
|
-
},
|
|
187
|
-
});
|
|
188
|
-
```
|
|
189
|
-
|
|
190
|
-
### 2.3 Client Configuration
|
|
191
|
-
|
|
192
|
-
```typescript
|
|
193
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
194
|
-
import { ConvexClient } from 'convex/browser';
|
|
195
|
-
|
|
196
|
-
const convexClient = new ConvexClient(process.env.EXPO_PUBLIC_CONVEX_URL!);
|
|
197
|
-
|
|
198
|
-
export const config = defineSyncConfig({
|
|
199
|
-
tables: ['todos'],
|
|
200
|
-
convex: {
|
|
201
|
-
client: convexClient,
|
|
202
|
-
pushMutation: 'sync:pushBatch',
|
|
203
|
-
pullQuery: 'sync:pullDeltas',
|
|
204
|
-
updatedAtColumn: 'updatedAt',
|
|
205
|
-
deletedColumn: 'deleted',
|
|
206
|
-
},
|
|
207
|
-
});
|
|
208
|
-
```
|
|
209
|
-
|
|
210
|
-
---
|
|
211
|
-
|
|
212
|
-
## 3. Firebase / Cloud Firestore
|
|
213
|
-
|
|
214
|
-
Synchronizes local SQLite with Google Cloud Firestore collections.
|
|
215
|
-
|
|
216
|
-
```bash
|
|
217
|
-
npm install firebase # or @react-native-firebase/firestore
|
|
218
|
-
```
|
|
219
|
-
|
|
220
|
-
### Client Configuration
|
|
221
|
-
|
|
222
|
-
```typescript
|
|
223
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
224
|
-
import { initializeApp } from 'firebase/app';
|
|
225
|
-
import { getFirestore } from 'firebase/firestore';
|
|
226
|
-
|
|
227
|
-
const app = initializeApp({
|
|
228
|
-
apiKey: process.env.EXPO_PUBLIC_FIREBASE_API_KEY,
|
|
229
|
-
projectId: process.env.EXPO_PUBLIC_FIREBASE_PROJECT_ID,
|
|
230
|
-
});
|
|
231
|
-
const firestore = getFirestore(app);
|
|
232
|
-
|
|
233
|
-
export const config = defineSyncConfig({
|
|
234
|
-
tables: ['todos'],
|
|
235
|
-
firebase: {
|
|
236
|
-
firestore,
|
|
237
|
-
updatedAtColumn: 'updatedAt',
|
|
238
|
-
deletedColumn: 'deleted',
|
|
239
|
-
},
|
|
240
|
-
});
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
---
|
|
244
|
-
|
|
245
|
-
## 4. In-Memory Simulated Demo Backend
|
|
246
|
-
|
|
247
|
-
For mock testing, automated unit tests, and prototyping when you don't have internet access or cloud credentials:
|
|
248
|
-
|
|
249
|
-
```typescript
|
|
250
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
251
|
-
|
|
252
|
-
export const config = defineSyncConfig({
|
|
253
|
-
tables: ['todos'],
|
|
254
|
-
inMemoryRemote: true, // Simulates remote with 300ms network delay
|
|
255
|
-
});
|
|
256
|
-
```
|
|
257
|
-
|
|
258
|
-
---
|
|
259
|
-
|
|
260
|
-
## 5. Custom Remote Adapters
|
|
261
|
-
|
|
262
|
-
Implement `RemoteDBAdapter` to connect `local-lite` to your own REST, GraphQL, or WebSocket servers:
|
|
263
|
-
|
|
264
|
-
```typescript
|
|
265
|
-
import { RemoteDBAdapter, SyncOperation, DeltaChanges } from 'local-lite';
|
|
266
|
-
|
|
267
|
-
export class MyCustomServerAdapter implements RemoteDBAdapter {
|
|
268
|
-
async pushChanges(operations: SyncOperation[]): Promise<boolean> {
|
|
269
|
-
const response = await fetch('https://api.mybackend.com/sync/push', {
|
|
270
|
-
method: 'POST',
|
|
271
|
-
headers: { 'Content-Type': 'application/json' },
|
|
272
|
-
body: JSON.stringify({ operations }),
|
|
273
|
-
});
|
|
274
|
-
return response.ok;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
async fetchChanges(sinceTimestamp: number): Promise<DeltaChanges> {
|
|
278
|
-
const res = await fetch(`https://api.mybackend.com/sync/pull?since=${sinceTimestamp}`);
|
|
279
|
-
return await res.json();
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
subscribeToLiveChanges(onRemoteChange: (changes: DeltaChanges) => void): () => void {
|
|
283
|
-
const ws = new WebSocket('wss://api.mybackend.com/realtime');
|
|
284
|
-
ws.onmessage = (event) => onRemoteChange(JSON.parse(event.data));
|
|
285
|
-
return () => ws.close();
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
```
|
|
289
|
-
|
|
290
|
-
`subscribeToLiveChanges()` must return a cleanup function even when no listener is
|
|
291
|
-
created; return a no-op function in that case.
|
package/docs/api-keys.md
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
# 🔐 API Keys & Signed Tokens Wrapper
|
|
2
|
-
|
|
3
|
-
`local-lite` provides a zero-dependency **API Key & Signed Token toolkit** for generating, verifying, hashing, and renewing keys and tokens. It does not replace your primary authentication (e.g. Supabase Auth, Google, Microsoft), but provides utilities for issuing developer API keys, tenant scanner keys, mobile session tokens, or signed renewal tokens.
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## ⚡ 1. Generating & Verifying Checksummed API Keys
|
|
8
|
-
|
|
9
|
-
Modern API keys (like GitHub `ghp_...` or Stripe `sk_live_...`) contain embedded checksums so their authenticity and integrity can be verified instantaneously without querying a database.
|
|
10
|
-
|
|
11
|
-
```typescript
|
|
12
|
-
import { generateApiKey, verifyApiKey, verifyApiKeyFormat } from 'local-lite/keys';
|
|
13
|
-
|
|
14
|
-
// 1. Generate an API key
|
|
15
|
-
const { key, keyHash, prefix, display } = generateApiKey({
|
|
16
|
-
prefix: 'prop', // Output: prop_x7A9..._c4f910e2
|
|
17
|
-
byteLength: 24, // 192 bits of cryptographically secure entropy
|
|
18
|
-
withChecksum: true, // Appends a 4-byte checksum
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
console.log('Plaintext Key (show to user once):', key);
|
|
22
|
-
console.log('Key Hash (safe to store in SQLite/Postgres):', keyHash);
|
|
23
|
-
console.log('Display Mask:', display); // e.g. "prop_...10e2"
|
|
24
|
-
|
|
25
|
-
// 2. Instant syntactic & checksum check (no DB required)
|
|
26
|
-
const isFormatValid = verifyApiKeyFormat(incomingKey, 'prop');
|
|
27
|
-
|
|
28
|
-
// 3. Cryptographic timing-safe verification against stored SHA-256 hash
|
|
29
|
-
const isValid = verifyApiKey(incomingKey, storedHash);
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
## ✍️ 2. Signed Tokens & Renewal (HMAC-SHA256)
|
|
35
|
-
|
|
36
|
-
For self-contained tokens that embed data (such as `{ businessId, role }`), expiration dates, and renewal capabilities without needing database lookups:
|
|
37
|
-
|
|
38
|
-
```typescript
|
|
39
|
-
import { createSignedToken, verifySignedToken, renewSignedToken } from 'local-lite/keys';
|
|
40
|
-
|
|
41
|
-
const SECRET = process.env.API_SIGNING_SECRET || 'your-secure-secret';
|
|
42
|
-
|
|
43
|
-
// 1. Create a signed token with expiration
|
|
44
|
-
const token = createSignedToken({
|
|
45
|
-
payload: { businessId: 'biz_123', role: 'admin' },
|
|
46
|
-
secret: SECRET,
|
|
47
|
-
expiresInMs: 7 * 24 * 60 * 60 * 1000, // 7 days
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
// 2. Verify token signature and check expiration
|
|
51
|
-
const verification = verifySignedToken(token, SECRET);
|
|
52
|
-
if (verification.valid) {
|
|
53
|
-
console.log('Authorized Payload:', verification.payload);
|
|
54
|
-
console.log('Expires at:', new Date(verification.expiresAt!).toISOString());
|
|
55
|
-
} else if (verification.expired) {
|
|
56
|
-
console.warn('Token expired at:', verification.expiresAt);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// 3. Renew an existing token (extends expiration with a fresh HMAC signature)
|
|
60
|
-
const renewedToken = renewSignedToken(token, SECRET, {
|
|
61
|
-
extendMs: 7 * 24 * 60 * 60 * 1000,
|
|
62
|
-
});
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
---
|
|
66
|
-
|
|
67
|
-
## 💾 3. SQLite Key Manager (`client.keys.*`)
|
|
68
|
-
|
|
69
|
-
`local-lite` includes an optional SQLite store (`_local_api_keys`) managed directly via `client.keys`:
|
|
70
|
-
|
|
71
|
-
### Creating a Key
|
|
72
|
-
```typescript
|
|
73
|
-
const { key, record } = await client.keys.create({
|
|
74
|
-
name: 'Mobile Property Scanner',
|
|
75
|
-
prefix: 'scan',
|
|
76
|
-
expiresInMs: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
77
|
-
metadata: { businessId: 'biz_99', device: 'iPad Warehouse 1' },
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
// Returns the raw key to show once, while persisting the SHA-256 hash to SQLite
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
### Verifying a Key
|
|
84
|
-
```typescript
|
|
85
|
-
const result = await client.keys.verify(incomingKey);
|
|
86
|
-
|
|
87
|
-
if (result.valid) {
|
|
88
|
-
console.log('Key is active for business:', result.record.metadata.businessId);
|
|
89
|
-
// Automatically stamps record.last_used_at in SQLite
|
|
90
|
-
} else {
|
|
91
|
-
console.error('Key verification failed:', result.status, result.error);
|
|
92
|
-
// status: 'INVALID' | 'EXPIRED' | 'REVOKED' | 'MALFORMED'
|
|
93
|
-
}
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
### Revoking, Listing & Pruning
|
|
97
|
-
```typescript
|
|
98
|
-
// Revoke a compromised or deactivated key
|
|
99
|
-
await client.keys.revoke(keyId);
|
|
100
|
-
|
|
101
|
-
// List active or revoked keys
|
|
102
|
-
const keys = await client.keys.list({ revoked: false });
|
|
103
|
-
|
|
104
|
-
// Prune old revoked keys
|
|
105
|
-
await client.keys.prune({ revokedOlderThanMs: 30 * 24 * 60 * 60 * 1000 });
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
---
|
|
109
|
-
|
|
110
|
-
## 🔒 Security Guarantees
|
|
111
|
-
|
|
112
|
-
* **Timing-Safe Comparison:** Hash and signature comparisons use constant-time operations (`timingSafeEqual`) to prevent side-channel timing attacks.
|
|
113
|
-
* **Plaintext Safety:** Plaintext keys are never stored by `ApiKeyManager`; only SHA-256 digests are written to disk.
|
|
114
|
-
* **Tamper-Evident:** Signed tokens are signed using HMAC-SHA256 (`@noble/hashes`); any payload alteration invalidates the signature immediately.
|