local-lite 0.2.1 → 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/local.d.ts +33 -1
- package/dist/auth/local.js +94 -13
- 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/README.md
CHANGED
|
@@ -95,6 +95,7 @@ For an application-level upgrade checklist or AI-assisted code review, see the
|
|
|
95
95
|
The package ships [Agent Skills](./skills) that AI coding assistants can load:
|
|
96
96
|
* `local-lite-setup`: Multi-platform setup (Expo, Web, Node) and client initialization.
|
|
97
97
|
* `local-lite-auth`: Zero-backend SQLite authentication, PBKDF2 crypto, lockout, reset tokens, and OAuth.
|
|
98
|
+
* `local-lite-server`: Framework-neutral REST API routing, route params, middleware pipelines, and single fetch() dispatcher.
|
|
98
99
|
* `local-lite-backups`: Cloud backups (OneDrive, Google Drive), AES-256-GCM database encryption, and restore.
|
|
99
100
|
* `local-lite-schema`: Declarative cascading deletions (`onDelete`), append-only migrations, and FTS5 search.
|
|
100
101
|
* `local-lite-storage`: Blob and file management, ExpoFileDriver, and cloud storage bucket sync.
|
|
@@ -104,8 +105,10 @@ The package ships [Agent Skills](./skills) that AI coding assistants can load:
|
|
|
104
105
|
* `local-lite-upgrade`: Migration checklist and breaking change reviews across version upgrades.
|
|
105
106
|
|
|
106
107
|
```bash
|
|
107
|
-
npx local-lite install-skills
|
|
108
|
-
npx local-lite install-skills --target claude
|
|
108
|
+
npx local-lite install-skills # Copilot: .github/skills
|
|
109
|
+
npx local-lite install-skills --target claude # Claude Code: .claude/skills
|
|
110
|
+
npx local-lite install-skills --target antigravity # Antigravity / Gemini: .gemini/skills
|
|
111
|
+
npx local-lite install-skills --target cursor # Cursor: .cursor/skills
|
|
109
112
|
npx local-lite install-skills --dir path/to/dir --force
|
|
110
113
|
```
|
|
111
114
|
|
package/bin/local-lite.mjs
CHANGED
|
@@ -1,62 +1,66 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { cp, mkdir, readdir } from 'node:fs/promises';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { fileURLToPath } from 'node:url';
|
|
5
|
-
|
|
6
|
-
const skillsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills');
|
|
7
|
-
const targets = {
|
|
8
|
-
copilot: '.github/skills',
|
|
9
|
-
claude: '.claude/skills',
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
2
|
+
import { cp, mkdir, readdir } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const skillsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills');
|
|
7
|
+
const targets = {
|
|
8
|
+
copilot: '.github/skills',
|
|
9
|
+
claude: '.claude/skills',
|
|
10
|
+
antigravity: '.gemini/skills',
|
|
11
|
+
gemini: '.gemini/skills',
|
|
12
|
+
cursor: '.cursor/skills',
|
|
13
|
+
agent: '.agent/skills',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const usage = `Usage: local-lite install-skills [--target copilot|claude|antigravity|cursor|agent] [--dir <path>] [--force]
|
|
17
|
+
|
|
18
|
+
Copies the bundled AI skills into your project.
|
|
19
|
+
--target copilot (default, .github/skills), claude (.claude/skills), antigravity (.gemini/skills), cursor (.cursor/skills), agent (.agent/skills)
|
|
20
|
+
--dir custom destination directory (overrides --target)
|
|
21
|
+
--force overwrite existing skill files`;
|
|
22
|
+
|
|
23
|
+
function parseArgs(argv) {
|
|
24
|
+
const options = { target: 'copilot', dir: undefined, force: false };
|
|
25
|
+
for (let i = 0; i < argv.length; i++) {
|
|
26
|
+
const arg = argv[i];
|
|
27
|
+
if (arg === '--force') options.force = true;
|
|
28
|
+
else if (arg === '--target') options.target = argv[++i];
|
|
29
|
+
else if (arg === '--dir') {
|
|
30
|
+
options.dir = argv[++i];
|
|
31
|
+
if (!options.dir) throw new Error('--dir requires a path.');
|
|
32
|
+
} else throw new Error(`Unknown option: ${arg}`);
|
|
33
|
+
}
|
|
34
|
+
if (!options.dir && !targets[options.target]) {
|
|
35
|
+
throw new Error(`Unknown target "${options.target}". Supported: ${Object.keys(targets).join(', ')}.`);
|
|
36
|
+
}
|
|
37
|
+
return options;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function installSkills(options) {
|
|
41
|
+
const destination = path.resolve(process.cwd(), options.dir ?? targets[options.target]);
|
|
42
|
+
await mkdir(destination, { recursive: true });
|
|
43
|
+
const entries = await readdir(skillsRoot, { withFileTypes: true });
|
|
44
|
+
for (const entry of entries.filter((item) => item.isDirectory())) {
|
|
45
|
+
await cp(path.join(skillsRoot, entry.name), path.join(destination, entry.name), {
|
|
46
|
+
recursive: true,
|
|
47
|
+
force: options.force,
|
|
48
|
+
errorOnExist: false,
|
|
49
|
+
});
|
|
50
|
+
console.log(`Installed ${entry.name} -> ${path.join(destination, entry.name)}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
55
|
+
try {
|
|
56
|
+
if (command === 'install-skills') {
|
|
57
|
+
await installSkills(parseArgs(rest));
|
|
58
|
+
} else {
|
|
59
|
+
console.log(usage);
|
|
60
|
+
process.exitCode = command && command !== '--help' && command !== '-h' ? 1 : 0;
|
|
61
|
+
}
|
|
62
|
+
} catch (error) {
|
|
63
|
+
console.error(error instanceof Error ? error.message : error);
|
|
64
|
+
console.error(usage);
|
|
65
|
+
process.exitCode = 1;
|
|
66
|
+
}
|
package/dist/auth/local.d.ts
CHANGED
|
@@ -90,7 +90,19 @@ export interface LocalAuthEngineOptions {
|
|
|
90
90
|
* Shared SessionManager instance or options to configure internal SessionManager.
|
|
91
91
|
*/
|
|
92
92
|
session?: SessionManager | SessionManagerOptions;
|
|
93
|
+
/**
|
|
94
|
+
* Optional remote authentication handler to exchange local sessions for remote sync provider tokens.
|
|
95
|
+
*/
|
|
96
|
+
remoteAuthHandler?: RemoteAuthHandler;
|
|
97
|
+
}
|
|
98
|
+
export interface RemoteAuthExchangeContext<TMetadata = any> {
|
|
99
|
+
user: LocalUser<TMetadata>;
|
|
100
|
+
session: SessionRecord<LocalUser<TMetadata>>;
|
|
93
101
|
}
|
|
102
|
+
export type RemoteAuthHandler<TMetadata = any> = (context: RemoteAuthExchangeContext<TMetadata>) => Promise<{
|
|
103
|
+
token: string;
|
|
104
|
+
[key: string]: any;
|
|
105
|
+
} | null>;
|
|
94
106
|
export interface SignUpOptions<TMetadata = Record<string, any>> {
|
|
95
107
|
id?: string;
|
|
96
108
|
email: string;
|
|
@@ -198,7 +210,27 @@ export declare class LocalAuthEngine {
|
|
|
198
210
|
private minPasswordLength;
|
|
199
211
|
private customPasswordValidator?;
|
|
200
212
|
private sessionManager;
|
|
201
|
-
|
|
213
|
+
private remoteAuthHandler?;
|
|
214
|
+
constructor(db: DBExecutable, sessionOrManager?: SessionManager | SessionManagerOptions | LocalAuthEngineOptions, events?: EventEmitter | undefined, options?: LocalAuthEngineOptions);
|
|
215
|
+
/**
|
|
216
|
+
* Registers a pluggable remote authentication exchange handler.
|
|
217
|
+
*/
|
|
218
|
+
setRemoteAuthHandler(handler: RemoteAuthHandler): void;
|
|
219
|
+
/**
|
|
220
|
+
* Gets the configured remote authentication exchange handler.
|
|
221
|
+
*/
|
|
222
|
+
getRemoteAuthHandler(): RemoteAuthHandler | undefined;
|
|
223
|
+
/**
|
|
224
|
+
* Triggers token exchange with the registered remote sync provider for the active session.
|
|
225
|
+
*/
|
|
226
|
+
exchangeRemoteAuth(): Promise<{
|
|
227
|
+
token: string;
|
|
228
|
+
[key: string]: any;
|
|
229
|
+
} | null>;
|
|
230
|
+
/**
|
|
231
|
+
* Retrieves the cached remote sync authentication token from the active session.
|
|
232
|
+
*/
|
|
233
|
+
getRemoteAuthToken(): Promise<string | null>;
|
|
202
234
|
/**
|
|
203
235
|
* Retrieves the underlying SessionManager instance.
|
|
204
236
|
*/
|
package/dist/auth/local.js
CHANGED
|
@@ -10,6 +10,7 @@ exports.mapStoredUserRow = mapStoredUserRow;
|
|
|
10
10
|
const pbkdf2_js_1 = require("@noble/hashes/pbkdf2.js");
|
|
11
11
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
12
12
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
13
|
+
const event_emitter_js_1 = require("../reactive/event-emitter.js");
|
|
13
14
|
const uuid_js_1 = require("../utils/uuid.js");
|
|
14
15
|
const sql_js_1 = require("../utils/sql.js");
|
|
15
16
|
const generator_js_1 = require("../keys/generator.js");
|
|
@@ -184,27 +185,83 @@ class LocalAuthEngine {
|
|
|
184
185
|
minPasswordLength;
|
|
185
186
|
customPasswordValidator;
|
|
186
187
|
sessionManager;
|
|
188
|
+
remoteAuthHandler;
|
|
187
189
|
constructor(db, sessionOrManager, events, options = {}) {
|
|
188
190
|
this.db = db;
|
|
189
191
|
this.events = events;
|
|
190
|
-
|
|
191
|
-
|
|
192
|
+
let resolvedOptions = options;
|
|
193
|
+
let resolvedSession = sessionOrManager instanceof session_js_1.SessionManager ? sessionOrManager : undefined;
|
|
194
|
+
let resolvedEvents = events;
|
|
195
|
+
if (sessionOrManager && !(sessionOrManager instanceof session_js_1.SessionManager)) {
|
|
196
|
+
if ('usersTable' in sessionOrManager ||
|
|
197
|
+
'iterations' in sessionOrManager ||
|
|
198
|
+
'remoteAuthHandler' in sessionOrManager ||
|
|
199
|
+
'maxFailedAttempts' in sessionOrManager) {
|
|
200
|
+
resolvedOptions = sessionOrManager;
|
|
201
|
+
resolvedSession = sessionOrManager.session;
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
resolvedSession = sessionOrManager;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
this.events = resolvedEvents || new event_emitter_js_1.EventEmitter();
|
|
208
|
+
this.usersTable = resolvedOptions.usersTable || exports.DEFAULT_USERS_TABLE;
|
|
209
|
+
this.tokensTable = resolvedOptions.tokensTable || exports.DEFAULT_USER_TOKENS_TABLE;
|
|
192
210
|
this.sqlUsersTable = (0, sql_js_1.escapeIdentifier)(this.usersTable);
|
|
193
211
|
this.sqlTokensTable = (0, sql_js_1.escapeIdentifier)(this.tokensTable);
|
|
194
|
-
this.algorithm =
|
|
195
|
-
this.iterations =
|
|
196
|
-
this.saltBytes =
|
|
197
|
-
this.maxFailedAttempts =
|
|
198
|
-
this.lockoutDurationMs =
|
|
199
|
-
this.resetTokenExpiryMs =
|
|
200
|
-
this.minPasswordLength =
|
|
201
|
-
this.customPasswordValidator =
|
|
202
|
-
|
|
203
|
-
|
|
212
|
+
this.algorithm = resolvedOptions.algorithm || exports.DEFAULT_PASSWORD_ALGORITHM;
|
|
213
|
+
this.iterations = resolvedOptions.iterations || exports.DEFAULT_PASSWORD_ITERATIONS;
|
|
214
|
+
this.saltBytes = resolvedOptions.saltBytes || exports.DEFAULT_SALT_BYTES;
|
|
215
|
+
this.maxFailedAttempts = resolvedOptions.maxFailedAttempts ?? exports.DEFAULT_LOCKOUT_ATTEMPTS;
|
|
216
|
+
this.lockoutDurationMs = resolvedOptions.lockoutDurationMs ?? exports.DEFAULT_LOCKOUT_DURATION_MS;
|
|
217
|
+
this.resetTokenExpiryMs = resolvedOptions.resetTokenExpiryMs ?? exports.DEFAULT_RESET_TOKEN_EXPIRY_MS;
|
|
218
|
+
this.minPasswordLength = resolvedOptions.minPasswordLength ?? exports.DEFAULT_MIN_PASSWORD_LENGTH;
|
|
219
|
+
this.customPasswordValidator = resolvedOptions.validatePassword;
|
|
220
|
+
this.remoteAuthHandler = resolvedOptions.remoteAuthHandler;
|
|
221
|
+
if (resolvedSession instanceof session_js_1.SessionManager) {
|
|
222
|
+
this.sessionManager = resolvedSession;
|
|
204
223
|
}
|
|
205
224
|
else {
|
|
206
|
-
this.sessionManager = new session_js_1.SessionManager(this.db, this.events,
|
|
225
|
+
this.sessionManager = new session_js_1.SessionManager(this.db, this.events, resolvedSession);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Registers a pluggable remote authentication exchange handler.
|
|
230
|
+
*/
|
|
231
|
+
setRemoteAuthHandler(handler) {
|
|
232
|
+
this.remoteAuthHandler = handler;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Gets the configured remote authentication exchange handler.
|
|
236
|
+
*/
|
|
237
|
+
getRemoteAuthHandler() {
|
|
238
|
+
return this.remoteAuthHandler;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Triggers token exchange with the registered remote sync provider for the active session.
|
|
242
|
+
*/
|
|
243
|
+
async exchangeRemoteAuth() {
|
|
244
|
+
if (!this.remoteAuthHandler)
|
|
245
|
+
return null;
|
|
246
|
+
const session = await this.sessionManager.getActiveSession();
|
|
247
|
+
if (!session || !session.userId)
|
|
248
|
+
return null;
|
|
249
|
+
const user = await this.getUserById(session.userId);
|
|
250
|
+
if (!user)
|
|
251
|
+
return null;
|
|
252
|
+
const result = await this.remoteAuthHandler({ user, session });
|
|
253
|
+
if (result && result.token) {
|
|
254
|
+
await this.sessionManager.updateTokens({ token: result.token });
|
|
255
|
+
session.token = result.token;
|
|
207
256
|
}
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Retrieves the cached remote sync authentication token from the active session.
|
|
261
|
+
*/
|
|
262
|
+
async getRemoteAuthToken() {
|
|
263
|
+
const session = await this.sessionManager.getActiveSession();
|
|
264
|
+
return session?.token || null;
|
|
208
265
|
}
|
|
209
266
|
/**
|
|
210
267
|
* Retrieves the underlying SessionManager instance.
|
|
@@ -341,6 +398,18 @@ class LocalAuthEngine {
|
|
|
341
398
|
offlineDurationMs: options.offlineDurationMs,
|
|
342
399
|
setActive: true,
|
|
343
400
|
});
|
|
401
|
+
if (this.remoteAuthHandler && session) {
|
|
402
|
+
try {
|
|
403
|
+
const remoteRes = await this.remoteAuthHandler({ user, session });
|
|
404
|
+
if (remoteRes && remoteRes.token) {
|
|
405
|
+
await this.sessionManager.updateTokens({ token: remoteRes.token });
|
|
406
|
+
session.token = remoteRes.token;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
// Non-fatal if offline
|
|
411
|
+
}
|
|
412
|
+
}
|
|
344
413
|
}
|
|
345
414
|
this.events?.emit(this.usersTable, { operation: 'SIGN_UP', user });
|
|
346
415
|
return { user, session };
|
|
@@ -426,6 +495,18 @@ class LocalAuthEngine {
|
|
|
426
495
|
offlineDurationMs: options.offlineDurationMs,
|
|
427
496
|
setActive: true,
|
|
428
497
|
});
|
|
498
|
+
if (this.remoteAuthHandler && session) {
|
|
499
|
+
try {
|
|
500
|
+
const remoteRes = await this.remoteAuthHandler({ user, session });
|
|
501
|
+
if (remoteRes && remoteRes.token) {
|
|
502
|
+
await this.sessionManager.updateTokens({ token: remoteRes.token });
|
|
503
|
+
session.token = remoteRes.token;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
// Non-fatal if offline
|
|
508
|
+
}
|
|
509
|
+
}
|
|
429
510
|
}
|
|
430
511
|
this.events?.emit(this.usersTable, { operation: 'SIGN_IN', user, session });
|
|
431
512
|
return { user, session };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-lite",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Never let a lost connection break a promise. Local-first sync that faithfully keeps data safe until you're back online.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -11,7 +11,6 @@
|
|
|
11
11
|
"files": [
|
|
12
12
|
"bin",
|
|
13
13
|
"dist",
|
|
14
|
-
"docs",
|
|
15
14
|
"skills",
|
|
16
15
|
"README.md",
|
|
17
16
|
"LICENSE"
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
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.
|
|
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, remoteAuthHandler JWT exchange, UnifiedAuthManager multi-provider linking, or integrating OAuth providers (Google, Microsoft, GitHub, Apple) and offline sessions.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# local-lite Authentication
|
|
7
7
|
|
|
8
|
-
Comprehensive guide for implementing zero-backend local SQLite authentication and OAuth integrations in `local-lite`.
|
|
8
|
+
Comprehensive guide for implementing zero-backend local SQLite authentication, multi-provider identity unification, and OAuth integrations in `local-lite`.
|
|
9
9
|
|
|
10
10
|
---
|
|
11
11
|
|
|
@@ -14,11 +14,13 @@ Comprehensive guide for implementing zero-backend local SQLite authentication an
|
|
|
14
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
15
|
|
|
16
16
|
### Features
|
|
17
|
-
* **PBKDF2-SHA256 Cryptography**: Fast, unboxed 32-bit integer arithmetic optimized for mobile (Hermes) and hardware-accelerated WebCrypto on Web.
|
|
17
|
+
* **PBKDF2-SHA256 Cryptography**: Fast, unboxed 32-bit integer arithmetic optimized for mobile (Hermes) and hardware-accelerated WebCrypto on Web. Seamless auto-migration of legacy `PBKDF2-SHA512` hashes upon successful sign-in.
|
|
18
18
|
* **Cryptographic Salting**: 16-byte (128-bit) secure random salt per user to prevent rainbow table attacks.
|
|
19
19
|
* **Timing-Attack Protection**: Constant-time byte comparisons (`timingSafeEqual`) and dummy verification for non-existent accounts.
|
|
20
20
|
* **Brute-Force Lockout**: Automatically locks accounts after consecutive failed attempts for a configurable duration.
|
|
21
21
|
* **Single-Use Reset Tokens**: 32-byte high-entropy tokens with SHA-256 storage and automated expiration.
|
|
22
|
+
* **Pluggable Remote Auth Exchange**: `remoteAuthHandler` automatically exchanges local credentials with your backend to retrieve and cache remote JWTs.
|
|
23
|
+
* **User Status Lifecycle**: Active, locked, or suspended accounts (`status: 'active' | 'locked' | 'suspended'`). Suspended accounts are immediately rejected on sign-in.
|
|
22
24
|
* **Offline Sessions**: Integrated with `SessionManager` for persistent multi-device or single-device offline session lifecycles.
|
|
23
25
|
|
|
24
26
|
---
|
|
@@ -38,10 +40,11 @@ export const syncConfig = defineSyncConfig({
|
|
|
38
40
|
usersTable: '_local_users',
|
|
39
41
|
tokensTable: '_local_user_tokens',
|
|
40
42
|
|
|
41
|
-
// Password requirements & validation
|
|
43
|
+
// Password requirements & custom validation (returns boolean or custom error string)
|
|
42
44
|
minPasswordLength: 8,
|
|
43
45
|
validatePassword: (password: string) => {
|
|
44
46
|
if (!/[0-9]/.test(password)) return 'Password must include at least one number.';
|
|
47
|
+
if (!/[A-Z]/.test(password)) return 'Password must include at least one uppercase letter.';
|
|
45
48
|
return true;
|
|
46
49
|
},
|
|
47
50
|
|
|
@@ -55,6 +58,17 @@ export const syncConfig = defineSyncConfig({
|
|
|
55
58
|
// Tuning (defaults: 'PBKDF2-SHA256' with 1,000 rounds)
|
|
56
59
|
algorithm: 'PBKDF2-SHA256',
|
|
57
60
|
iterations: 1_000,
|
|
61
|
+
|
|
62
|
+
// Optional remote auth token exchange (e.g. swap local login for backend JWT)
|
|
63
|
+
remoteAuthHandler: async ({ user, session }) => {
|
|
64
|
+
const res = await fetch('https://api.example.com/auth/sync-token', {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers: { 'Content-Type': 'application/json' },
|
|
67
|
+
body: JSON.stringify({ userId: user.id, email: user.email }),
|
|
68
|
+
});
|
|
69
|
+
const data = await res.json();
|
|
70
|
+
return { token: data.token };
|
|
71
|
+
},
|
|
58
72
|
},
|
|
59
73
|
});
|
|
60
74
|
```
|
|
@@ -130,7 +144,7 @@ export function AuthScreen() {
|
|
|
130
144
|
|
|
131
145
|
---
|
|
132
146
|
|
|
133
|
-
## 4. Password Management &
|
|
147
|
+
## 4. Password Management & Administrative Controls
|
|
134
148
|
|
|
135
149
|
### Changing Passwords (User Authenticated)
|
|
136
150
|
```typescript
|
|
@@ -153,37 +167,63 @@ await client.auth.resetPasswordWithToken(token, 'NewStrongPassword789!');
|
|
|
153
167
|
// The token is permanently invalidated in SQLite and the account is unlocked.
|
|
154
168
|
```
|
|
155
169
|
|
|
170
|
+
### Administrative User Controls
|
|
171
|
+
```typescript
|
|
172
|
+
// Suspend an abusive or compromised account
|
|
173
|
+
await client.auth.updateUser(userId, { status: 'suspended' });
|
|
174
|
+
|
|
175
|
+
// Manually unlock an account
|
|
176
|
+
await client.auth.unlockAccount(userId);
|
|
177
|
+
|
|
178
|
+
// Delete user and cascade clear tokens
|
|
179
|
+
await client.auth.deleteUser(userId);
|
|
180
|
+
```
|
|
181
|
+
|
|
156
182
|
---
|
|
157
183
|
|
|
158
|
-
## 5.
|
|
184
|
+
## 5. Multi-Provider Identity Unification (`UnifiedAuthManager`)
|
|
159
185
|
|
|
160
|
-
|
|
186
|
+
When supporting both local authentication and third-party OAuth providers, `UnifiedAuthManager` generates a canonical, deterministic `userId` linking accounts by verified email:
|
|
161
187
|
|
|
162
|
-
### Google OAuth
|
|
163
188
|
```typescript
|
|
164
|
-
import {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
189
|
+
import {
|
|
190
|
+
UnifiedAuthManager,
|
|
191
|
+
GoogleAuthClient,
|
|
192
|
+
GitHubAuthClient,
|
|
193
|
+
SessionManager,
|
|
194
|
+
} from 'local-lite/auth';
|
|
195
|
+
|
|
196
|
+
const sessionManager = new SessionManager(client.getAdapter());
|
|
197
|
+
await sessionManager.initialize();
|
|
198
|
+
|
|
199
|
+
export const unifiedAuth = new UnifiedAuthManager({
|
|
200
|
+
google: googleClient,
|
|
201
|
+
github: githubClient,
|
|
202
|
+
local: client.auth,
|
|
203
|
+
sessionManager,
|
|
204
|
+
unifyByEmail: true, // Derives canonical UUIDv5 by normalized verified email
|
|
172
205
|
});
|
|
173
|
-
```
|
|
174
206
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
207
|
+
// Sign in with any provider - user sessions and local tables link seamlessly
|
|
208
|
+
const user = await unifiedAuth.signIn('google');
|
|
209
|
+
console.log('Unified Canonical User ID:', user.userId);
|
|
178
210
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
scopes: ['openid', 'profile', 'User.Read', 'Files.ReadWrite.AppFolder'],
|
|
183
|
-
authorize: async (req) => { /* invoke browser */ },
|
|
211
|
+
// Listen to unified state changes
|
|
212
|
+
const unsubscribe = unifiedAuth.onAuthStateChange((user) => {
|
|
213
|
+
console.log('Active User:', user?.email);
|
|
184
214
|
});
|
|
215
|
+
|
|
216
|
+
// Cleanup when unmounting
|
|
217
|
+
unifiedAuth.destroy();
|
|
185
218
|
```
|
|
186
219
|
|
|
187
|
-
|
|
188
|
-
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
## 6. Standalone OAuth Providers
|
|
223
|
+
|
|
224
|
+
`local-lite/auth` includes standalone PKCE OAuth clients with matching React hooks:
|
|
189
225
|
|
|
226
|
+
* **Google**: `GoogleAuthClient` / `useGoogleAuth`
|
|
227
|
+
* **Microsoft & OneDrive**: `MicrosoftAuthClient` / `OneDriveAuthClient` / `useMicrosoftAuth`
|
|
228
|
+
* **GitHub**: `GitHubAuthClient` / `useGitHubAuth`
|
|
229
|
+
* **Apple**: `AppleAuthClient` / `useAppleAuth`
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-server
|
|
3
|
+
description: Configure and implement framework-neutral REST API routing and dispatching with local-lite/server. Use when setting up server endpoints (defineServerConfig, createServer), declaring route parameters, implementing middleware pipelines, managing HTTP methods (GET, POST, PUT, DELETE, OPTIONS), 405 Method Not Allowed handling, or dispatching single fetch() requests in Edge, Node, Next.js, or Expo Router API routes.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Server API Routing
|
|
7
|
+
|
|
8
|
+
Guide for building framework-neutral REST API handlers, route parameters, middleware pipelines, and request dispatchers using `local-lite/server`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Overview
|
|
13
|
+
|
|
14
|
+
`local-lite/server` provides a lightweight, framework-agnostic HTTP routing layer using standard Web `Request` and `Response` objects. It is designed for:
|
|
15
|
+
* **Expo Router API Routes** (`app/api/...index+api.ts`)
|
|
16
|
+
* **Next.js App Router Route Handlers** (`app/api/.../route.ts`)
|
|
17
|
+
* **Cloudflare Workers / Edge / Node.js** standalone HTTP servers
|
|
18
|
+
* **Integration Tests** using single-call `server.fetch(request)` dispatchers
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 2. Defining Server Configuration (`defineServerConfig`)
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
// src/server/api.ts
|
|
26
|
+
import { defineServerConfig, createServer } from 'local-lite/server';
|
|
27
|
+
|
|
28
|
+
interface AppServerServices {
|
|
29
|
+
apiKey: string;
|
|
30
|
+
db: any;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const config = defineServerConfig<AppServerServices>({
|
|
34
|
+
config: {
|
|
35
|
+
apiKey: process.env.API_SECRET_KEY!,
|
|
36
|
+
db: myBackendDbClient,
|
|
37
|
+
},
|
|
38
|
+
// Middleware executes sequentially in declaration order
|
|
39
|
+
middleware: [
|
|
40
|
+
async (ctx, next) => {
|
|
41
|
+
const authHeader = ctx.request.headers.get('Authorization');
|
|
42
|
+
if (!authHeader) {
|
|
43
|
+
return Response.json({ error: 'Unauthorized' }, { status: 401 });
|
|
44
|
+
}
|
|
45
|
+
return await next();
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
endpoints: {
|
|
49
|
+
'/api/tasks': {
|
|
50
|
+
GET: async (ctx) => {
|
|
51
|
+
const tasks = await ctx.config.db.query('SELECT * FROM tasks');
|
|
52
|
+
return Response.json({ tasks });
|
|
53
|
+
},
|
|
54
|
+
POST: async (ctx) => {
|
|
55
|
+
const body = await ctx.request.json();
|
|
56
|
+
const created = await ctx.config.db.insert('tasks', body);
|
|
57
|
+
return Response.json(created, { status: 201 });
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
'/api/tasks/:taskId': {
|
|
61
|
+
GET: async (ctx) => {
|
|
62
|
+
const task = await ctx.config.db.getById('tasks', ctx.params.taskId);
|
|
63
|
+
if (!task) {
|
|
64
|
+
return Response.json({ error: 'Task not found' }, { status: 404 });
|
|
65
|
+
}
|
|
66
|
+
return Response.json(task);
|
|
67
|
+
},
|
|
68
|
+
DELETE: async (ctx) => {
|
|
69
|
+
await ctx.config.db.delete('tasks', ctx.params.taskId);
|
|
70
|
+
return Response.json({ success: true });
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
onError(error, context) {
|
|
75
|
+
// Report internal server errors safely to telemetry without leaking stack trace to clients
|
|
76
|
+
console.error(`[Server Error] ${context.path}:`, error);
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
export const apiServer = createServer(config);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 3. Mounting in Framework Route Handlers
|
|
86
|
+
|
|
87
|
+
### In Expo Router (`app/api/tasks+api.ts`):
|
|
88
|
+
```typescript
|
|
89
|
+
import { apiServer } from '@/server/api';
|
|
90
|
+
|
|
91
|
+
export const GET = apiServer.handler('/api/tasks', 'GET');
|
|
92
|
+
export const POST = apiServer.handler('/api/tasks', 'POST');
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### In Dynamic Expo Router Routes (`app/api/tasks/[taskId]+api.ts`):
|
|
96
|
+
```typescript
|
|
97
|
+
import { apiServer } from '@/server/api';
|
|
98
|
+
|
|
99
|
+
export const GET = apiServer.handler('/api/tasks/:taskId', 'GET');
|
|
100
|
+
export const DELETE = apiServer.handler('/api/tasks/:taskId', 'DELETE');
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## 4. Single `fetch()` Dispatcher
|
|
106
|
+
|
|
107
|
+
For platforms mounting a single catch-all handler (Cloudflare Workers, Hono, Node.js HTTP server):
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
import { apiServer } from './api';
|
|
111
|
+
|
|
112
|
+
export default {
|
|
113
|
+
async fetch(request: Request): Promise<Response> {
|
|
114
|
+
return await apiServer.fetch(request);
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## 5. Built-in Behaviors
|
|
122
|
+
|
|
123
|
+
* **Path Matching & Parameters**: Segments prefixed with `:` (e.g. `:taskId`) are automatically extracted and URL-decoded into `ctx.params`.
|
|
124
|
+
* **Method Not Allowed (405)**: If a route exists for `GET` but receives a `DELETE`, it automatically returns status `405` with an RFC-compliant `Allow: GET` header.
|
|
125
|
+
* **Not Found (404)**: Unmatched paths return a standardized `{ error: 'Not Found' }` with status `404`.
|
|
126
|
+
* **Safe Error Handling (500)**: Unhandled errors in middleware or endpoints trigger `onError` server-side and return `{ error: 'Internal Server Error' }` without exposing internal implementation details.
|
|
127
|
+
|
package/docs/.nojekyll
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
# Disable Jekyll processing on GitHub Pages
|