local-lite 2.0.3 → 2.0.4
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/dist/adapters/local/better-sqlite3.js +3 -10
- package/dist/adapters/local/node-sqlite.js +3 -10
- package/dist/adapters/remote/convex.js +2 -5
- package/dist/adapters/remote/firestore.js +2 -5
- package/dist/auth/apple.js +7 -70
- package/dist/auth/github.js +6 -69
- package/dist/auth/google.js +10 -80
- package/dist/auth/microsoft.js +8 -71
- package/dist/backups/cloud-storage.d.ts +2 -2
- package/dist/backups/cloud-storage.js +8 -39
- package/dist/backups/encryption.js +2 -5
- package/dist/keys/generator.d.ts +2 -4
- package/dist/keys/generator.js +4 -33
- package/dist/keys/signed-token.d.ts +2 -1
- package/dist/keys/signed-token.js +6 -23
- package/dist/utils/crypto.d.ts +13 -0
- package/dist/utils/crypto.js +70 -0
- package/dist/utils/oauth.d.ts +20 -0
- package/dist/utils/oauth.js +60 -0
- package/dist/utils/sql.d.ts +8 -0
- package/dist/utils/sql.js +23 -0
- package/package.json +1 -1
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.BetterSQLite3Adapter = void 0;
|
|
4
|
-
const
|
|
5
|
-
const READ_ONLY_PRAGMA_REGEX = /^PRAGMA\b/i;
|
|
6
|
-
const MUTATING_PRAGMA_REGEX = /=|wal_checkpoint|shrink_memory|optimize/i;
|
|
7
|
-
function isReadQuery(sql) {
|
|
8
|
-
if (READ_QUERY_REGEX.test(sql))
|
|
9
|
-
return true;
|
|
10
|
-
return READ_ONLY_PRAGMA_REGEX.test(sql) && !MUTATING_PRAGMA_REGEX.test(sql);
|
|
11
|
-
}
|
|
4
|
+
const sql_js_1 = require("../../utils/sql.js");
|
|
12
5
|
/**
|
|
13
6
|
* Adapter for better-sqlite3 in Node.js, Electron, Next.js, and server environments.
|
|
14
7
|
*/
|
|
@@ -37,7 +30,7 @@ class BetterSQLite3Adapter {
|
|
|
37
30
|
async execute(query, params = []) {
|
|
38
31
|
const trimmed = query.trim();
|
|
39
32
|
// Fast-path: Readers execute directly and synchronously without artificial promise queue delay
|
|
40
|
-
if (isReadQuery(trimmed)) {
|
|
33
|
+
if ((0, sql_js_1.isReadQuery)(trimmed)) {
|
|
41
34
|
const stmt = this.getStatement(trimmed);
|
|
42
35
|
return stmt.all(...params);
|
|
43
36
|
}
|
|
@@ -62,7 +55,7 @@ class BetterSQLite3Adapter {
|
|
|
62
55
|
execute: async (q, p = []) => {
|
|
63
56
|
const trimmed = q.trim();
|
|
64
57
|
const stmt = this.getStatement(trimmed);
|
|
65
|
-
if (stmt.reader || isReadQuery(trimmed)) {
|
|
58
|
+
if (stmt.reader || (0, sql_js_1.isReadQuery)(trimmed)) {
|
|
66
59
|
return stmt.all(...p);
|
|
67
60
|
}
|
|
68
61
|
return [stmt.run(...p)];
|
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.NodeSQLiteAdapter = void 0;
|
|
4
|
-
const
|
|
5
|
-
const READ_ONLY_PRAGMA_REGEX = /^PRAGMA\b/i;
|
|
6
|
-
const MUTATING_PRAGMA_REGEX = /=|wal_checkpoint|shrink_memory|optimize/i;
|
|
7
|
-
function isReadQuery(sql) {
|
|
8
|
-
if (READ_QUERY_REGEX.test(sql))
|
|
9
|
-
return true;
|
|
10
|
-
return READ_ONLY_PRAGMA_REGEX.test(sql) && !MUTATING_PRAGMA_REGEX.test(sql);
|
|
11
|
-
}
|
|
4
|
+
const sql_js_1 = require("../../utils/sql.js");
|
|
12
5
|
/**
|
|
13
6
|
* Adapter for Node.js 22+ built-in `node:sqlite` (DatabaseSync).
|
|
14
7
|
* Provides zero-dependency, native SQLite on modern Node.js runtimes.
|
|
@@ -38,7 +31,7 @@ class NodeSQLiteAdapter {
|
|
|
38
31
|
async execute(query, params = []) {
|
|
39
32
|
const trimmed = query.trim();
|
|
40
33
|
// Fast-path: Readers execute directly and synchronously without queuing delay
|
|
41
|
-
if (isReadQuery(trimmed)) {
|
|
34
|
+
if ((0, sql_js_1.isReadQuery)(trimmed)) {
|
|
42
35
|
const stmt = this.getStatement(trimmed);
|
|
43
36
|
return stmt.all(...params);
|
|
44
37
|
}
|
|
@@ -59,7 +52,7 @@ class NodeSQLiteAdapter {
|
|
|
59
52
|
execute: async (q, p = []) => {
|
|
60
53
|
const trimmed = q.trim();
|
|
61
54
|
const stmt = this.getStatement(trimmed);
|
|
62
|
-
if (isReadQuery(trimmed)) {
|
|
55
|
+
if ((0, sql_js_1.isReadQuery)(trimmed)) {
|
|
63
56
|
return stmt.all(...p);
|
|
64
57
|
}
|
|
65
58
|
return [stmt.run(...p)];
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createConvexStorageUploader = exports.ConvexRemoteAdapter = void 0;
|
|
4
|
+
const sql_js_1 = require("../../utils/sql.js");
|
|
4
5
|
const logger_js_1 = require("../../utils/logger.js");
|
|
5
6
|
const convex_js_1 = require("../../storage/convex.js");
|
|
6
7
|
Object.defineProperty(exports, "createConvexStorageUploader", { enumerable: true, get: function () { return convex_js_1.createConvexStorageUploader; } });
|
|
@@ -19,11 +20,7 @@ function getRowTimestamp(value, fallback) {
|
|
|
19
20
|
throw new Error('Convex change is missing a valid updatedAt timestamp.');
|
|
20
21
|
}
|
|
21
22
|
function getRowId(row, primaryKey) {
|
|
22
|
-
|
|
23
|
-
if (id === undefined || id === null || String(id).length === 0) {
|
|
24
|
-
throw new Error('Convex change is missing its document ID.');
|
|
25
|
-
}
|
|
26
|
-
return String(id);
|
|
23
|
+
return (0, sql_js_1.extractDocumentId)(row, primaryKey, row?._id, 'Convex');
|
|
27
24
|
}
|
|
28
25
|
class ConvexRemoteAdapter {
|
|
29
26
|
client;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createFirebaseStorageUploader = exports.FirestoreAdapter = exports.FirestoreRemoteAdapter = void 0;
|
|
4
4
|
const dynamic_js_1 = require("../../utils/dynamic.js");
|
|
5
|
+
const sql_js_1 = require("../../utils/sql.js");
|
|
5
6
|
const logger_js_1 = require("../../utils/logger.js");
|
|
6
7
|
const firebase_js_1 = require("../../storage/firebase.js");
|
|
7
8
|
Object.defineProperty(exports, "createFirebaseStorageUploader", { enumerable: true, get: function () { return firebase_js_1.createFirebaseStorageUploader; } });
|
|
@@ -33,11 +34,7 @@ function extractTimestamp(val) {
|
|
|
33
34
|
throw new Error('Firestore change has an unsupported updatedAt timestamp.');
|
|
34
35
|
}
|
|
35
36
|
function getRowId(data, primaryKey, documentId) {
|
|
36
|
-
|
|
37
|
-
if (id === undefined || id === null || String(id).length === 0) {
|
|
38
|
-
throw new Error('Firestore change is missing its document ID.');
|
|
39
|
-
}
|
|
40
|
-
return String(id);
|
|
37
|
+
return (0, sql_js_1.extractDocumentId)(data, primaryKey, documentId, 'Firestore');
|
|
41
38
|
}
|
|
42
39
|
class FirestoreRemoteAdapter {
|
|
43
40
|
db;
|
package/dist/auth/apple.js
CHANGED
|
@@ -4,39 +4,11 @@ exports.AppleAuthClient = exports.DEFAULT_APPLE_AUTH_SCOPES = exports.APPLE_TOKE
|
|
|
4
4
|
exports.createInMemoryAppleTokenStore = createInMemoryAppleTokenStore;
|
|
5
5
|
exports.createAppleAuthTokenStore = createAppleAuthTokenStore;
|
|
6
6
|
const identity_js_1 = require("./identity.js");
|
|
7
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
8
|
+
const oauth_js_1 = require("../utils/oauth.js");
|
|
7
9
|
exports.APPLE_AUTHORIZATION_ENDPOINT = 'https://appleid.apple.com/auth/authorize';
|
|
8
10
|
exports.APPLE_TOKEN_ENDPOINT = 'https://appleid.apple.com/auth/token';
|
|
9
11
|
exports.DEFAULT_APPLE_AUTH_SCOPES = ['name', 'email'];
|
|
10
|
-
function secureRandomBytes(length) {
|
|
11
|
-
const crypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
12
|
-
if (!crypto?.getRandomValues) {
|
|
13
|
-
const fallback = new Uint8Array(length);
|
|
14
|
-
for (let i = 0; i < length; i++) {
|
|
15
|
-
fallback[i] = Math.floor(Math.random() * 256);
|
|
16
|
-
}
|
|
17
|
-
return fallback;
|
|
18
|
-
}
|
|
19
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
20
|
-
}
|
|
21
|
-
function base64UrlEncode(bytes) {
|
|
22
|
-
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
23
|
-
let result = '';
|
|
24
|
-
for (let index = 0; index < bytes.length; index += 3) {
|
|
25
|
-
const first = bytes[index];
|
|
26
|
-
const second = bytes[index + 1];
|
|
27
|
-
const third = bytes[index + 2];
|
|
28
|
-
result += alphabet[first >> 2];
|
|
29
|
-
result +=
|
|
30
|
-
alphabet[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
31
|
-
if (second !== undefined) {
|
|
32
|
-
result +=
|
|
33
|
-
alphabet[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
34
|
-
}
|
|
35
|
-
if (third !== undefined)
|
|
36
|
-
result += alphabet[third & 63];
|
|
37
|
-
}
|
|
38
|
-
return result;
|
|
39
|
-
}
|
|
40
12
|
function parseJwtClaims(jwt) {
|
|
41
13
|
try {
|
|
42
14
|
const parts = jwt.split('.');
|
|
@@ -68,45 +40,10 @@ function validateUser(value) {
|
|
|
68
40
|
return typeof user.id === 'string' && typeof user.email === 'string';
|
|
69
41
|
}
|
|
70
42
|
function createInMemoryAppleTokenStore() {
|
|
71
|
-
|
|
72
|
-
let storedUser = null;
|
|
73
|
-
return {
|
|
74
|
-
getTokens: async () => storedTokens,
|
|
75
|
-
setTokens: async (tokens) => {
|
|
76
|
-
storedTokens = tokens;
|
|
77
|
-
},
|
|
78
|
-
removeTokens: async () => {
|
|
79
|
-
storedTokens = null;
|
|
80
|
-
},
|
|
81
|
-
getUser: async () => storedUser,
|
|
82
|
-
setUser: async (user) => {
|
|
83
|
-
storedUser = user;
|
|
84
|
-
},
|
|
85
|
-
};
|
|
43
|
+
return (0, oauth_js_1.createInMemoryOAuthTokenStore)();
|
|
86
44
|
}
|
|
87
45
|
function createAppleAuthTokenStore(storage, prefix = 'local-lite-apple-auth') {
|
|
88
|
-
|
|
89
|
-
const userKey = `${prefix}-user`;
|
|
90
|
-
return {
|
|
91
|
-
getTokens: async () => {
|
|
92
|
-
const raw = await storage.getItem(tokensKey);
|
|
93
|
-
return validateTokens(raw) ? raw : null;
|
|
94
|
-
},
|
|
95
|
-
setTokens: (tokens) => storage.setItem(tokensKey, tokens),
|
|
96
|
-
removeTokens: () => storage.removeItem(tokensKey),
|
|
97
|
-
getUser: async () => {
|
|
98
|
-
const raw = await storage.getItem(userKey);
|
|
99
|
-
return validateUser(raw) ? raw : null;
|
|
100
|
-
},
|
|
101
|
-
setUser: async (user) => {
|
|
102
|
-
if (user) {
|
|
103
|
-
await storage.setItem(userKey, user);
|
|
104
|
-
}
|
|
105
|
-
else {
|
|
106
|
-
await storage.removeItem(userKey);
|
|
107
|
-
}
|
|
108
|
-
},
|
|
109
|
-
};
|
|
46
|
+
return (0, oauth_js_1.createOAuthTokenStore)(storage, prefix, validateTokens, validateUser);
|
|
110
47
|
}
|
|
111
48
|
class AppleAuthClient {
|
|
112
49
|
options;
|
|
@@ -161,9 +98,9 @@ class AppleAuthClient {
|
|
|
161
98
|
if (!this.options.redirectUri) {
|
|
162
99
|
throw new Error('Apple OAuth redirectUri is required for web authorization flow.');
|
|
163
100
|
}
|
|
164
|
-
const randomBytes = this.options.randomBytes ??
|
|
165
|
-
const state = base64UrlEncode(randomBytes(32));
|
|
166
|
-
const nonce = base64UrlEncode(randomBytes(32));
|
|
101
|
+
const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
|
|
102
|
+
const state = (0, crypto_js_1.base64UrlEncode)(randomBytes(32));
|
|
103
|
+
const nonce = (0, crypto_js_1.base64UrlEncode)(randomBytes(32));
|
|
167
104
|
const scopes = this.options.scopes && this.options.scopes.length > 0
|
|
168
105
|
? this.options.scopes.join(' ')
|
|
169
106
|
: exports.DEFAULT_APPLE_AUTH_SCOPES.join(' ');
|
package/dist/auth/github.js
CHANGED
|
@@ -4,40 +4,12 @@ exports.GitHubAuthClient = exports.DEFAULT_GITHUB_AUTH_SCOPES = exports.GITHUB_A
|
|
|
4
4
|
exports.createInMemoryGitHubTokenStore = createInMemoryGitHubTokenStore;
|
|
5
5
|
exports.createGitHubAuthTokenStore = createGitHubAuthTokenStore;
|
|
6
6
|
const identity_js_1 = require("./identity.js");
|
|
7
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
8
|
+
const oauth_js_1 = require("../utils/oauth.js");
|
|
7
9
|
exports.GITHUB_AUTHORIZATION_ENDPOINT = 'https://github.com/login/oauth/authorize';
|
|
8
10
|
exports.GITHUB_TOKEN_ENDPOINT = 'https://github.com/login/oauth/access_token';
|
|
9
11
|
exports.GITHUB_API_ENDPOINT = 'https://api.github.com';
|
|
10
12
|
exports.DEFAULT_GITHUB_AUTH_SCOPES = ['read:user', 'user:email'];
|
|
11
|
-
function secureRandomBytes(length) {
|
|
12
|
-
const crypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
13
|
-
if (!crypto?.getRandomValues) {
|
|
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;
|
|
19
|
-
}
|
|
20
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
21
|
-
}
|
|
22
|
-
function base64UrlEncode(bytes) {
|
|
23
|
-
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
24
|
-
let result = '';
|
|
25
|
-
for (let index = 0; index < bytes.length; index += 3) {
|
|
26
|
-
const first = bytes[index];
|
|
27
|
-
const second = bytes[index + 1];
|
|
28
|
-
const third = bytes[index + 2];
|
|
29
|
-
result += alphabet[first >> 2];
|
|
30
|
-
result +=
|
|
31
|
-
alphabet[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
32
|
-
if (second !== undefined) {
|
|
33
|
-
result +=
|
|
34
|
-
alphabet[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
35
|
-
}
|
|
36
|
-
if (third !== undefined)
|
|
37
|
-
result += alphabet[third & 63];
|
|
38
|
-
}
|
|
39
|
-
return result;
|
|
40
|
-
}
|
|
41
13
|
function validateTokens(value) {
|
|
42
14
|
if (!value || typeof value !== 'object')
|
|
43
15
|
return false;
|
|
@@ -53,45 +25,10 @@ function validateUser(value) {
|
|
|
53
25
|
typeof user.name === 'string');
|
|
54
26
|
}
|
|
55
27
|
function createInMemoryGitHubTokenStore() {
|
|
56
|
-
|
|
57
|
-
let storedUser = null;
|
|
58
|
-
return {
|
|
59
|
-
getTokens: async () => storedTokens,
|
|
60
|
-
setTokens: async (tokens) => {
|
|
61
|
-
storedTokens = tokens;
|
|
62
|
-
},
|
|
63
|
-
removeTokens: async () => {
|
|
64
|
-
storedTokens = null;
|
|
65
|
-
},
|
|
66
|
-
getUser: async () => storedUser,
|
|
67
|
-
setUser: async (user) => {
|
|
68
|
-
storedUser = user;
|
|
69
|
-
},
|
|
70
|
-
};
|
|
28
|
+
return (0, oauth_js_1.createInMemoryOAuthTokenStore)();
|
|
71
29
|
}
|
|
72
30
|
function createGitHubAuthTokenStore(storage, prefix = 'local-lite-github-auth') {
|
|
73
|
-
|
|
74
|
-
const userKey = `${prefix}-user`;
|
|
75
|
-
return {
|
|
76
|
-
getTokens: async () => {
|
|
77
|
-
const raw = await storage.getItem(tokensKey);
|
|
78
|
-
return validateTokens(raw) ? raw : null;
|
|
79
|
-
},
|
|
80
|
-
setTokens: (tokens) => storage.setItem(tokensKey, tokens),
|
|
81
|
-
removeTokens: () => storage.removeItem(tokensKey),
|
|
82
|
-
getUser: async () => {
|
|
83
|
-
const raw = await storage.getItem(userKey);
|
|
84
|
-
return validateUser(raw) ? raw : null;
|
|
85
|
-
},
|
|
86
|
-
setUser: async (user) => {
|
|
87
|
-
if (user) {
|
|
88
|
-
await storage.setItem(userKey, user);
|
|
89
|
-
}
|
|
90
|
-
else {
|
|
91
|
-
await storage.removeItem(userKey);
|
|
92
|
-
}
|
|
93
|
-
},
|
|
94
|
-
};
|
|
31
|
+
return (0, oauth_js_1.createOAuthTokenStore)(storage, prefix, validateTokens, validateUser);
|
|
95
32
|
}
|
|
96
33
|
class GitHubAuthClient {
|
|
97
34
|
options;
|
|
@@ -136,12 +73,12 @@ class GitHubAuthClient {
|
|
|
136
73
|
}
|
|
137
74
|
}
|
|
138
75
|
async signIn() {
|
|
139
|
-
const randomBytes = this.options.randomBytes ??
|
|
76
|
+
const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
|
|
140
77
|
const stateBytes = randomBytes(32);
|
|
141
78
|
if (stateBytes.length !== 32) {
|
|
142
79
|
throw new Error('The randomBytes provider returned an invalid number of bytes.');
|
|
143
80
|
}
|
|
144
|
-
const state = base64UrlEncode(stateBytes);
|
|
81
|
+
const state = (0, crypto_js_1.base64UrlEncode)(stateBytes);
|
|
145
82
|
const scopes = this.options.scopes && this.options.scopes.length > 0
|
|
146
83
|
? this.options.scopes
|
|
147
84
|
: exports.DEFAULT_GITHUB_AUTH_SCOPES;
|
package/dist/auth/google.js
CHANGED
|
@@ -6,41 +6,13 @@ exports.createGoogleAuthTokenStore = createGoogleAuthTokenStore;
|
|
|
6
6
|
const identity_js_1 = require("./identity.js");
|
|
7
7
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
8
8
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
9
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
10
|
+
const oauth_js_1 = require("../utils/oauth.js");
|
|
9
11
|
const cloud_storage_js_1 = require("../backups/cloud-storage.js");
|
|
10
12
|
exports.GOOGLE_AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth';
|
|
11
13
|
exports.GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
|
|
12
14
|
exports.GOOGLE_USERINFO_ENDPOINT = 'https://www.googleapis.com/oauth2/v3/userinfo';
|
|
13
15
|
exports.DEFAULT_GOOGLE_AUTH_SCOPES = ['openid', 'email', 'profile'];
|
|
14
|
-
function secureRandomBytes(length) {
|
|
15
|
-
const crypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
16
|
-
if (!crypto?.getRandomValues) {
|
|
17
|
-
const fallback = new Uint8Array(length);
|
|
18
|
-
for (let i = 0; i < length; i++) {
|
|
19
|
-
fallback[i] = Math.floor(Math.random() * 256);
|
|
20
|
-
}
|
|
21
|
-
return fallback;
|
|
22
|
-
}
|
|
23
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
24
|
-
}
|
|
25
|
-
function base64UrlEncode(bytes) {
|
|
26
|
-
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
27
|
-
let result = '';
|
|
28
|
-
for (let index = 0; index < bytes.length; index += 3) {
|
|
29
|
-
const first = bytes[index];
|
|
30
|
-
const second = bytes[index + 1];
|
|
31
|
-
const third = bytes[index + 2];
|
|
32
|
-
result += alphabet[first >> 2];
|
|
33
|
-
result +=
|
|
34
|
-
alphabet[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
35
|
-
if (second !== undefined) {
|
|
36
|
-
result +=
|
|
37
|
-
alphabet[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
38
|
-
}
|
|
39
|
-
if (third !== undefined)
|
|
40
|
-
result += alphabet[third & 63];
|
|
41
|
-
}
|
|
42
|
-
return result;
|
|
43
|
-
}
|
|
44
16
|
function validateTokens(value) {
|
|
45
17
|
if (!value || typeof value !== 'object')
|
|
46
18
|
return false;
|
|
@@ -60,58 +32,16 @@ function validateUser(value) {
|
|
|
60
32
|
typeof user.name === 'string');
|
|
61
33
|
}
|
|
62
34
|
function createInMemoryGoogleTokenStore() {
|
|
63
|
-
|
|
64
|
-
let storedUser = null;
|
|
65
|
-
return {
|
|
66
|
-
getTokens: async () => storedTokens,
|
|
67
|
-
setTokens: async (tokens) => {
|
|
68
|
-
storedTokens = tokens;
|
|
69
|
-
},
|
|
70
|
-
removeTokens: async () => {
|
|
71
|
-
storedTokens = null;
|
|
72
|
-
},
|
|
73
|
-
getUser: async () => storedUser,
|
|
74
|
-
setUser: async (user) => {
|
|
75
|
-
storedUser = user;
|
|
76
|
-
},
|
|
77
|
-
};
|
|
35
|
+
return (0, oauth_js_1.createInMemoryOAuthTokenStore)();
|
|
78
36
|
}
|
|
79
37
|
function createGoogleAuthTokenStore(storage, prefix = 'local-lite-google-auth') {
|
|
80
|
-
|
|
81
|
-
const userKey = `${prefix}-user`;
|
|
82
|
-
return {
|
|
83
|
-
getTokens: async () => {
|
|
84
|
-
const raw = await storage.getItem(tokensKey);
|
|
85
|
-
return validateTokens(raw) ? raw : null;
|
|
86
|
-
},
|
|
87
|
-
setTokens: (tokens) => storage.setItem(tokensKey, tokens),
|
|
88
|
-
removeTokens: () => storage.removeItem(tokensKey),
|
|
89
|
-
getUser: async () => {
|
|
90
|
-
const raw = await storage.getItem(userKey);
|
|
91
|
-
return validateUser(raw) ? raw : null;
|
|
92
|
-
},
|
|
93
|
-
setUser: async (user) => {
|
|
94
|
-
if (user) {
|
|
95
|
-
await storage.setItem(userKey, user);
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
await storage.removeItem(userKey);
|
|
99
|
-
}
|
|
100
|
-
},
|
|
101
|
-
};
|
|
38
|
+
return (0, oauth_js_1.createOAuthTokenStore)(storage, prefix, validateTokens, validateUser);
|
|
102
39
|
}
|
|
103
40
|
async function parseTokenResponse(response) {
|
|
104
|
-
|
|
105
|
-
return (await response.json());
|
|
106
|
-
}
|
|
107
|
-
catch {
|
|
108
|
-
throw new Error(`Google OAuth request failed (${response.status}).`);
|
|
109
|
-
}
|
|
41
|
+
return (0, oauth_js_1.parseOAuthTokenResponse)(response, 'Google');
|
|
110
42
|
}
|
|
111
43
|
function throwOAuthError(payload, status) {
|
|
112
|
-
|
|
113
|
-
payload.error ||
|
|
114
|
-
`Google OAuth request failed (${status}).`);
|
|
44
|
+
return (0, oauth_js_1.throwOAuthError)(payload, status, 'Google');
|
|
115
45
|
}
|
|
116
46
|
class GoogleAuthClient {
|
|
117
47
|
options;
|
|
@@ -156,15 +86,15 @@ class GoogleAuthClient {
|
|
|
156
86
|
}
|
|
157
87
|
}
|
|
158
88
|
async signIn() {
|
|
159
|
-
const randomBytes = this.options.randomBytes ??
|
|
89
|
+
const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
|
|
160
90
|
const verifierBytes = randomBytes(32);
|
|
161
91
|
const stateBytes = randomBytes(32);
|
|
162
92
|
if (verifierBytes.length !== 32 || stateBytes.length !== 32) {
|
|
163
93
|
throw new Error('The randomBytes provider returned an invalid number of bytes.');
|
|
164
94
|
}
|
|
165
|
-
const codeVerifier = base64UrlEncode(verifierBytes);
|
|
166
|
-
const codeChallenge = base64UrlEncode((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
|
|
167
|
-
const state = base64UrlEncode(stateBytes);
|
|
95
|
+
const codeVerifier = (0, crypto_js_1.base64UrlEncode)(verifierBytes);
|
|
96
|
+
const codeChallenge = (0, crypto_js_1.base64UrlEncode)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
|
|
97
|
+
const state = (0, crypto_js_1.base64UrlEncode)(stateBytes);
|
|
168
98
|
const scopes = this.options.scopes && this.options.scopes.length > 0
|
|
169
99
|
? this.options.scopes
|
|
170
100
|
: exports.DEFAULT_GOOGLE_AUTH_SCOPES;
|
package/dist/auth/microsoft.js
CHANGED
|
@@ -6,6 +6,8 @@ exports.createMicrosoftAuthTokenStore = createMicrosoftAuthTokenStore;
|
|
|
6
6
|
const identity_js_1 = require("./identity.js");
|
|
7
7
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
8
8
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
9
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
10
|
+
const oauth_js_1 = require("../utils/oauth.js");
|
|
9
11
|
const onedrive_js_1 = require("../backups/onedrive.js");
|
|
10
12
|
exports.MICROSOFT_GRAPH_ENDPOINT = 'https://graph.microsoft.com/v1.0';
|
|
11
13
|
exports.DEFAULT_MICROSOFT_AUTH_SCOPES = [
|
|
@@ -14,36 +16,6 @@ exports.DEFAULT_MICROSOFT_AUTH_SCOPES = [
|
|
|
14
16
|
'email',
|
|
15
17
|
'User.Read',
|
|
16
18
|
];
|
|
17
|
-
function secureRandomBytes(length) {
|
|
18
|
-
const crypto = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
19
|
-
if (!crypto?.getRandomValues) {
|
|
20
|
-
const fallback = new Uint8Array(length);
|
|
21
|
-
for (let i = 0; i < length; i++) {
|
|
22
|
-
fallback[i] = Math.floor(Math.random() * 256);
|
|
23
|
-
}
|
|
24
|
-
return fallback;
|
|
25
|
-
}
|
|
26
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
27
|
-
}
|
|
28
|
-
function base64UrlEncode(bytes) {
|
|
29
|
-
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
30
|
-
let result = '';
|
|
31
|
-
for (let index = 0; index < bytes.length; index += 3) {
|
|
32
|
-
const first = bytes[index];
|
|
33
|
-
const second = bytes[index + 1];
|
|
34
|
-
const third = bytes[index + 2];
|
|
35
|
-
result += alphabet[first >> 2];
|
|
36
|
-
result +=
|
|
37
|
-
alphabet[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
38
|
-
if (second !== undefined) {
|
|
39
|
-
result +=
|
|
40
|
-
alphabet[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
41
|
-
}
|
|
42
|
-
if (third !== undefined)
|
|
43
|
-
result += alphabet[third & 63];
|
|
44
|
-
}
|
|
45
|
-
return result;
|
|
46
|
-
}
|
|
47
19
|
function validateTokens(value) {
|
|
48
20
|
if (!value || typeof value !== 'object')
|
|
49
21
|
return false;
|
|
@@ -63,45 +35,10 @@ function validateUser(value) {
|
|
|
63
35
|
typeof user.name === 'string');
|
|
64
36
|
}
|
|
65
37
|
function createInMemoryMicrosoftTokenStore() {
|
|
66
|
-
|
|
67
|
-
let storedUser = null;
|
|
68
|
-
return {
|
|
69
|
-
getTokens: async () => storedTokens,
|
|
70
|
-
setTokens: async (tokens) => {
|
|
71
|
-
storedTokens = tokens;
|
|
72
|
-
},
|
|
73
|
-
removeTokens: async () => {
|
|
74
|
-
storedTokens = null;
|
|
75
|
-
},
|
|
76
|
-
getUser: async () => storedUser,
|
|
77
|
-
setUser: async (user) => {
|
|
78
|
-
storedUser = user;
|
|
79
|
-
},
|
|
80
|
-
};
|
|
38
|
+
return (0, oauth_js_1.createInMemoryOAuthTokenStore)();
|
|
81
39
|
}
|
|
82
40
|
function createMicrosoftAuthTokenStore(storage, prefix = 'local-lite-microsoft-auth') {
|
|
83
|
-
|
|
84
|
-
const userKey = `${prefix}-user`;
|
|
85
|
-
return {
|
|
86
|
-
getTokens: async () => {
|
|
87
|
-
const raw = await storage.getItem(tokensKey);
|
|
88
|
-
return validateTokens(raw) ? raw : null;
|
|
89
|
-
},
|
|
90
|
-
setTokens: (tokens) => storage.setItem(tokensKey, tokens),
|
|
91
|
-
removeTokens: () => storage.removeItem(tokensKey),
|
|
92
|
-
getUser: async () => {
|
|
93
|
-
const raw = await storage.getItem(userKey);
|
|
94
|
-
return validateUser(raw) ? raw : null;
|
|
95
|
-
},
|
|
96
|
-
setUser: async (user) => {
|
|
97
|
-
if (user) {
|
|
98
|
-
await storage.setItem(userKey, user);
|
|
99
|
-
}
|
|
100
|
-
else {
|
|
101
|
-
await storage.removeItem(userKey);
|
|
102
|
-
}
|
|
103
|
-
},
|
|
104
|
-
};
|
|
41
|
+
return (0, oauth_js_1.createOAuthTokenStore)(storage, prefix, validateTokens, validateUser);
|
|
105
42
|
}
|
|
106
43
|
class MicrosoftAuthClient {
|
|
107
44
|
options;
|
|
@@ -154,15 +91,15 @@ class MicrosoftAuthClient {
|
|
|
154
91
|
}
|
|
155
92
|
}
|
|
156
93
|
async signIn() {
|
|
157
|
-
const randomBytes = this.options.randomBytes ??
|
|
94
|
+
const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
|
|
158
95
|
const verifierBytes = randomBytes(32);
|
|
159
96
|
const stateBytes = randomBytes(32);
|
|
160
97
|
if (verifierBytes.length !== 32 || stateBytes.length !== 32) {
|
|
161
98
|
throw new Error('The randomBytes provider returned an invalid number of bytes.');
|
|
162
99
|
}
|
|
163
|
-
const codeVerifier = base64UrlEncode(verifierBytes);
|
|
164
|
-
const codeChallenge = base64UrlEncode((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
|
|
165
|
-
const state = base64UrlEncode(stateBytes);
|
|
100
|
+
const codeVerifier = (0, crypto_js_1.base64UrlEncode)(verifierBytes);
|
|
101
|
+
const codeChallenge = (0, crypto_js_1.base64UrlEncode)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
|
|
102
|
+
const state = (0, crypto_js_1.base64UrlEncode)(stateBytes);
|
|
166
103
|
const scopes = this.options.scopes && this.options.scopes.length > 0
|
|
167
104
|
? this.options.scopes
|
|
168
105
|
: exports.DEFAULT_MICROSOFT_AUTH_SCOPES;
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import type { BackupStorage, CloudBackupClient, CreateDatabaseBackupOptions, ResolvableBackupDatabase } from './operations.js';
|
|
1
|
+
import type { BackupAccessTokenProvider, BackupStorage, CloudBackupClient, CreateDatabaseBackupOptions, ResolvableBackupDatabase } from './operations.js';
|
|
2
2
|
import type { EncryptedBackupOptions, RestoreEncryptedBackupOptions } from './encryption.js';
|
|
3
3
|
import type { GoogleAuthClient } from '../auth/google.js';
|
|
4
|
+
export type { BackupAccessTokenProvider };
|
|
4
5
|
export interface CloudBackupFile {
|
|
5
6
|
id: string;
|
|
6
7
|
name: string;
|
|
7
8
|
modifiedAt?: string;
|
|
8
9
|
size?: number;
|
|
9
10
|
}
|
|
10
|
-
export type BackupAccessTokenProvider = () => Promise<string>;
|
|
11
11
|
export declare const GOOGLE_DRIVE_SCOPE = "https://www.googleapis.com/auth/drive.file";
|
|
12
12
|
export interface GoogleDriveTokens {
|
|
13
13
|
accessToken: string;
|
|
@@ -6,38 +6,14 @@ exports.createGoogleDriveTokenStore = createGoogleDriveTokenStore;
|
|
|
6
6
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
7
7
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
8
8
|
const operations_js_1 = require("./operations.js");
|
|
9
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
10
|
+
const oauth_js_1 = require("../utils/oauth.js");
|
|
9
11
|
const GOOGLE_API = 'https://www.googleapis.com/drive/v3';
|
|
10
12
|
const GOOGLE_UPLOAD_API = 'https://www.googleapis.com/upload/drive/v3';
|
|
11
13
|
const GOOGLE_AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth';
|
|
12
14
|
const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
|
|
13
15
|
exports.GOOGLE_DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.file';
|
|
14
16
|
const BACKUP_FOLDER = 'backups';
|
|
15
|
-
function secureRandomBytes(length) {
|
|
16
|
-
const crypto = globalThis.crypto;
|
|
17
|
-
if (!crypto?.getRandomValues) {
|
|
18
|
-
throw new Error('Secure random number generation is unavailable.');
|
|
19
|
-
}
|
|
20
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
21
|
-
}
|
|
22
|
-
function base64UrlEncode(bytes) {
|
|
23
|
-
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
24
|
-
let result = '';
|
|
25
|
-
for (let index = 0; index < bytes.length; index += 3) {
|
|
26
|
-
const first = bytes[index];
|
|
27
|
-
const second = bytes[index + 1];
|
|
28
|
-
const third = bytes[index + 2];
|
|
29
|
-
result += alphabet[first >> 2];
|
|
30
|
-
result +=
|
|
31
|
-
alphabet[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
32
|
-
if (second !== undefined) {
|
|
33
|
-
result +=
|
|
34
|
-
alphabet[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
35
|
-
}
|
|
36
|
-
if (third !== undefined)
|
|
37
|
-
result += alphabet[third & 63];
|
|
38
|
-
}
|
|
39
|
-
return result;
|
|
40
|
-
}
|
|
41
17
|
function validateGoogleTokens(value) {
|
|
42
18
|
if (!value || typeof value !== 'object')
|
|
43
19
|
return false;
|
|
@@ -70,12 +46,7 @@ function createGoogleDriveTokenStore(storage, key = 'local-lite-google-drive-bac
|
|
|
70
46
|
};
|
|
71
47
|
}
|
|
72
48
|
async function parseTokenResponse(response) {
|
|
73
|
-
|
|
74
|
-
return (await response.json());
|
|
75
|
-
}
|
|
76
|
-
catch {
|
|
77
|
-
throw new Error(`Google OAuth request failed (${response.status}).`);
|
|
78
|
-
}
|
|
49
|
+
return (0, oauth_js_1.parseOAuthTokenResponse)(response, 'Google');
|
|
79
50
|
}
|
|
80
51
|
function createStoredTokens(payload, prior) {
|
|
81
52
|
if (!payload.access_token) {
|
|
@@ -88,9 +59,7 @@ function createStoredTokens(payload, prior) {
|
|
|
88
59
|
};
|
|
89
60
|
}
|
|
90
61
|
function throwTokenError(payload, status) {
|
|
91
|
-
|
|
92
|
-
payload.error ||
|
|
93
|
-
`Google OAuth request failed (${status}).`);
|
|
62
|
+
return (0, oauth_js_1.throwOAuthError)(payload, status, 'Google');
|
|
94
63
|
}
|
|
95
64
|
async function parseApiError(response) {
|
|
96
65
|
let detail = '';
|
|
@@ -269,15 +238,15 @@ class GoogleDriveBackupClient {
|
|
|
269
238
|
this.notify(connected);
|
|
270
239
|
return connected;
|
|
271
240
|
}
|
|
272
|
-
const randomBytes = this.options.randomBytes ??
|
|
241
|
+
const randomBytes = this.options.randomBytes ?? crypto_js_1.requireSecureRandomBytes;
|
|
273
242
|
const verifierBytes = randomBytes(32);
|
|
274
243
|
const stateBytes = randomBytes(32);
|
|
275
244
|
if (verifierBytes.length !== 32 || stateBytes.length !== 32) {
|
|
276
245
|
throw new Error('The randomBytes provider returned an invalid number of bytes.');
|
|
277
246
|
}
|
|
278
|
-
const codeVerifier = base64UrlEncode(verifierBytes);
|
|
279
|
-
const codeChallenge = base64UrlEncode((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
|
|
280
|
-
const state = base64UrlEncode(stateBytes);
|
|
247
|
+
const codeVerifier = (0, crypto_js_1.base64UrlEncode)(verifierBytes);
|
|
248
|
+
const codeChallenge = (0, crypto_js_1.base64UrlEncode)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
|
|
249
|
+
const state = (0, crypto_js_1.base64UrlEncode)(stateBytes);
|
|
281
250
|
const authorizationParams = new URLSearchParams({
|
|
282
251
|
client_id: this.options.clientId,
|
|
283
252
|
redirect_uri: this.options.redirectUri,
|
|
@@ -8,16 +8,13 @@ exports.restoreEncryptedDatabaseBackup = restoreEncryptedDatabaseBackup;
|
|
|
8
8
|
const pbkdf2_js_1 = require("@noble/hashes/pbkdf2.js");
|
|
9
9
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
10
10
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
11
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
11
12
|
const MAGIC_HEADER = new Uint8Array([0x4c, 0x4c, 0x45, 0x4e, 0x43, 0x31]); // "LLENC1"
|
|
12
13
|
const SALT_LENGTH = 16;
|
|
13
14
|
const IV_LENGTH = 12;
|
|
14
15
|
const DEFAULT_ITERATIONS = 50000;
|
|
15
16
|
function getRandomBytes(length) {
|
|
16
|
-
|
|
17
|
-
if (!crypto?.getRandomValues) {
|
|
18
|
-
throw new Error('Secure random generation is unavailable for backup encryption.');
|
|
19
|
-
}
|
|
20
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
17
|
+
return (0, crypto_js_1.requireSecureRandomBytes)(length, 'Secure random generation is unavailable for backup encryption.');
|
|
21
18
|
}
|
|
22
19
|
const ITERATIONS_LENGTH = 4;
|
|
23
20
|
function isEncryptedBackup(data) {
|
package/dist/keys/generator.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
+
import { getRandomBytes } from '../utils/crypto.js';
|
|
1
2
|
import { GenerateApiKeyOptions, GeneratedApiKey } from './types.js';
|
|
2
|
-
|
|
3
|
-
* Generates cryptographically secure random bytes across Web, Expo/React Native, and Node.js.
|
|
4
|
-
*/
|
|
5
|
-
export declare function getRandomBytes(length: number): Uint8Array;
|
|
3
|
+
export { getRandomBytes };
|
|
6
4
|
/**
|
|
7
5
|
* Encodes raw bytes into a base62 string.
|
|
8
6
|
*/
|
package/dist/keys/generator.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getRandomBytes =
|
|
3
|
+
exports.getRandomBytes = void 0;
|
|
4
4
|
exports.bytesToBase62 = bytesToBase62;
|
|
5
5
|
exports.calculateKeyChecksum = calculateKeyChecksum;
|
|
6
6
|
exports.timingSafeEqual = timingSafeEqual;
|
|
@@ -10,38 +10,9 @@ exports.verifyApiKeyFormat = verifyApiKeyFormat;
|
|
|
10
10
|
exports.verifyApiKey = verifyApiKey;
|
|
11
11
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
12
12
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
13
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
14
|
+
Object.defineProperty(exports, "getRandomBytes", { enumerable: true, get: function () { return crypto_js_1.getRandomBytes; } });
|
|
13
15
|
const BASE62_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
|
14
|
-
/**
|
|
15
|
-
* Generates cryptographically secure random bytes across Web, Expo/React Native, and Node.js.
|
|
16
|
-
*/
|
|
17
|
-
function getRandomBytes(length) {
|
|
18
|
-
const cryptoObj = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
19
|
-
if (cryptoObj?.getRandomValues) {
|
|
20
|
-
try {
|
|
21
|
-
return cryptoObj.getRandomValues(new Uint8Array(length));
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
// Fallback below
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
try {
|
|
28
|
-
// Dynamic fallback for Node.js environments without globalThis.crypto
|
|
29
|
-
const nodeCrypto = globalThis.process?.versions?.node
|
|
30
|
-
? globalThis.require('node:crypto')
|
|
31
|
-
: null;
|
|
32
|
-
if (nodeCrypto?.randomBytes) {
|
|
33
|
-
return new Uint8Array(nodeCrypto.randomBytes(length));
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
catch {
|
|
37
|
-
// Fallback ignored
|
|
38
|
-
}
|
|
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;
|
|
44
|
-
}
|
|
45
16
|
/**
|
|
46
17
|
* Encodes raw bytes into a base62 string.
|
|
47
18
|
*/
|
|
@@ -92,7 +63,7 @@ function generateApiKey(options = {}) {
|
|
|
92
63
|
.replace(/[^a-z0-9_-]/g, '');
|
|
93
64
|
const byteLength = options.byteLength ?? 24;
|
|
94
65
|
const withChecksum = options.withChecksum ?? true;
|
|
95
|
-
const entropyBytes = getRandomBytes(byteLength);
|
|
66
|
+
const entropyBytes = (0, crypto_js_1.getRandomBytes)(byteLength);
|
|
96
67
|
const entropy = bytesToBase62(entropyBytes);
|
|
97
68
|
let key;
|
|
98
69
|
let checksum = '';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { base64UrlEncode } from '../utils/crypto.js';
|
|
1
2
|
import { CreateSignedTokenOptions, RenewSignedTokenOptions, VerifySignedTokenResult } from './types.js';
|
|
2
|
-
export
|
|
3
|
+
export { base64UrlEncode };
|
|
3
4
|
export declare function base64UrlDecode(str: string): Uint8Array;
|
|
4
5
|
/**
|
|
5
6
|
* Creates a signed, tamper-evident token with optional expiration and token ID.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.base64UrlEncode =
|
|
3
|
+
exports.base64UrlEncode = void 0;
|
|
4
4
|
exports.base64UrlDecode = base64UrlDecode;
|
|
5
5
|
exports.createSignedToken = createSignedToken;
|
|
6
6
|
exports.verifySignedToken = verifySignedToken;
|
|
@@ -8,6 +8,8 @@ exports.renewSignedToken = renewSignedToken;
|
|
|
8
8
|
const hmac_js_1 = require("@noble/hashes/hmac.js");
|
|
9
9
|
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
10
10
|
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
11
|
+
const crypto_js_1 = require("../utils/crypto.js");
|
|
12
|
+
Object.defineProperty(exports, "base64UrlEncode", { enumerable: true, get: function () { return crypto_js_1.base64UrlEncode; } });
|
|
11
13
|
const uuid_js_1 = require("../utils/uuid.js");
|
|
12
14
|
const generator_js_1 = require("./generator.js");
|
|
13
15
|
const B64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
@@ -15,25 +17,6 @@ const B64URL_LOOKUP = new Uint8Array(256);
|
|
|
15
17
|
for (let i = 0; i < B64URL_ALPHABET.length; i++) {
|
|
16
18
|
B64URL_LOOKUP[B64URL_ALPHABET.charCodeAt(i)] = i;
|
|
17
19
|
}
|
|
18
|
-
function base64UrlEncode(bytes) {
|
|
19
|
-
let result = '';
|
|
20
|
-
for (let i = 0; i < bytes.length; i += 3) {
|
|
21
|
-
const first = bytes[i];
|
|
22
|
-
const second = bytes[i + 1];
|
|
23
|
-
const third = bytes[i + 2];
|
|
24
|
-
result += B64URL_ALPHABET[first >> 2];
|
|
25
|
-
result +=
|
|
26
|
-
B64URL_ALPHABET[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
27
|
-
if (second !== undefined) {
|
|
28
|
-
result +=
|
|
29
|
-
B64URL_ALPHABET[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
30
|
-
}
|
|
31
|
-
if (third !== undefined) {
|
|
32
|
-
result += B64URL_ALPHABET[third & 63];
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
return result;
|
|
36
|
-
}
|
|
37
20
|
function base64UrlDecode(str) {
|
|
38
21
|
// Normalize base64url padding
|
|
39
22
|
let clean = str.replace(/[^A-Za-z0-9\-_]/g, '');
|
|
@@ -67,7 +50,7 @@ function base64UrlDecode(str) {
|
|
|
67
50
|
}
|
|
68
51
|
function computeHmacSignature(content, secret) {
|
|
69
52
|
const sigBytes = (0, hmac_js_1.hmac)(sha2_js_1.sha256, (0, utils_js_1.utf8ToBytes)(secret), (0, utils_js_1.utf8ToBytes)(content));
|
|
70
|
-
return base64UrlEncode(sigBytes);
|
|
53
|
+
return (0, crypto_js_1.base64UrlEncode)(sigBytes);
|
|
71
54
|
}
|
|
72
55
|
/**
|
|
73
56
|
* Creates a signed, tamper-evident token with optional expiration and token ID.
|
|
@@ -93,8 +76,8 @@ function createSignedToken(options) {
|
|
|
93
76
|
exp: expiresAt,
|
|
94
77
|
jti: options.tokenId || (0, uuid_js_1.generateUUID)(),
|
|
95
78
|
};
|
|
96
|
-
const headerB64 = base64UrlEncode((0, utils_js_1.utf8ToBytes)(JSON.stringify(header)));
|
|
97
|
-
const payloadB64 = base64UrlEncode((0, utils_js_1.utf8ToBytes)(JSON.stringify(payload)));
|
|
79
|
+
const headerB64 = (0, crypto_js_1.base64UrlEncode)((0, utils_js_1.utf8ToBytes)(JSON.stringify(header)));
|
|
80
|
+
const payloadB64 = (0, crypto_js_1.base64UrlEncode)((0, utils_js_1.utf8ToBytes)(JSON.stringify(payload)));
|
|
98
81
|
const content = `${headerB64}.${payloadB64}`;
|
|
99
82
|
const signature = computeHmacSignature(content, options.secret);
|
|
100
83
|
return `${content}.${signature}`;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Encodes raw bytes into unpadded URL-safe Base64 (RFC 4648 §5).
|
|
3
|
+
*/
|
|
4
|
+
export declare function base64UrlEncode(bytes: Uint8Array): string;
|
|
5
|
+
/**
|
|
6
|
+
* Generates cryptographically secure random bytes across Web, Expo/React Native, and Node.js.
|
|
7
|
+
* Falls back to Math.random() only when no CSPRNG is available.
|
|
8
|
+
*/
|
|
9
|
+
export declare function getRandomBytes(length: number): Uint8Array;
|
|
10
|
+
/**
|
|
11
|
+
* Generates cryptographically secure random bytes, throwing if Web Crypto CSPRNG is unavailable.
|
|
12
|
+
*/
|
|
13
|
+
export declare function requireSecureRandomBytes(length: number, errorMessage?: string): Uint8Array;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.base64UrlEncode = base64UrlEncode;
|
|
4
|
+
exports.getRandomBytes = getRandomBytes;
|
|
5
|
+
exports.requireSecureRandomBytes = requireSecureRandomBytes;
|
|
6
|
+
const B64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
7
|
+
/**
|
|
8
|
+
* Encodes raw bytes into unpadded URL-safe Base64 (RFC 4648 §5).
|
|
9
|
+
*/
|
|
10
|
+
function base64UrlEncode(bytes) {
|
|
11
|
+
let result = '';
|
|
12
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
13
|
+
const first = bytes[i];
|
|
14
|
+
const second = bytes[i + 1];
|
|
15
|
+
const third = bytes[i + 2];
|
|
16
|
+
result += B64URL_ALPHABET[first >> 2];
|
|
17
|
+
result +=
|
|
18
|
+
B64URL_ALPHABET[((first & 3) << 4) | (second === undefined ? 0 : second >> 4)];
|
|
19
|
+
if (second !== undefined) {
|
|
20
|
+
result +=
|
|
21
|
+
B64URL_ALPHABET[((second & 15) << 2) | (third === undefined ? 0 : third >> 6)];
|
|
22
|
+
}
|
|
23
|
+
if (third !== undefined) {
|
|
24
|
+
result += B64URL_ALPHABET[third & 63];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Generates cryptographically secure random bytes across Web, Expo/React Native, and Node.js.
|
|
31
|
+
* Falls back to Math.random() only when no CSPRNG is available.
|
|
32
|
+
*/
|
|
33
|
+
function getRandomBytes(length) {
|
|
34
|
+
const cryptoObj = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
35
|
+
if (cryptoObj?.getRandomValues) {
|
|
36
|
+
try {
|
|
37
|
+
return cryptoObj.getRandomValues(new Uint8Array(length));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Fallback below
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
// Dynamic fallback for Node.js environments without globalThis.crypto
|
|
45
|
+
const nodeCrypto = globalThis.process?.versions?.node
|
|
46
|
+
? globalThis.require('node:crypto')
|
|
47
|
+
: null;
|
|
48
|
+
if (nodeCrypto?.randomBytes) {
|
|
49
|
+
return new Uint8Array(nodeCrypto.randomBytes(length));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Fallback ignored
|
|
54
|
+
}
|
|
55
|
+
const fallback = new Uint8Array(length);
|
|
56
|
+
for (let i = 0; i < length; i++) {
|
|
57
|
+
fallback[i] = Math.floor(Math.random() * 256);
|
|
58
|
+
}
|
|
59
|
+
return fallback;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Generates cryptographically secure random bytes, throwing if Web Crypto CSPRNG is unavailable.
|
|
63
|
+
*/
|
|
64
|
+
function requireSecureRandomBytes(length, errorMessage = 'Secure random number generation is unavailable.') {
|
|
65
|
+
const cryptoObj = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
66
|
+
if (!cryptoObj?.getRandomValues) {
|
|
67
|
+
throw new Error(errorMessage);
|
|
68
|
+
}
|
|
69
|
+
return cryptoObj.getRandomValues(new Uint8Array(length));
|
|
70
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface OAuthKeyValueStorage {
|
|
2
|
+
getItem(key: string): Promise<unknown>;
|
|
3
|
+
setItem(key: string, value: unknown): Promise<void>;
|
|
4
|
+
removeItem(key: string): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export interface OAuthTokenStore<TTokens, TUser> {
|
|
7
|
+
getTokens(): Promise<TTokens | null>;
|
|
8
|
+
setTokens(tokens: TTokens): Promise<void>;
|
|
9
|
+
removeTokens(): Promise<void>;
|
|
10
|
+
getUser(): Promise<TUser | null>;
|
|
11
|
+
setUser(user: TUser | null): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
export declare function createInMemoryOAuthTokenStore<TTokens, TUser>(): OAuthTokenStore<TTokens, TUser>;
|
|
14
|
+
export declare function createOAuthTokenStore<TTokens, TUser>(storage: OAuthKeyValueStorage, prefix: string, validateTokens: (value: unknown) => value is TTokens, validateUser: (value: unknown) => value is TUser): OAuthTokenStore<TTokens, TUser>;
|
|
15
|
+
export interface OAuthTokenErrorPayload {
|
|
16
|
+
error?: string;
|
|
17
|
+
error_description?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function parseOAuthTokenResponse<T extends OAuthTokenErrorPayload = Record<string, any>>(response: Response, providerLabel: string): Promise<T>;
|
|
20
|
+
export declare function throwOAuthError(payload: OAuthTokenErrorPayload, status: number, providerLabel: string): never;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createInMemoryOAuthTokenStore = createInMemoryOAuthTokenStore;
|
|
4
|
+
exports.createOAuthTokenStore = createOAuthTokenStore;
|
|
5
|
+
exports.parseOAuthTokenResponse = parseOAuthTokenResponse;
|
|
6
|
+
exports.throwOAuthError = throwOAuthError;
|
|
7
|
+
function createInMemoryOAuthTokenStore() {
|
|
8
|
+
let storedTokens = null;
|
|
9
|
+
let storedUser = null;
|
|
10
|
+
return {
|
|
11
|
+
getTokens: async () => storedTokens,
|
|
12
|
+
setTokens: async (tokens) => {
|
|
13
|
+
storedTokens = tokens;
|
|
14
|
+
},
|
|
15
|
+
removeTokens: async () => {
|
|
16
|
+
storedTokens = null;
|
|
17
|
+
},
|
|
18
|
+
getUser: async () => storedUser,
|
|
19
|
+
setUser: async (user) => {
|
|
20
|
+
storedUser = user;
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function createOAuthTokenStore(storage, prefix, validateTokens, validateUser) {
|
|
25
|
+
const tokensKey = `${prefix}-tokens`;
|
|
26
|
+
const userKey = `${prefix}-user`;
|
|
27
|
+
return {
|
|
28
|
+
getTokens: async () => {
|
|
29
|
+
const raw = await storage.getItem(tokensKey);
|
|
30
|
+
return validateTokens(raw) ? raw : null;
|
|
31
|
+
},
|
|
32
|
+
setTokens: (tokens) => storage.setItem(tokensKey, tokens),
|
|
33
|
+
removeTokens: () => storage.removeItem(tokensKey),
|
|
34
|
+
getUser: async () => {
|
|
35
|
+
const raw = await storage.getItem(userKey);
|
|
36
|
+
return validateUser(raw) ? raw : null;
|
|
37
|
+
},
|
|
38
|
+
setUser: async (user) => {
|
|
39
|
+
if (user) {
|
|
40
|
+
await storage.setItem(userKey, user);
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
await storage.removeItem(userKey);
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
async function parseOAuthTokenResponse(response, providerLabel) {
|
|
49
|
+
try {
|
|
50
|
+
return (await response.json());
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
throw new Error(`${providerLabel} OAuth request failed (${response.status}).`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function throwOAuthError(payload, status, providerLabel) {
|
|
57
|
+
throw new Error(payload.error_description ||
|
|
58
|
+
payload.error ||
|
|
59
|
+
`${providerLabel} OAuth request failed (${status}).`);
|
|
60
|
+
}
|
package/dist/utils/sql.d.ts
CHANGED
|
@@ -7,3 +7,11 @@ export declare function escapeIdentifier(identifier: string): string;
|
|
|
7
7
|
* (e.g. FTS5 index and shadow tables, sync outbox, local session/key stores, sqlite/android internals).
|
|
8
8
|
*/
|
|
9
9
|
export declare function isInternalTable(tableName: string): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Determines whether a SQLite statement is a read-only query (SELECT/WITH/EXPLAIN or non-mutating PRAGMA).
|
|
12
|
+
*/
|
|
13
|
+
export declare function isReadQuery(sql: string): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Extracts a required document/row ID from a record using primaryKey, an optional fallback ID, or `id`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function extractDocumentId(row: any, primaryKey: string, fallbackId?: unknown, providerLabel?: string): string;
|
package/dist/utils/sql.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.escapeIdentifier = escapeIdentifier;
|
|
4
4
|
exports.isInternalTable = isInternalTable;
|
|
5
|
+
exports.isReadQuery = isReadQuery;
|
|
6
|
+
exports.extractDocumentId = extractDocumentId;
|
|
5
7
|
/**
|
|
6
8
|
* Safely escape a SQL identifier (table name or column name) with double quotes.
|
|
7
9
|
*/
|
|
@@ -28,3 +30,24 @@ function isInternalTable(tableName) {
|
|
|
28
30
|
return true;
|
|
29
31
|
return false;
|
|
30
32
|
}
|
|
33
|
+
const READ_QUERY_REGEX = /^(?:SELECT|WITH|EXPLAIN)\b/i;
|
|
34
|
+
const READ_ONLY_PRAGMA_REGEX = /^PRAGMA\b/i;
|
|
35
|
+
const MUTATING_PRAGMA_REGEX = /=|wal_checkpoint|shrink_memory|optimize/i;
|
|
36
|
+
/**
|
|
37
|
+
* Determines whether a SQLite statement is a read-only query (SELECT/WITH/EXPLAIN or non-mutating PRAGMA).
|
|
38
|
+
*/
|
|
39
|
+
function isReadQuery(sql) {
|
|
40
|
+
if (READ_QUERY_REGEX.test(sql))
|
|
41
|
+
return true;
|
|
42
|
+
return READ_ONLY_PRAGMA_REGEX.test(sql) && !MUTATING_PRAGMA_REGEX.test(sql);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Extracts a required document/row ID from a record using primaryKey, an optional fallback ID, or `id`.
|
|
46
|
+
*/
|
|
47
|
+
function extractDocumentId(row, primaryKey, fallbackId, providerLabel = 'Remote') {
|
|
48
|
+
const id = row?.[primaryKey] ?? fallbackId ?? row?.id;
|
|
49
|
+
if (id === undefined || id === null || String(id).length === 0) {
|
|
50
|
+
throw new Error(`${providerLabel} change is missing its document ID.`);
|
|
51
|
+
}
|
|
52
|
+
return String(id);
|
|
53
|
+
}
|
package/package.json
CHANGED