local-lite 0.1.1 โ 0.1.3
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/bin/local-lite.mjs +1 -1
- package/dist/adapters/network/index.js +3 -1
- package/dist/adapters/remote/firestore.js +4 -2
- 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/core/table-manager.js +13 -3
- package/dist/keys/generator.js +12 -3
- package/dist/react/auth.d.ts +21 -0
- package/dist/react/auth.js +121 -0
- package/dist/storage/driver.js +9 -2
- package/dist/storage/expo.js +9 -5
- package/dist/utils/dynamic.js +21 -0
- 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/dist/auth/microsoft.js
CHANGED
|
@@ -9,9 +9,13 @@ const onedrive_js_1 = require("../backups/onedrive.js");
|
|
|
9
9
|
exports.MICROSOFT_GRAPH_ENDPOINT = 'https://graph.microsoft.com/v1.0';
|
|
10
10
|
exports.DEFAULT_MICROSOFT_AUTH_SCOPES = ['openid', 'profile', 'email', 'User.Read'];
|
|
11
11
|
function secureRandomBytes(length) {
|
|
12
|
-
const crypto = globalThis.crypto;
|
|
12
|
+
const crypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
13
13
|
if (!crypto?.getRandomValues) {
|
|
14
|
-
|
|
14
|
+
const fallback = new Uint8Array(length);
|
|
15
|
+
for (let i = 0; i < length; i++) {
|
|
16
|
+
fallback[i] = Math.floor(Math.random() * 256);
|
|
17
|
+
}
|
|
18
|
+
return fallback;
|
|
15
19
|
}
|
|
16
20
|
return crypto.getRandomValues(new Uint8Array(length));
|
|
17
21
|
}
|
|
@@ -317,3 +321,4 @@ class MicrosoftAuthClient {
|
|
|
317
321
|
}
|
|
318
322
|
}
|
|
319
323
|
exports.MicrosoftAuthClient = MicrosoftAuthClient;
|
|
324
|
+
onedrive_js_1.OneDriveBackupClient.AuthClientClass = MicrosoftAuthClient;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { BackupAccessTokenProvider, BackupStorage, CloudBackupClient, CreateDatabaseBackupOptions, ResolvableBackupDatabase } from './operations.js';
|
|
2
2
|
import type { CloudBackupFile } from './cloud-storage.js';
|
|
3
3
|
import type { EncryptedBackupOptions, RestoreEncryptedBackupOptions } from './encryption.js';
|
|
4
|
-
import { MicrosoftAuthClient,
|
|
4
|
+
import type { MicrosoftAuthClient, MicrosoftAuthClientOptions } from '../auth/microsoft.js';
|
|
5
5
|
export declare const MICROSOFT_GRAPH_DRIVE = "https://graph.microsoft.com/v1.0/me/drive";
|
|
6
6
|
export declare class OneDriveBackupStorage implements BackupStorage {
|
|
7
7
|
private readonly getAccessToken;
|
|
@@ -17,6 +17,7 @@ export type OneDriveBackupClientOptions = MicrosoftAuthClientOptions | {
|
|
|
17
17
|
fetch?: typeof fetch;
|
|
18
18
|
};
|
|
19
19
|
export declare class OneDriveBackupClient implements CloudBackupClient {
|
|
20
|
+
static AuthClientClass: (new (options: MicrosoftAuthClientOptions) => MicrosoftAuthClient) | null;
|
|
20
21
|
private readonly storage;
|
|
21
22
|
private readonly authClient;
|
|
22
23
|
private readonly listeners;
|
package/dist/backups/onedrive.js
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.OneDriveBackupClient = exports.OneDriveBackupStorage = exports.MICROSOFT_GRAPH_DRIVE = void 0;
|
|
4
4
|
const operations_js_1 = require("./operations.js");
|
|
5
|
-
const microsoft_js_1 = require("../auth/microsoft.js");
|
|
6
5
|
exports.MICROSOFT_GRAPH_DRIVE = 'https://graph.microsoft.com/v1.0/me/drive';
|
|
7
6
|
const BACKUP_FOLDER = 'backups';
|
|
8
7
|
class OneDriveBackupStorage {
|
|
@@ -90,6 +89,7 @@ class OneDriveBackupStorage {
|
|
|
90
89
|
}
|
|
91
90
|
exports.OneDriveBackupStorage = OneDriveBackupStorage;
|
|
92
91
|
class OneDriveBackupClient {
|
|
92
|
+
static AuthClientClass = null;
|
|
93
93
|
storage;
|
|
94
94
|
authClient;
|
|
95
95
|
listeners = new Set();
|
|
@@ -107,7 +107,11 @@ class OneDriveBackupClient {
|
|
|
107
107
|
'User.Read',
|
|
108
108
|
'Files.ReadWrite.AppFolder',
|
|
109
109
|
];
|
|
110
|
-
|
|
110
|
+
const AuthClass = OneDriveBackupClient.AuthClientClass;
|
|
111
|
+
if (!AuthClass) {
|
|
112
|
+
throw new Error('MicrosoftAuthClient is not registered. Pass an authClient instance in options or ensure local-lite/auth is loaded.');
|
|
113
|
+
}
|
|
114
|
+
this.authClient = new AuthClass({
|
|
111
115
|
...msOptions,
|
|
112
116
|
scopes,
|
|
113
117
|
});
|
package/dist/config/index.js
CHANGED
|
@@ -95,6 +95,7 @@ async function createSyncClient(config) {
|
|
|
95
95
|
syncScope: config.syncScope,
|
|
96
96
|
autoPauseOnBackground: config.autoPauseOnBackground,
|
|
97
97
|
touchUpdatedAt: config.touchUpdatedAt,
|
|
98
|
+
auth: config.auth ?? config.localAuth,
|
|
98
99
|
});
|
|
99
100
|
// 5. Execute Migrations & Auto-initialize
|
|
100
101
|
if (config.autoInitialize !== false) {
|
package/dist/config/types.d.ts
CHANGED
|
@@ -3,7 +3,9 @@ import { RemoteDBAdapter } from '../adapters/remote/index.js';
|
|
|
3
3
|
import { ConflictResolver, ConflictStrategy, NetworkStatusProvider, RetryConfig, SchemaMigration } from '../core/types.js';
|
|
4
4
|
import type { RelationshipDefinition } from '../core/client.js';
|
|
5
5
|
import { SyncLogger, CustomLogger, LogLevel } from '../utils/logger.js';
|
|
6
|
+
import type { LocalAuthEngineOptions } from '../auth/local.js';
|
|
6
7
|
export type { OnDeleteAction, RelationshipDefinition } from '../core/client.js';
|
|
8
|
+
export type { LocalAuthEngineOptions } from '../auth/local.js';
|
|
7
9
|
export interface SupabaseConfigOptions {
|
|
8
10
|
url?: string;
|
|
9
11
|
anonKey?: string;
|
|
@@ -204,4 +206,9 @@ export interface LocalLiteConfig {
|
|
|
204
206
|
* - `false`: disabled
|
|
205
207
|
*/
|
|
206
208
|
touchUpdatedAt?: boolean | string;
|
|
209
|
+
/**
|
|
210
|
+
* Options for the fully local, zero-backend authentication engine (`client.auth`).
|
|
211
|
+
*/
|
|
212
|
+
auth?: LocalAuthEngineOptions;
|
|
213
|
+
localAuth?: LocalAuthEngineOptions;
|
|
207
214
|
}
|
package/dist/core/client.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { SearchManager } from '../search/index.js';
|
|
|
17
17
|
import { BlobStorageManager, type BlobStorageManagerOptions } from '../storage/index.js';
|
|
18
18
|
import { JobScheduler, type JobSchedulerOptions } from '../scheduler/index.js';
|
|
19
19
|
import { SessionManager, type SessionManagerOptions } from '../auth/session.js';
|
|
20
|
+
import { LocalAuthEngine, type LocalAuthEngineOptions } from '../auth/local.js';
|
|
20
21
|
export type OnDeleteAction = 'cascade' | 'restrict' | 'setNull' | 'noAction';
|
|
21
22
|
export interface RelationshipDefinition {
|
|
22
23
|
/** Table containing the referencing rows. */
|
|
@@ -65,6 +66,8 @@ export interface LocalFirstClientConfig {
|
|
|
65
66
|
storage?: BlobStorageManagerOptions;
|
|
66
67
|
scheduler?: JobSchedulerOptions;
|
|
67
68
|
session?: SessionManagerOptions;
|
|
69
|
+
localAuth?: LocalAuthEngineOptions;
|
|
70
|
+
auth?: LocalAuthEngineOptions;
|
|
68
71
|
}
|
|
69
72
|
export declare class TransactionalClient {
|
|
70
73
|
private parent;
|
|
@@ -122,6 +125,7 @@ export declare class LocalFirstClient {
|
|
|
122
125
|
readonly storage: BlobStorageManager;
|
|
123
126
|
readonly scheduler: JobScheduler;
|
|
124
127
|
readonly session: SessionManager;
|
|
128
|
+
readonly auth: LocalAuthEngine;
|
|
125
129
|
private primaryKey;
|
|
126
130
|
private schemaMigrations;
|
|
127
131
|
private autoStart;
|
package/dist/core/client.js
CHANGED
|
@@ -21,6 +21,7 @@ const index_js_5 = require("../search/index.js");
|
|
|
21
21
|
const index_js_6 = require("../storage/index.js");
|
|
22
22
|
const index_js_7 = require("../scheduler/index.js");
|
|
23
23
|
const session_js_1 = require("../auth/session.js");
|
|
24
|
+
const local_js_1 = require("../auth/local.js");
|
|
24
25
|
function normalizeSchemaMigrations(migrations) {
|
|
25
26
|
if (!Array.isArray(migrations)) {
|
|
26
27
|
throw new TypeError('schemaMigrations must be an array.');
|
|
@@ -246,6 +247,7 @@ class LocalFirstClient {
|
|
|
246
247
|
storage;
|
|
247
248
|
scheduler;
|
|
248
249
|
session;
|
|
250
|
+
auth;
|
|
249
251
|
primaryKey;
|
|
250
252
|
schemaMigrations;
|
|
251
253
|
autoStart;
|
|
@@ -307,7 +309,8 @@ class LocalFirstClient {
|
|
|
307
309
|
'_local_api_keys',
|
|
308
310
|
'_local_actions',
|
|
309
311
|
'_local_sessions',
|
|
310
|
-
'
|
|
312
|
+
'_local_users',
|
|
313
|
+
'_local_user_tokens',
|
|
311
314
|
]);
|
|
312
315
|
const actionNetwork = config.actions?.network ?? config.network;
|
|
313
316
|
this.keys = new index_js_3.ApiKeyManager(this.db, config.keys);
|
|
@@ -334,6 +337,7 @@ class LocalFirstClient {
|
|
|
334
337
|
network: config.network,
|
|
335
338
|
...config.session,
|
|
336
339
|
});
|
|
340
|
+
this.auth = new local_js_1.LocalAuthEngine(this.db, this.session, this.events, config.auth || config.localAuth);
|
|
337
341
|
this.actions = new index_js_2.ActionManager(this.db, this.events, () => Promise.resolve(actionNetwork ? actionNetwork.isOnline() : true), {
|
|
338
342
|
network: actionNetwork,
|
|
339
343
|
...config.actions,
|
|
@@ -502,6 +506,7 @@ class LocalFirstClient {
|
|
|
502
506
|
await this.storage.initialize();
|
|
503
507
|
await this.scheduler.initialize();
|
|
504
508
|
await this.session.initialize();
|
|
509
|
+
await this.auth.initialize();
|
|
505
510
|
await this.applySchemaMigrations();
|
|
506
511
|
if (this.autoSchema && this.tables.length > 0) {
|
|
507
512
|
for (const table of this.tables) {
|
|
@@ -50,10 +50,20 @@ class TableManager {
|
|
|
50
50
|
const keys = Object.keys(rowData);
|
|
51
51
|
if (keys.length === 0)
|
|
52
52
|
return;
|
|
53
|
-
// Use atomic SQLite UPSERT (INSERT ... ON CONFLICT DO UPDATE) for
|
|
54
|
-
//
|
|
55
|
-
// completely eliminating the redundant SELECT 1 pre-check on every mutation!
|
|
53
|
+
// Use atomic SQLite UPSERT (INSERT ... ON CONFLICT DO UPDATE) for INSERT,
|
|
54
|
+
// and direct UPDATE when updating an existing row so omitted NOT NULL columns do not fail.
|
|
56
55
|
const updateKeys = keys.filter((k) => k !== primaryKey);
|
|
56
|
+
if (operation === 'UPDATE' && updateKeys.length > 0) {
|
|
57
|
+
const existing = await TableManager.fetchRow(tx, tableName, rowId, primaryKey, options);
|
|
58
|
+
if (existing) {
|
|
59
|
+
const setClause = updateKeys
|
|
60
|
+
.map((k) => `${(0, sql_js_1.escapeIdentifier)(k)} = ?`)
|
|
61
|
+
.join(', ');
|
|
62
|
+
const setValues = [...updateKeys.map((k) => rowData[k]), rowId];
|
|
63
|
+
await tx.execute(`UPDATE ${safeTable} SET ${setClause} WHERE ${safePk} = ?`, setValues);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
57
67
|
const cols = keys.map((k) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
|
|
58
68
|
const placeholders = keys.map(() => '?').join(', ');
|
|
59
69
|
const values = keys.map((k) => rowData[k]);
|
package/dist/keys/generator.js
CHANGED
|
@@ -15,9 +15,14 @@ const BASE62_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs
|
|
|
15
15
|
* Generates cryptographically secure random bytes across Web, Expo/React Native, and Node.js.
|
|
16
16
|
*/
|
|
17
17
|
function getRandomBytes(length) {
|
|
18
|
-
const cryptoObj = globalThis.crypto;
|
|
18
|
+
const cryptoObj = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
19
19
|
if (cryptoObj?.getRandomValues) {
|
|
20
|
-
|
|
20
|
+
try {
|
|
21
|
+
return cryptoObj.getRandomValues(new Uint8Array(length));
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// Fallback below
|
|
25
|
+
}
|
|
21
26
|
}
|
|
22
27
|
try {
|
|
23
28
|
// Dynamic fallback for Node.js environments without globalThis.crypto
|
|
@@ -31,7 +36,11 @@ function getRandomBytes(length) {
|
|
|
31
36
|
catch {
|
|
32
37
|
// Fallback ignored
|
|
33
38
|
}
|
|
34
|
-
|
|
39
|
+
const fallback = new Uint8Array(length);
|
|
40
|
+
for (let i = 0; i < length; i++) {
|
|
41
|
+
fallback[i] = Math.floor(Math.random() * 256);
|
|
42
|
+
}
|
|
43
|
+
return fallback;
|
|
35
44
|
}
|
|
36
45
|
/**
|
|
37
46
|
* Encodes raw bytes into a base62 string.
|
package/dist/react/auth.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import type { GoogleAuthClient, GoogleUser } from '../auth/google.js';
|
|
|
2
2
|
import type { MicrosoftAuthClient, MicrosoftUser } from '../auth/microsoft.js';
|
|
3
3
|
import type { GitHubAuthClient, GitHubUser } from '../auth/github.js';
|
|
4
4
|
import type { AppleAuthClient, AppleUser, AppleNativeCredential } from '../auth/apple.js';
|
|
5
|
+
import type { LocalAuthEngine, LocalUser, SignUpOptions, SignInOptions, SignInResult } from '../auth/local.js';
|
|
6
|
+
import type { SessionRecord } from '../auth/session.js';
|
|
5
7
|
export interface UseGoogleAuthResult {
|
|
6
8
|
user: GoogleUser | null;
|
|
7
9
|
isSignedIn: boolean;
|
|
@@ -42,3 +44,22 @@ export interface UseAppleAuthResult {
|
|
|
42
44
|
refetchUser: () => Promise<AppleUser | null>;
|
|
43
45
|
}
|
|
44
46
|
export declare function useAppleAuth(client: AppleAuthClient | null | undefined): UseAppleAuthResult;
|
|
47
|
+
export interface UseLocalAuthResult<TMetadata = any> {
|
|
48
|
+
user: LocalUser<TMetadata> | null;
|
|
49
|
+
session: SessionRecord<LocalUser<TMetadata>> | null;
|
|
50
|
+
isSignedIn: boolean;
|
|
51
|
+
loading: boolean;
|
|
52
|
+
error: Error | null;
|
|
53
|
+
signIn: (identifier: string, password: string, options?: Omit<SignInOptions, 'identifier' | 'password'>) => Promise<SignInResult<TMetadata>>;
|
|
54
|
+
signUp: (options: SignUpOptions<TMetadata>) => Promise<SignInResult<TMetadata>>;
|
|
55
|
+
signOut: () => Promise<void>;
|
|
56
|
+
refetchUser: () => Promise<LocalUser<TMetadata> | null>;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Reactive React hook for the fully local, zero-backend authentication engine.
|
|
60
|
+
* Automatically synchronizes with local user state and offline sessions in SQLite.
|
|
61
|
+
*
|
|
62
|
+
* Example:
|
|
63
|
+
* const { user, isSignedIn, signIn, signUp, signOut } = useLocalAuth(client.auth);
|
|
64
|
+
*/
|
|
65
|
+
export declare function useLocalAuth<TMetadata = any>(engine: LocalAuthEngine | null | undefined): UseLocalAuthResult<TMetadata>;
|
package/dist/react/auth.js
CHANGED
|
@@ -4,6 +4,7 @@ exports.useGoogleAuth = useGoogleAuth;
|
|
|
4
4
|
exports.useMicrosoftAuth = useMicrosoftAuth;
|
|
5
5
|
exports.useGitHubAuth = useGitHubAuth;
|
|
6
6
|
exports.useAppleAuth = useAppleAuth;
|
|
7
|
+
exports.useLocalAuth = useLocalAuth;
|
|
7
8
|
const react_1 = require("react");
|
|
8
9
|
function useGoogleAuth(client) {
|
|
9
10
|
const [user, setUser] = (0, react_1.useState)(null);
|
|
@@ -361,3 +362,123 @@ function useAppleAuth(client) {
|
|
|
361
362
|
refetchUser,
|
|
362
363
|
};
|
|
363
364
|
}
|
|
365
|
+
/**
|
|
366
|
+
* Reactive React hook for the fully local, zero-backend authentication engine.
|
|
367
|
+
* Automatically synchronizes with local user state and offline sessions in SQLite.
|
|
368
|
+
*
|
|
369
|
+
* Example:
|
|
370
|
+
* const { user, isSignedIn, signIn, signUp, signOut } = useLocalAuth(client.auth);
|
|
371
|
+
*/
|
|
372
|
+
function useLocalAuth(engine) {
|
|
373
|
+
const [user, setUser] = (0, react_1.useState)(null);
|
|
374
|
+
const [session, setSession] = (0, react_1.useState)(null);
|
|
375
|
+
const [loading, setLoading] = (0, react_1.useState)(true);
|
|
376
|
+
const [error, setError] = (0, react_1.useState)(null);
|
|
377
|
+
const refreshState = (0, react_1.useCallback)(async () => {
|
|
378
|
+
if (!engine) {
|
|
379
|
+
setUser(null);
|
|
380
|
+
setSession(null);
|
|
381
|
+
setLoading(false);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
try {
|
|
385
|
+
const sessionMgr = engine.getSessionManager();
|
|
386
|
+
const currentSession = await sessionMgr.getActiveSession();
|
|
387
|
+
setSession(currentSession);
|
|
388
|
+
const currentUser = await engine.getCurrentUser();
|
|
389
|
+
setUser(currentUser);
|
|
390
|
+
setError(null);
|
|
391
|
+
}
|
|
392
|
+
catch (err) {
|
|
393
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
394
|
+
}
|
|
395
|
+
finally {
|
|
396
|
+
setLoading(false);
|
|
397
|
+
}
|
|
398
|
+
}, [engine]);
|
|
399
|
+
(0, react_1.useEffect)(() => {
|
|
400
|
+
refreshState();
|
|
401
|
+
if (!engine)
|
|
402
|
+
return;
|
|
403
|
+
const unsub = engine.onAuthStateChange(() => {
|
|
404
|
+
refreshState();
|
|
405
|
+
});
|
|
406
|
+
return () => {
|
|
407
|
+
unsub();
|
|
408
|
+
};
|
|
409
|
+
}, [engine, refreshState]);
|
|
410
|
+
const signIn = (0, react_1.useCallback)(async (identifier, password, options) => {
|
|
411
|
+
if (!engine)
|
|
412
|
+
throw new Error('LocalAuthEngine is not initialized.');
|
|
413
|
+
setError(null);
|
|
414
|
+
setLoading(true);
|
|
415
|
+
try {
|
|
416
|
+
const result = await engine.signIn({
|
|
417
|
+
identifier,
|
|
418
|
+
password,
|
|
419
|
+
...options,
|
|
420
|
+
});
|
|
421
|
+
setUser(result.user);
|
|
422
|
+
setSession(result.session ?? null);
|
|
423
|
+
return result;
|
|
424
|
+
}
|
|
425
|
+
catch (err) {
|
|
426
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
427
|
+
setError(e);
|
|
428
|
+
throw e;
|
|
429
|
+
}
|
|
430
|
+
finally {
|
|
431
|
+
setLoading(false);
|
|
432
|
+
}
|
|
433
|
+
}, [engine]);
|
|
434
|
+
const signUp = (0, react_1.useCallback)(async (options) => {
|
|
435
|
+
if (!engine)
|
|
436
|
+
throw new Error('LocalAuthEngine is not initialized.');
|
|
437
|
+
setError(null);
|
|
438
|
+
setLoading(true);
|
|
439
|
+
try {
|
|
440
|
+
const result = await engine.signUp(options);
|
|
441
|
+
setUser(result.user);
|
|
442
|
+
setSession(result.session ?? null);
|
|
443
|
+
return result;
|
|
444
|
+
}
|
|
445
|
+
catch (err) {
|
|
446
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
447
|
+
setError(e);
|
|
448
|
+
throw e;
|
|
449
|
+
}
|
|
450
|
+
finally {
|
|
451
|
+
setLoading(false);
|
|
452
|
+
}
|
|
453
|
+
}, [engine]);
|
|
454
|
+
const signOut = (0, react_1.useCallback)(async () => {
|
|
455
|
+
if (!engine)
|
|
456
|
+
return;
|
|
457
|
+
setError(null);
|
|
458
|
+
setLoading(true);
|
|
459
|
+
try {
|
|
460
|
+
await engine.signOut();
|
|
461
|
+
setUser(null);
|
|
462
|
+
setSession(null);
|
|
463
|
+
}
|
|
464
|
+
catch (err) {
|
|
465
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
466
|
+
setError(e);
|
|
467
|
+
throw e;
|
|
468
|
+
}
|
|
469
|
+
finally {
|
|
470
|
+
setLoading(false);
|
|
471
|
+
}
|
|
472
|
+
}, [engine]);
|
|
473
|
+
return {
|
|
474
|
+
user,
|
|
475
|
+
session,
|
|
476
|
+
isSignedIn: Boolean(user),
|
|
477
|
+
loading,
|
|
478
|
+
error,
|
|
479
|
+
signIn,
|
|
480
|
+
signUp,
|
|
481
|
+
signOut,
|
|
482
|
+
refetchUser: refreshState,
|
|
483
|
+
};
|
|
484
|
+
}
|
package/dist/storage/driver.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.NodeFileDriver = exports.MemoryFileDriver = void 0;
|
|
4
|
+
const dynamic_js_1 = require("../utils/dynamic.js");
|
|
5
|
+
const NODE_FS_PROMISES_PKG = ['node:fs', 'promises'].join('/');
|
|
6
|
+
const NODE_PATH_PKG = ['node', 'path'].join(':');
|
|
4
7
|
/**
|
|
5
8
|
* Universal in-memory driver (ideal for tests, memory caches, and browser storage fallback).
|
|
6
9
|
*/
|
|
@@ -35,8 +38,12 @@ class NodeFileDriver {
|
|
|
35
38
|
}
|
|
36
39
|
async getFs() {
|
|
37
40
|
try {
|
|
38
|
-
const fs =
|
|
39
|
-
|
|
41
|
+
const fs = (0, dynamic_js_1.safeDynamicRequire)(NODE_FS_PROMISES_PKG) ??
|
|
42
|
+
(await (0, dynamic_js_1.safeDynamicImport)(NODE_FS_PROMISES_PKG));
|
|
43
|
+
const path = (0, dynamic_js_1.safeDynamicRequire)(NODE_PATH_PKG) ?? (await (0, dynamic_js_1.safeDynamicImport)(NODE_PATH_PKG));
|
|
44
|
+
if (!fs || !path) {
|
|
45
|
+
throw new Error('Node fs/path unavailable');
|
|
46
|
+
}
|
|
40
47
|
return { fs, path };
|
|
41
48
|
}
|
|
42
49
|
catch {
|
package/dist/storage/expo.js
CHANGED
|
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.ExpoFileDriver = void 0;
|
|
4
4
|
exports.bytesToBase64 = bytesToBase64;
|
|
5
5
|
exports.base64ToBytes = base64ToBytes;
|
|
6
|
+
const dynamic_js_1 = require("../utils/dynamic.js");
|
|
7
|
+
const EXPO_FILE_SYSTEM_PKG = ['expo', 'file', 'system'].join('-');
|
|
6
8
|
/**
|
|
7
9
|
* Universal binary <-> base64 utilities compatible with Node, Browser, and React Native (Hermes).
|
|
8
10
|
*/
|
|
@@ -54,11 +56,13 @@ class ExpoFileDriver {
|
|
|
54
56
|
async resolveClasses() {
|
|
55
57
|
if (!this.FileClass || !this.DirectoryClass || !this.PathsObj) {
|
|
56
58
|
try {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
59
|
+
const mod = (0, dynamic_js_1.safeDynamicRequire)(EXPO_FILE_SYSTEM_PKG) ??
|
|
60
|
+
(await (0, dynamic_js_1.safeDynamicImport)(EXPO_FILE_SYSTEM_PKG));
|
|
61
|
+
if (mod) {
|
|
62
|
+
this.FileClass = this.FileClass ?? mod.File;
|
|
63
|
+
this.DirectoryClass = this.DirectoryClass ?? mod.Directory;
|
|
64
|
+
this.PathsObj = this.PathsObj ?? mod.Paths;
|
|
65
|
+
}
|
|
62
66
|
}
|
|
63
67
|
catch (error) {
|
|
64
68
|
if (!this.FileClass) {
|
package/dist/utils/dynamic.js
CHANGED
|
@@ -8,6 +8,20 @@ exports.safeDynamicImport = safeDynamicImport;
|
|
|
8
8
|
*/
|
|
9
9
|
function safeDynamicRequire(pkgName) {
|
|
10
10
|
try {
|
|
11
|
+
if (pkgName === 'react-native') {
|
|
12
|
+
return require('react-native');
|
|
13
|
+
}
|
|
14
|
+
if (pkgName === 'expo-sqlite') {
|
|
15
|
+
return require('expo-sqlite');
|
|
16
|
+
}
|
|
17
|
+
if (pkgName === 'expo-file-system') {
|
|
18
|
+
return require('expo-file-system');
|
|
19
|
+
}
|
|
20
|
+
// In Metro bundler (__r), calling require(variableString) triggers Metro's
|
|
21
|
+
// unknownModuleError console.error before throwing. Skip non-literal require in Metro.
|
|
22
|
+
if (typeof globalThis !== 'undefined' && typeof globalThis.__r === 'function') {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
11
25
|
const req = typeof __non_webpack_require__ !== 'undefined'
|
|
12
26
|
? __non_webpack_require__
|
|
13
27
|
: typeof require === 'function'
|
|
@@ -21,6 +35,13 @@ function safeDynamicRequire(pkgName) {
|
|
|
21
35
|
}
|
|
22
36
|
async function safeDynamicImport(pkgName) {
|
|
23
37
|
try {
|
|
38
|
+
const syncMod = safeDynamicRequire(pkgName);
|
|
39
|
+
if (syncMod !== undefined) {
|
|
40
|
+
return syncMod;
|
|
41
|
+
}
|
|
42
|
+
if (typeof globalThis !== 'undefined' && typeof globalThis.__r === 'function') {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
24
45
|
// Metro's AST worker rejects `import(dynamicVariable)` with "Invalid call at line ...: import(...)".
|
|
25
46
|
// Evaluating via new Function bypasses the bundler AST parser entirely while working in Node/browser.
|
|
26
47
|
const dynamicImport = new Function('specifier', 'return import(specifier);');
|
package/dist/utils/uuid.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { v4 as uuidv4 } from 'uuid';
|
|
2
1
|
/**
|
|
3
|
-
* Generates an RFC4122
|
|
4
|
-
*
|
|
2
|
+
* Generates an RFC4122 version 4 compliant UUID.
|
|
3
|
+
* Works natively across Web, React Native (Hermes), Node.js, and Expo without bare global lookups.
|
|
5
4
|
*/
|
|
6
5
|
export declare function generateUUID(): string;
|
|
7
|
-
export
|
|
6
|
+
export declare const uuidv4: typeof generateUUID;
|
package/dist/utils/uuid.js
CHANGED
|
@@ -2,17 +2,47 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.uuidv4 = void 0;
|
|
4
4
|
exports.generateUUID = generateUUID;
|
|
5
|
-
const uuid_1 = require("uuid");
|
|
6
|
-
Object.defineProperty(exports, "uuidv4", { enumerable: true, get: function () { return uuid_1.v4; } });
|
|
7
|
-
// Detect once at module load โ avoids 3 typeof checks per UUID call
|
|
8
|
-
const nativeRandomUUID = typeof globalThis !== 'undefined' &&
|
|
9
|
-
typeof globalThis.crypto?.randomUUID === 'function'
|
|
10
|
-
? () => globalThis.crypto.randomUUID()
|
|
11
|
-
: null;
|
|
12
5
|
/**
|
|
13
|
-
* Generates an RFC4122
|
|
14
|
-
*
|
|
6
|
+
* Generates an RFC4122 version 4 compliant UUID.
|
|
7
|
+
* Works natively across Web, React Native (Hermes), Node.js, and Expo without bare global lookups.
|
|
15
8
|
*/
|
|
16
9
|
function generateUUID() {
|
|
17
|
-
|
|
10
|
+
const gCrypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
11
|
+
if (typeof gCrypto?.randomUUID === 'function') {
|
|
12
|
+
try {
|
|
13
|
+
return gCrypto.randomUUID();
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// Fallback to byte-based generation
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const bytes = new Uint8Array(16);
|
|
20
|
+
if (typeof gCrypto?.getRandomValues === 'function') {
|
|
21
|
+
try {
|
|
22
|
+
gCrypto.getRandomValues(bytes);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
for (let i = 0; i < 16; i++) {
|
|
26
|
+
bytes[i] = Math.floor(Math.random() * 256);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
for (let i = 0; i < 16; i++) {
|
|
32
|
+
bytes[i] = Math.floor(Math.random() * 256);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// RFC4122 ยง4.4: Set version to 0100 (v4) and variant to 10xx (RFC4122)
|
|
36
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
37
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
38
|
+
let hex = '';
|
|
39
|
+
for (let i = 0; i < 16; i++) {
|
|
40
|
+
if (i === 4 || i === 6 || i === 8 || i === 10) {
|
|
41
|
+
hex += '-';
|
|
42
|
+
}
|
|
43
|
+
const b = bytes[i];
|
|
44
|
+
hex += (b < 16 ? '0' : '') + b.toString(16);
|
|
45
|
+
}
|
|
46
|
+
return hex;
|
|
18
47
|
}
|
|
48
|
+
exports.uuidv4 = generateUUID;
|
package/docs/auth.md
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
# ๐ Authentication (Google, Microsoft / OneDrive, GitHub & Apple)
|
|
1
|
+
# ๐ Authentication (Local SQLite, Google, Microsoft / OneDrive, GitHub & Apple)
|
|
2
2
|
|
|
3
|
-
`local-lite` provides zero-backend, PKCE-secured authentication clients and React hooks out of the box for the four most popular identity providers
|
|
3
|
+
`local-lite` provides zero-backend, PKCE-secured authentication clients and React hooks out of the box for the four most popular identity providers, plus a **fully local SQLite authentication engine**:
|
|
4
|
+
* **Local SQLite Auth Engine** (`LocalAuthEngine`, `useLocalAuth`) โ 100% offline, PBKDF2-SHA512 password crypto, account lockout, tokens, and users table
|
|
4
5
|
* **Google** (`GoogleAuthClient`, `useGoogleAuth`)
|
|
5
6
|
* **Microsoft / OneDrive** (`MicrosoftAuthClient`, `OneDriveAuthClient`, `useMicrosoftAuth`, `useOneDriveAuth`)
|
|
6
7
|
* **GitHub** (`GitHubAuthClient`, `useGitHubAuth`)
|
|
@@ -257,3 +258,85 @@ const msTokenStore = createMicrosoftAuthTokenStore(storage);
|
|
|
257
258
|
const ghTokenStore = createGitHubAuthTokenStore(storage);
|
|
258
259
|
const appleTokenStore = createAppleAuthTokenStore(storage);
|
|
259
260
|
```
|
|
261
|
+
|
|
262
|
+
---
|
|
263
|
+
|
|
264
|
+
## ๐ 5. Fully Local Authentication Engine (`auth/local`)
|
|
265
|
+
|
|
266
|
+
For standalone offline-first apps, local-only modes, or self-contained credentials without third-party OAuth, `local-lite` provides a zero-backend **LocalAuthEngine** storing credentials directly in SQLite.
|
|
267
|
+
|
|
268
|
+
```typescript
|
|
269
|
+
import { LocalAuthEngine } from 'local-lite/auth/local';
|
|
270
|
+
// or access client.auth directly on LocalFirstClient:
|
|
271
|
+
import { useLocalAuth } from 'local-lite/react';
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
### Features & Security:
|
|
275
|
+
* **๐ก๏ธ High-Level Crypto Credentials:** PBKDF2 with SHA-512 key derivation, 100,000 iterations by default, and distinct cryptographically secure 16-byte random salts.
|
|
276
|
+
* **โฑ๏ธ Constant-Time Verification:** Password comparison uses timing-safe XOR operations to defeat side-channel timing attacks.
|
|
277
|
+
* **๐ซ Brute-Force & Lockout Protection:** Automatically tracks consecutive failed login attempts and locks accounts temporarily (default: 5 failed attempts locks for 15 minutes).
|
|
278
|
+
* **๐ Single-Use Password Reset Tokens:** Cryptographically secure 32-byte tokens stored only as SHA-256 hashes with configurable expiry.
|
|
279
|
+
* **๐ค SQLite `_local_users` Table:** Stores sanitized user profiles, usernames, case-insensitive emails, roles, JSON metadata, and status (`active`, `suspended`, `locked`).
|
|
280
|
+
* **๐ฑ Integrated Offline Sessions:** Automatically creates and persists sessions in `SessionManager` so users stay logged in offline.
|
|
281
|
+
|
|
282
|
+
### Basic Usage:
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
// Standalone or via client.auth:
|
|
286
|
+
const { user, session } = await client.auth.signUp({
|
|
287
|
+
email: 'alice@example.com',
|
|
288
|
+
username: 'alice',
|
|
289
|
+
password: 'SuperSecretPassword123!',
|
|
290
|
+
displayName: 'Alice Wonderland',
|
|
291
|
+
metadata: { role: 'admin' },
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
// Sign In with email or username:
|
|
295
|
+
const { user, session } = await client.auth.signIn({
|
|
296
|
+
identifier: 'alice@example.com', // or username 'alice'
|
|
297
|
+
password: 'SuperSecretPassword123!',
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
// Password Change:
|
|
301
|
+
await client.auth.changePassword({
|
|
302
|
+
userId: user.id,
|
|
303
|
+
oldPassword: 'SuperSecretPassword123!',
|
|
304
|
+
newPassword: 'BrandNewPassword456!',
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
// Password Reset Flow:
|
|
308
|
+
const { token } = await client.auth.createPasswordResetToken('alice@example.com');
|
|
309
|
+
await client.auth.resetPasswordWithToken(token, 'BrandNewPassword456!');
|
|
310
|
+
|
|
311
|
+
// Sign Out:
|
|
312
|
+
await client.auth.signOut();
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
### React Hook (`useLocalAuth`):
|
|
316
|
+
|
|
317
|
+
```tsx
|
|
318
|
+
import { useLocalAuth } from 'local-lite/react';
|
|
319
|
+
|
|
320
|
+
export function AuthScreen({ client }) {
|
|
321
|
+
const { user, isSignedIn, loading, signIn, signUp, signOut } = useLocalAuth(client.auth);
|
|
322
|
+
|
|
323
|
+
if (loading) return <Text>Loading user state...</Text>;
|
|
324
|
+
|
|
325
|
+
if (isSignedIn) {
|
|
326
|
+
return (
|
|
327
|
+
<View>
|
|
328
|
+
<Text>Welcome back, {user.displayName || user.email}!</Text>
|
|
329
|
+
<Button title="Sign Out" onPress={() => signOut()} />
|
|
330
|
+
</View>
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return (
|
|
335
|
+
<LoginForm
|
|
336
|
+
onLogin={(email, password) => signIn(email, password)}
|
|
337
|
+
onRegister={(email, password) => signUp({ email, password })}
|
|
338
|
+
/>
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
```
|
|
342
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-lite",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
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",
|
|
@@ -67,6 +67,11 @@
|
|
|
67
67
|
"import": "./dist/auth/index.js",
|
|
68
68
|
"default": "./dist/auth/index.js"
|
|
69
69
|
},
|
|
70
|
+
"./auth/local": {
|
|
71
|
+
"types": "./dist/auth/local/index.d.ts",
|
|
72
|
+
"import": "./dist/auth/local/index.js",
|
|
73
|
+
"default": "./dist/auth/local/index.js"
|
|
74
|
+
},
|
|
70
75
|
"./backups": {
|
|
71
76
|
"types": "./dist/backups/index.d.ts",
|
|
72
77
|
"import": "./dist/backups/index.js",
|