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/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/dist/auth/microsoft.d.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
+
import { type AuthUser } from './identity.js';
|
|
1
2
|
import { OneDriveBackupStorage, OneDriveBackupClient, type OneDriveBackupClientOptions } from '../backups/onedrive.js';
|
|
2
3
|
export declare const MICROSOFT_GRAPH_ENDPOINT = "https://graph.microsoft.com/v1.0";
|
|
3
4
|
export declare const DEFAULT_MICROSOFT_AUTH_SCOPES: string[];
|
|
4
|
-
export interface MicrosoftUser {
|
|
5
|
-
|
|
6
|
-
email: string;
|
|
7
|
-
name: string;
|
|
5
|
+
export interface MicrosoftUser extends AuthUser {
|
|
6
|
+
provider: 'microsoft';
|
|
8
7
|
givenName?: string;
|
|
9
8
|
familyName?: string;
|
|
10
|
-
picture?: string;
|
|
11
9
|
userPrincipalName?: string;
|
|
12
10
|
}
|
|
13
11
|
export interface MicrosoftAuthTokens {
|
package/dist/auth/microsoft.js
CHANGED
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.MicrosoftAuthClient = exports.DEFAULT_MICROSOFT_AUTH_SCOPES = exports.MICROSOFT_GRAPH_ENDPOINT = void 0;
|
|
4
4
|
exports.createInMemoryMicrosoftTokenStore = createInMemoryMicrosoftTokenStore;
|
|
5
5
|
exports.createMicrosoftAuthTokenStore = createMicrosoftAuthTokenStore;
|
|
6
|
+
const identity_js_1 = require("./identity.js");
|
|
6
7
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
7
8
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
8
9
|
const onedrive_js_1 = require("../backups/onedrive.js");
|
|
@@ -299,14 +300,26 @@ class MicrosoftAuthClient {
|
|
|
299
300
|
throw new Error(`Failed to fetch Microsoft user profile (${res.status}).`);
|
|
300
301
|
}
|
|
301
302
|
const raw = (await res.json());
|
|
302
|
-
const email = raw.mail || raw.userPrincipalName ||
|
|
303
|
+
const email = (raw.mail || raw.userPrincipalName || '').trim().toLowerCase();
|
|
304
|
+
const sub = String(raw.id || raw.sub || 'microsoft_user');
|
|
305
|
+
const id = (0, identity_js_1.resolveUnifiedUserId)({ id: sub, email, emailVerified: true }, 'microsoft');
|
|
306
|
+
const name = raw.displayName || email || 'Microsoft User';
|
|
303
307
|
return {
|
|
304
|
-
id
|
|
308
|
+
id,
|
|
309
|
+
userId: id,
|
|
305
310
|
email,
|
|
306
|
-
|
|
311
|
+
emailVerified: true,
|
|
312
|
+
name,
|
|
313
|
+
displayName: name,
|
|
314
|
+
avatarUrl: null,
|
|
315
|
+
picture: null,
|
|
316
|
+
provider: 'microsoft',
|
|
317
|
+
providerAccountId: sub,
|
|
307
318
|
givenName: raw.givenName,
|
|
308
319
|
familyName: raw.surname,
|
|
309
320
|
userPrincipalName: raw.userPrincipalName,
|
|
321
|
+
rawProfile: raw,
|
|
322
|
+
createdAt: Date.now(),
|
|
310
323
|
};
|
|
311
324
|
}
|
|
312
325
|
createOneDriveBackupStorage() {
|
package/dist/auth/session.d.ts
CHANGED
|
@@ -75,6 +75,10 @@ export declare class SessionManager {
|
|
|
75
75
|
* Retrieves the authenticated user profile object, or null if signed out.
|
|
76
76
|
*/
|
|
77
77
|
getUser<TUser = any>(): Promise<TUser | null>;
|
|
78
|
+
/**
|
|
79
|
+
* Retrieves a session record by its canonical userId.
|
|
80
|
+
*/
|
|
81
|
+
getSessionByUserId<TUser = any>(userId: string): Promise<SessionRecord<TUser> | null>;
|
|
78
82
|
/**
|
|
79
83
|
* Updates last active timestamp.
|
|
80
84
|
*/
|
package/dist/auth/session.js
CHANGED
|
@@ -84,7 +84,16 @@ class SessionManager {
|
|
|
84
84
|
* Creates or updates a user session, persisting it to local SQLite so it remains available offline.
|
|
85
85
|
*/
|
|
86
86
|
async createSession(options) {
|
|
87
|
-
|
|
87
|
+
let id = options.id;
|
|
88
|
+
if (!id) {
|
|
89
|
+
const existing = await this.db.execute(`SELECT id FROM ${this.sqlTableName} WHERE user_id = ? LIMIT 1;`, [options.userId]);
|
|
90
|
+
if (existing && existing.length > 0) {
|
|
91
|
+
id = String(existing[0].id);
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
id = `sess_${(0, uuid_js_1.generateUUID)()}`;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
88
97
|
const now = Date.now();
|
|
89
98
|
const offlineDuration = options.offlineDurationMs !== undefined
|
|
90
99
|
? options.offlineDurationMs
|
|
@@ -179,6 +188,15 @@ class SessionManager {
|
|
|
179
188
|
const session = await this.getActiveSession();
|
|
180
189
|
return session ? session.user : null;
|
|
181
190
|
}
|
|
191
|
+
/**
|
|
192
|
+
* Retrieves a session record by its canonical userId.
|
|
193
|
+
*/
|
|
194
|
+
async getSessionByUserId(userId) {
|
|
195
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlTableName} WHERE user_id = ? LIMIT 1;`, [userId]);
|
|
196
|
+
if (!rows || rows.length === 0)
|
|
197
|
+
return null;
|
|
198
|
+
return mapSessionRow(rows[0]);
|
|
199
|
+
}
|
|
182
200
|
/**
|
|
183
201
|
* Updates last active timestamp.
|
|
184
202
|
*/
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { GoogleAuthClient } from './google.js';
|
|
2
|
+
import { GitHubAuthClient } from './github.js';
|
|
3
|
+
import { MicrosoftAuthClient } from './microsoft.js';
|
|
4
|
+
import { AppleAuthClient } from './apple.js';
|
|
5
|
+
import { LocalAuthEngine } from './local.js';
|
|
6
|
+
import { SessionManager, SessionRecord } from './session.js';
|
|
7
|
+
import { SupportedAuthProvider, UnifiedAuthUser } from './identity.js';
|
|
8
|
+
export interface UnifiedAuthConfig {
|
|
9
|
+
google?: GoogleAuthClient;
|
|
10
|
+
github?: GitHubAuthClient;
|
|
11
|
+
microsoft?: MicrosoftAuthClient;
|
|
12
|
+
apple?: AppleAuthClient;
|
|
13
|
+
local?: LocalAuthEngine;
|
|
14
|
+
sessionManager?: SessionManager;
|
|
15
|
+
/**
|
|
16
|
+
* Whether to unify user identity across providers by verified email.
|
|
17
|
+
* Default: true
|
|
18
|
+
*/
|
|
19
|
+
unifyByEmail?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Custom UUIDv5 namespace for deriving email-based user IDs.
|
|
22
|
+
* Default: DEFAULT_UNIFIED_EMAIL_NAMESPACE ('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
|
|
23
|
+
*/
|
|
24
|
+
emailNamespace?: string;
|
|
25
|
+
}
|
|
26
|
+
export type AuthStateChangeListener = (user: UnifiedAuthUser | null) => void;
|
|
27
|
+
/**
|
|
28
|
+
* High-level orchestrator that unifies multiple OAuth providers (Google, GitHub,
|
|
29
|
+
* Microsoft, Apple) and local auth into a single consistent user identity model.
|
|
30
|
+
*/
|
|
31
|
+
export declare class UnifiedAuthManager {
|
|
32
|
+
private google?;
|
|
33
|
+
private github?;
|
|
34
|
+
private microsoft?;
|
|
35
|
+
private apple?;
|
|
36
|
+
private local?;
|
|
37
|
+
private sessionManager?;
|
|
38
|
+
private unifyByEmail;
|
|
39
|
+
private emailNamespace?;
|
|
40
|
+
private listeners;
|
|
41
|
+
private unsubscribers;
|
|
42
|
+
constructor(config: UnifiedAuthConfig);
|
|
43
|
+
private bindProviderListeners;
|
|
44
|
+
private notify;
|
|
45
|
+
/**
|
|
46
|
+
* Subscribes to global unified authentication state changes.
|
|
47
|
+
*/
|
|
48
|
+
onAuthStateChange(listener: AuthStateChangeListener): () => void;
|
|
49
|
+
/**
|
|
50
|
+
* Authenticates using the specified provider and automatically establishes a unified session.
|
|
51
|
+
*/
|
|
52
|
+
signIn(provider: SupportedAuthProvider, credentials?: any): Promise<UnifiedAuthUser | null>;
|
|
53
|
+
/**
|
|
54
|
+
* Retrieves the currently authenticated unified user.
|
|
55
|
+
*/
|
|
56
|
+
getUser(): Promise<UnifiedAuthUser | null>;
|
|
57
|
+
/**
|
|
58
|
+
* Retrieves the active SQLite session record.
|
|
59
|
+
*/
|
|
60
|
+
getSession(): Promise<SessionRecord<UnifiedAuthUser> | null>;
|
|
61
|
+
/**
|
|
62
|
+
* Checks whether there is an active session or signed-in provider.
|
|
63
|
+
*/
|
|
64
|
+
isAuthenticated(): Promise<boolean>;
|
|
65
|
+
/**
|
|
66
|
+
* Signs out of the active session and all configured providers.
|
|
67
|
+
*/
|
|
68
|
+
signOut(): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Cleans up all event listeners.
|
|
71
|
+
*/
|
|
72
|
+
destroy(): void;
|
|
73
|
+
}
|
|
@@ -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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-lite",
|
|
3
|
-
"version": "0.
|
|
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`
|