local-lite 2.0.3 → 2.0.5

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.
@@ -3,41 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GoogleDriveBackupClient = exports.GoogleDriveBackupStorage = exports.GOOGLE_DRIVE_SCOPE = void 0;
4
4
  exports.createInMemoryGoogleDriveTokenStore = createInMemoryGoogleDriveTokenStore;
5
5
  exports.createGoogleDriveTokenStore = createGoogleDriveTokenStore;
6
- const sha2_js_1 = require("@noble/hashes/sha2.js");
7
- const utils_js_1 = require("@noble/hashes/utils.js");
8
6
  const operations_js_1 = require("./operations.js");
7
+ const oauth_js_1 = require("../utils/oauth.js");
9
8
  const GOOGLE_API = 'https://www.googleapis.com/drive/v3';
10
9
  const GOOGLE_UPLOAD_API = 'https://www.googleapis.com/upload/drive/v3';
11
10
  const GOOGLE_AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth';
12
11
  const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
13
12
  exports.GOOGLE_DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.file';
14
13
  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
14
  function validateGoogleTokens(value) {
42
15
  if (!value || typeof value !== 'object')
43
16
  return false;
@@ -70,12 +43,7 @@ function createGoogleDriveTokenStore(storage, key = 'local-lite-google-drive-bac
70
43
  };
71
44
  }
72
45
  async function parseTokenResponse(response) {
73
- try {
74
- return (await response.json());
75
- }
76
- catch {
77
- throw new Error(`Google OAuth request failed (${response.status}).`);
78
- }
46
+ return (0, oauth_js_1.parseOAuthTokenResponse)(response, 'Google');
79
47
  }
80
48
  function createStoredTokens(payload, prior) {
81
49
  if (!payload.access_token) {
@@ -88,9 +56,7 @@ function createStoredTokens(payload, prior) {
88
56
  };
89
57
  }
90
58
  function throwTokenError(payload, status) {
91
- throw new Error(payload.error_description ||
92
- payload.error ||
93
- `Google OAuth request failed (${status}).`);
59
+ return (0, oauth_js_1.throwOAuthError)(payload, status, 'Google');
94
60
  }
95
61
  async function parseApiError(response) {
96
62
  let detail = '';
@@ -269,15 +235,7 @@ class GoogleDriveBackupClient {
269
235
  this.notify(connected);
270
236
  return connected;
271
237
  }
272
- const randomBytes = this.options.randomBytes ?? secureRandomBytes;
273
- const verifierBytes = randomBytes(32);
274
- const stateBytes = randomBytes(32);
275
- if (verifierBytes.length !== 32 || stateBytes.length !== 32) {
276
- throw new Error('The randomBytes provider returned an invalid number of bytes.');
277
- }
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);
238
+ const { codeVerifier, codeChallenge, state } = (0, oauth_js_1.createPkceChallengePair)(this.options.randomBytes);
281
239
  const authorizationParams = new URLSearchParams({
282
240
  client_id: this.options.clientId,
283
241
  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
- const crypto = globalThis.crypto;
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) {
@@ -39,20 +39,7 @@ const jsx_runtime_1 = require("react/jsx-runtime");
39
39
  const react_1 = __importStar(require("react"));
40
40
  const theme_js_1 = require("../react/theme.js");
41
41
  const sql_js_1 = require("../utils/sql.js");
42
- let RN;
43
- try {
44
- RN = require('react-native');
45
- }
46
- catch {
47
- // Web / DOM environment
48
- }
49
- let RNSafeArea;
50
- try {
51
- RNSafeArea = require('react-native-safe-area-context');
52
- }
53
- catch {
54
- // Web / DOM environment or not installed
55
- }
42
+ const shared_js_1 = require("./shared.js");
56
43
  const now = () => typeof performance !== 'undefined' && typeof performance.now === 'function'
57
44
  ? performance.now()
58
45
  : Date.now();
@@ -573,7 +560,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
573
560
  const [progress, setProgress] = (0, react_1.useState)(0);
574
561
  const [results, setResults] = (0, react_1.useState)([]);
575
562
  const [copied, setCopied] = (0, react_1.useState)(false);
576
- const systemColorScheme = RN?.useColorScheme ? RN.useColorScheme() : null;
563
+ const systemColorScheme = shared_js_1.RN?.useColorScheme ? shared_js_1.RN.useColorScheme() : null;
577
564
  const currentTheme = react_1.default.useMemo(() => (0, theme_js_1.resolveSyncTheme)(theme, systemColorScheme), [theme, systemColorScheme]);
578
565
  const startBenchmark = async () => {
579
566
  if (!client)
@@ -600,7 +587,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
600
587
  return;
601
588
  const report = [
602
589
  '# ⚡ local-lite SQLite Benchmark Report',
603
- `- Platform: ${RN && RN.Platform ? RN.Platform.OS : 'web'}`,
590
+ `- Platform: ${shared_js_1.RN && shared_js_1.RN.Platform ? shared_js_1.RN.Platform.OS : 'web'}`,
604
591
  `- Date: ${new Date().toLocaleString()}`,
605
592
  ...(results[0]?.note ? [`- App dataset: ${results[0].note}`] : []),
606
593
  '',
@@ -610,8 +597,8 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
610
597
  ].join('\n');
611
598
  let isCopied = false;
612
599
  try {
613
- if (RN && RN.Clipboard && typeof RN.Clipboard.setString === 'function') {
614
- RN.Clipboard.setString(report);
600
+ if (shared_js_1.RN && shared_js_1.RN.Clipboard && typeof shared_js_1.RN.Clipboard.setString === 'function') {
601
+ shared_js_1.RN.Clipboard.setString(report);
615
602
  isCopied = true;
616
603
  }
617
604
  }
@@ -629,9 +616,9 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
629
616
  if (!visible)
630
617
  return null;
631
618
  // React Native renderer (Full-height modal)
632
- if (RN && RN.View) {
633
- const { View, Text, TouchableOpacity, ScrollView, Modal, ActivityIndicator, Platform, StatusBar, } = RN;
634
- const SafeComp = RNSafeArea?.SafeAreaView || RN.SafeAreaView || View;
619
+ if (shared_js_1.RN && shared_js_1.RN.View) {
620
+ const { View, Text, TouchableOpacity, ScrollView, Modal, ActivityIndicator, Platform, StatusBar, } = shared_js_1.RN;
621
+ const SafeComp = shared_js_1.RNSafeArea?.SafeAreaView || shared_js_1.RN.SafeAreaView || View;
635
622
  const isAndroid = Platform?.OS === 'android';
636
623
  const statusBarHeight = isAndroid ? StatusBar?.currentHeight || 24 : 0;
637
624
  return ((0, jsx_runtime_1.jsx)(Modal, { visible: visible, animationType: "slide", presentationStyle: "fullScreen", statusBarTranslucent: true, onRequestClose: onDismiss, children: (0, jsx_runtime_1.jsxs)(SafeComp, { style: [styles.fullScreenSafe, { backgroundColor: currentTheme.bg }], edges: ['top', 'bottom', 'left', 'right'], children: [(0, jsx_runtime_1.jsxs)(View, { style: [
@@ -640,7 +627,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
640
627
  backgroundColor: currentTheme.surface,
641
628
  borderBottomColor: currentTheme.border,
642
629
  },
643
- !RNSafeArea?.SafeAreaView &&
630
+ !shared_js_1.RNSafeArea?.SafeAreaView &&
644
631
  isAndroid && { paddingTop: statusBarHeight + 10 },
645
632
  ], children: [(0, jsx_runtime_1.jsxs)(View, { style: { flex: 1 }, children: [(0, jsx_runtime_1.jsx)(Text, { style: [styles.topBarTitle, { color: currentTheme.text }], children: "\u26A1 SQLite Benchmark" }), (0, jsx_runtime_1.jsx)(Text, { style: [styles.topBarSub, { color: currentTheme.textMuted }], children: "Inbuilt local-lite throughput & ACID test suite" })] }), (0, jsx_runtime_1.jsx)(TouchableOpacity, { onPress: onDismiss, style: [
646
633
  styles.closeCircle,
@@ -718,7 +705,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
718
705
  backgroundColor: currentTheme.surface,
719
706
  borderTopColor: currentTheme.border,
720
707
  },
721
- !RNSafeArea?.SafeAreaView && isAndroid && { paddingBottom: 32 },
708
+ !shared_js_1.RNSafeArea?.SafeAreaView && isAndroid && { paddingBottom: 32 },
722
709
  ], children: [(0, jsx_runtime_1.jsx)(TouchableOpacity, { onPress: startBenchmark, disabled: isRunning, style: [
723
710
  styles.footerBtn,
724
711
  { backgroundColor: isRunning ? '#6D28D9' : '#8B5CF6' },
@@ -869,32 +856,24 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
869
856
  cursor: 'pointer',
870
857
  }, children: copied ? '✓ Copied' : 'Copy Report' }))] })] }));
871
858
  }
872
- const styles = RN && RN.StyleSheet
873
- ? RN.StyleSheet.create({
859
+ const styles = shared_js_1.RN && shared_js_1.RN.StyleSheet
860
+ ? shared_js_1.RN.StyleSheet.create({
874
861
  fullScreenSafe: {
875
- flex: 1,
876
- height: '100%',
862
+ ...shared_js_1.devtoolsBaseRNStyles.fullScreenSafe,
877
863
  backgroundColor: '#111827',
878
864
  },
879
865
  topBar: {
880
- flexDirection: 'row',
881
- alignItems: 'center',
882
- justifyContent: 'space-between',
883
- paddingHorizontal: 18,
884
- paddingVertical: 14,
866
+ ...shared_js_1.devtoolsBaseRNStyles.topBar,
885
867
  backgroundColor: '#1F2937',
886
- borderBottomWidth: 1,
887
868
  borderBottomColor: '#374151',
888
869
  },
889
870
  topBarTitle: {
871
+ ...shared_js_1.devtoolsBaseRNStyles.topBarTitle,
890
872
  color: '#F9FAFB',
891
- fontSize: 17,
892
- fontWeight: '700',
893
873
  },
894
874
  topBarSub: {
875
+ ...shared_js_1.devtoolsBaseRNStyles.topBarSub,
895
876
  color: '#9CA3AF',
896
- fontSize: 11,
897
- marginTop: 2,
898
877
  },
899
878
  closeCircle: {
900
879
  width: 32,
@@ -6,20 +6,7 @@ const react_1 = require("react");
6
6
  const status_js_1 = require("../react/status.js");
7
7
  const BenchmarkModal_js_1 = require("./BenchmarkModal.js");
8
8
  const theme_js_1 = require("../react/theme.js");
9
- let RN;
10
- try {
11
- RN = require('react-native');
12
- }
13
- catch {
14
- // Web / DOM environment
15
- }
16
- let RNSafeArea;
17
- try {
18
- RNSafeArea = require('react-native-safe-area-context');
19
- }
20
- catch {
21
- // Web / DOM environment or not installed
22
- }
9
+ const shared_js_1 = require("./shared.js");
23
10
  const BENCHMARK_DESCRIPTION = 'Runs automated stress tests directly validating local-lite client APIs: atomic batch ingestion, indexing, ACID rollback isolation, outbox queues, and non-blocking WAL concurrency.';
24
11
  /**
25
12
  * Universal Developer Inspector Component for local-lite.
@@ -32,7 +19,7 @@ function SyncInspector({ client, position = 'bottom-right', variant = 'pill', in
32
19
  const status = (0, status_js_1.useSyncStatus)(client);
33
20
  const [metrics, setMetrics] = (0, react_1.useState)(null);
34
21
  const [actionMessage, setActionMessage] = (0, react_1.useState)(null);
35
- const systemColorScheme = RN?.useColorScheme ? RN.useColorScheme() : null;
22
+ const systemColorScheme = shared_js_1.RN?.useColorScheme ? shared_js_1.RN.useColorScheme() : null;
36
23
  const currentTheme = (0, react_1.useMemo)(() => (0, theme_js_1.resolveSyncTheme)(theme, systemColorScheme), [theme, systemColorScheme]);
37
24
  (0, react_1.useEffect)(() => {
38
25
  if (!client || !isOpen)
@@ -83,8 +70,8 @@ function SyncInspector({ client, position = 'bottom-right', variant = 'pill', in
83
70
  }
84
71
  });
85
72
  const message = 'This permanently removes queued pending, processing, and failed mutations. Local database records are not deleted.';
86
- if (RN?.Alert?.alert) {
87
- RN.Alert.alert('Clear stuck outbox?', message, [
73
+ if (shared_js_1.RN?.Alert?.alert) {
74
+ shared_js_1.RN.Alert.alert('Clear stuck outbox?', message, [
88
75
  { text: 'Cancel', style: 'cancel' },
89
76
  {
90
77
  text: 'Clear outbox',
@@ -206,9 +193,9 @@ function SyncInspector({ client, position = 'bottom-right', variant = 'pill', in
206
193
  if (!client)
207
194
  return null;
208
195
  // React Native Renderer
209
- if (RN && RN.View) {
210
- const { View, Text, TouchableOpacity, ScrollView, Modal, Platform, StatusBar, } = RN;
211
- const SafeComp = RNSafeArea?.SafeAreaView || RN.SafeAreaView || View;
196
+ if (shared_js_1.RN && shared_js_1.RN.View) {
197
+ const { View, Text, TouchableOpacity, ScrollView, Modal, Platform, StatusBar, } = shared_js_1.RN;
198
+ const SafeComp = shared_js_1.RNSafeArea?.SafeAreaView || shared_js_1.RN.SafeAreaView || View;
212
199
  const isAndroid = Platform?.OS === 'android';
213
200
  const statusBarHeight = isAndroid ? StatusBar?.currentHeight || 24 : 0;
214
201
  const pillPosStyle = isInline
@@ -257,7 +244,7 @@ function SyncInspector({ client, position = 'bottom-right', variant = 'pill', in
257
244
  backgroundColor: currentTheme.surface,
258
245
  borderBottomColor: currentTheme.border,
259
246
  },
260
- !RNSafeArea?.SafeAreaView &&
247
+ !shared_js_1.RNSafeArea?.SafeAreaView &&
261
248
  isAndroid && { paddingTop: statusBarHeight + 10 },
262
249
  ], children: [(0, jsx_runtime_1.jsxs)(View, { style: { flex: 1 }, children: [(0, jsx_runtime_1.jsx)(Text, { style: [rnStyles.topBarTitle, { color: currentTheme.text }], children: title }), (0, jsx_runtime_1.jsx)(Text, { style: [
263
250
  rnStyles.topBarSub,
@@ -616,28 +603,9 @@ function SyncInspector({ client, position = 'bottom-right', variant = 'pill', in
616
603
  fontWeight: 700,
617
604
  }, children: status.pendingCount }))] })) })), enableBenchmark && !onOpenBenchmark && ((0, jsx_runtime_1.jsx)(BenchmarkModal_js_1.BenchmarkModal, { client: client, visible: isBenchmarkModalOpen, onDismiss: () => setIsBenchmarkModalOpen(false), theme: theme }))] }));
618
605
  }
619
- const rnStyles = RN && RN.StyleSheet
620
- ? RN.StyleSheet.create({
621
- fullScreenSafe: {
622
- flex: 1,
623
- height: '100%',
624
- },
625
- topBar: {
626
- flexDirection: 'row',
627
- alignItems: 'center',
628
- justifyContent: 'space-between',
629
- paddingHorizontal: 18,
630
- paddingVertical: 14,
631
- borderBottomWidth: 1,
632
- },
633
- topBarTitle: {
634
- fontSize: 17,
635
- fontWeight: '700',
636
- },
637
- topBarSub: {
638
- fontSize: 11,
639
- marginTop: 2,
640
- },
606
+ const rnStyles = shared_js_1.RN && shared_js_1.RN.StyleSheet
607
+ ? shared_js_1.RN.StyleSheet.create({
608
+ ...shared_js_1.devtoolsBaseRNStyles,
641
609
  statusBadge: {
642
610
  paddingHorizontal: 8,
643
611
  paddingVertical: 3,
@@ -0,0 +1,25 @@
1
+ declare let RN: any;
2
+ declare let RNSafeArea: any;
3
+ export { RN, RNSafeArea };
4
+ export declare const devtoolsBaseRNStyles: {
5
+ fullScreenSafe: {
6
+ flex: number;
7
+ height: string;
8
+ };
9
+ topBar: {
10
+ flexDirection: 'row';
11
+ alignItems: 'center';
12
+ justifyContent: 'space-between';
13
+ paddingHorizontal: number;
14
+ paddingVertical: number;
15
+ borderBottomWidth: number;
16
+ };
17
+ topBarTitle: {
18
+ fontSize: number;
19
+ fontWeight: '700';
20
+ };
21
+ topBarSub: {
22
+ fontSize: number;
23
+ marginTop: number;
24
+ };
25
+ };
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.devtoolsBaseRNStyles = exports.RNSafeArea = exports.RN = void 0;
4
+ let RN;
5
+ try {
6
+ exports.RN = RN = require('react-native');
7
+ }
8
+ catch {
9
+ // Web / DOM environment
10
+ }
11
+ let RNSafeArea;
12
+ try {
13
+ exports.RNSafeArea = RNSafeArea = require('react-native-safe-area-context');
14
+ }
15
+ catch {
16
+ // Web / DOM environment or not installed
17
+ }
18
+ exports.devtoolsBaseRNStyles = {
19
+ fullScreenSafe: {
20
+ flex: 1,
21
+ height: '100%',
22
+ },
23
+ topBar: {
24
+ flexDirection: 'row',
25
+ alignItems: 'center',
26
+ justifyContent: 'space-between',
27
+ paddingHorizontal: 18,
28
+ paddingVertical: 14,
29
+ borderBottomWidth: 1,
30
+ },
31
+ topBarTitle: {
32
+ fontSize: 17,
33
+ fontWeight: '700',
34
+ },
35
+ topBarSub: {
36
+ fontSize: 11,
37
+ marginTop: 2,
38
+ },
39
+ };
@@ -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
  */
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRandomBytes = 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 declare function base64UrlEncode(bytes: Uint8Array): string;
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 = 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,29 @@
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;
21
+ export interface PkceChallengePair {
22
+ codeVerifier: string;
23
+ codeChallenge: string;
24
+ state: string;
25
+ }
26
+ /**
27
+ * Generates a PKCE S256 verifier/challenge pair and an OAuth state token using a CSPRNG.
28
+ */
29
+ export declare function createPkceChallengePair(randomBytes?: (length: number) => Uint8Array): PkceChallengePair;