Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
966d9d0456 | ||
|
|
ccff136edb | ||
|
|
8f34c2de73 | ||
|
|
ca75df8bb4 | ||
|
|
c747f1f315 | ||
|
|
2a66b5eeec | ||
|
|
fa9688b17e | ||
|
|
a0e18c34d6 | ||
|
|
995c3f526c |
10
.gitignore
vendored
10
.gitignore
vendored
@@ -1,6 +1,6 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
nostr-tools/
|
||||
|
||||
|
||||
# IDE and OS files
|
||||
.idea/
|
||||
@@ -18,10 +18,4 @@ Thumbs.db
|
||||
log.txt
|
||||
Trash/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
|
||||
# Aider files
|
||||
.aider.chat.history.md
|
||||
.aider.input.history
|
||||
.aider.tags.cache.v3/
|
||||
nostr-login/
|
||||
128
README.md
128
README.md
@@ -1,62 +1,86 @@
|
||||
Nostr_Login_Lite
|
||||
===========
|
||||
|
||||
## Floating Tab API
|
||||
## API
|
||||
|
||||
Configure persistent floating tab for login/logout:
|
||||
Complete configuration showing all available options:
|
||||
|
||||
```javascript
|
||||
await NOSTR_LOGIN_LITE.init({
|
||||
// Set the initial theme (default: 'default')
|
||||
theme: 'dark', // Choose from 'default' or 'dark'
|
||||
await window.NOSTR_LOGIN_LITE.init({
|
||||
// Theme configuration
|
||||
theme: 'default', // 'default' | 'dark' | custom theme name
|
||||
|
||||
// Standard configuration options
|
||||
// 🔐 Authentication persistence configuration
|
||||
persistence: true, // Enable persistent authentication (default: true)
|
||||
isolateSession: false, // Use sessionStorage for per-tab isolation (default: false = localStorage)
|
||||
|
||||
// Relay configuration
|
||||
relays: ['wss://relay.damus.io', 'wss://nos.lol'],
|
||||
|
||||
// Authentication methods
|
||||
methods: {
|
||||
extension: true,
|
||||
local: true,
|
||||
readonly: true,
|
||||
connect: true,
|
||||
otp: true
|
||||
extension: true, // Browser extensions (Alby, nos2x, etc.)
|
||||
local: true, // Manual key entry & generation
|
||||
readonly: true, // Read-only mode (no signing)
|
||||
connect: true, // NIP-46 remote signers
|
||||
otp: false // OTP/DM authentication (not implemented yet)
|
||||
},
|
||||
|
||||
// Floating tab configuration (now uses theme-aware text icons)
|
||||
// Floating tab configuration
|
||||
floatingTab: {
|
||||
enabled: true,
|
||||
hPosition: 0.95, // 0.0-1.0 or '95%' from left
|
||||
vPosition: 0.5, // 0.0-1.0 or '50%' from top
|
||||
enabled: true, // Show/hide floating login tab
|
||||
hPosition: 0.95, // 0.0 = left edge, 1.0 = right edge
|
||||
vPosition: 0.1, // 0.0 = top edge, 1.0 = bottom edge
|
||||
offset: { x: 0, y: 0 }, // Fine-tune positioning (pixels)
|
||||
|
||||
appearance: {
|
||||
style: 'pill', // 'pill', 'square', 'circle', 'minimal'
|
||||
theme: 'auto', // 'auto' follows main theme
|
||||
icon: '[LOGIN]', // Now uses text-based icons like [LOGIN], [KEY], [NET]
|
||||
text: 'Login'
|
||||
style: 'pill', // 'pill' | 'square' | 'circle'
|
||||
theme: 'auto', // 'auto' | 'light' | 'dark'
|
||||
icon: '[LOGIN]', // Text-based icon
|
||||
text: 'Sign In', // Button text
|
||||
iconOnly: false // Show icon only (no text)
|
||||
},
|
||||
|
||||
behavior: {
|
||||
hideWhenAuthenticated: false,
|
||||
showUserInfo: true,
|
||||
autoSlide: true
|
||||
},
|
||||
animation: {
|
||||
slideDirection: 'auto' // 'auto', 'left', 'right', 'up', 'down'
|
||||
hideWhenAuthenticated: false, // Keep visible after login
|
||||
showUserInfo: true, // Show user info when authenticated
|
||||
autoSlide: true, // Slide animation on hover
|
||||
persistent: false // Persist across page reloads
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// After initialization, you can switch themes dynamically:
|
||||
NOSTR_LOGIN_LITE.switchTheme('dark');
|
||||
NOSTR_LOGIN_LITE.switchTheme('default');
|
||||
|
||||
// Or customize individual theme variables:
|
||||
NOSTR_LOGIN_LITE.setThemeVariable('--nl-accent-color', '#00ff00');
|
||||
// Control Methods
|
||||
NOSTR_LOGIN_LITE.launch(); // Open login modal
|
||||
NOSTR_LOGIN_LITE.logout(); // Clear authentication state
|
||||
NOSTR_LOGIN_LITE.switchTheme('dark'); // Change theme
|
||||
NOSTR_LOGIN_LITE.showFloatingTab(); // Show floating tab
|
||||
NOSTR_LOGIN_LITE.hideFloatingTab(); // Hide floating tab
|
||||
NOSTR_LOGIN_LITE.updateFloatingTab(options); // Update floating tab options
|
||||
NOSTR_LOGIN_LITE.toggleFloatingTab(); // Toggle floating tab visibility
|
||||
|
||||
// Get Authentication State (Single Source of Truth)
|
||||
const authState = NOSTR_LOGIN_LITE.getAuthState();
|
||||
const isAuthenticated = !!authState;
|
||||
const userInfo = authState; // Contains { method, pubkey, etc. }
|
||||
```
|
||||
|
||||
Control methods:
|
||||
```javascript
|
||||
NOSTR_LOGIN_LITE.showFloatingTab();
|
||||
NOSTR_LOGIN_LITE.hideFloatingTab();
|
||||
NOSTR_LOGIN_LITE.updateFloatingTab(options);
|
||||
NOSTR_LOGIN_LITE.destroyFloatingTab();
|
||||
```
|
||||
**Authentication Persistence:**
|
||||
|
||||
Two-tier configuration system:
|
||||
|
||||
1. **`persistence: boolean`** - Master switch for authentication persistence
|
||||
- `true` (default): Save authentication state for automatic restore
|
||||
- `false`: No persistence - user must login fresh every time
|
||||
|
||||
2. **`isolateSession: boolean`** - Storage location when persistence is enabled
|
||||
- `false` (default): Use localStorage - shared across tabs/windows
|
||||
- `true`: Use sessionStorage - isolated per tab/window
|
||||
|
||||
**Use Cases for Session Isolation (`isolateSession: true`):**
|
||||
- Multi-tenant applications where different tabs need different users
|
||||
- Testing environments requiring separate authentication per tab
|
||||
- Privacy-focused applications that shouldn't share login state across tabs
|
||||
|
||||
## Embedded Modal API
|
||||
|
||||
@@ -81,3 +105,31 @@ const modal = NOSTR_LOGIN_LITE.embed('#login-container', {
|
||||
```
|
||||
|
||||
Container can be CSS selector or DOM element. Modal renders inline without backdrop overlay.
|
||||
|
||||
## Logout API
|
||||
|
||||
To log out users and clear authentication state:
|
||||
|
||||
```javascript
|
||||
// Unified logout method - works for all authentication methods
|
||||
window.NOSTR_LOGIN_LITE.logout();
|
||||
```
|
||||
|
||||
This will:
|
||||
- Clear persistent authentication data from localStorage
|
||||
- Dispatch `nlLogout` event for custom cleanup
|
||||
- Reset the authentication state across all components
|
||||
|
||||
### Event Handling
|
||||
|
||||
Listen for logout events in your application:
|
||||
|
||||
```javascript
|
||||
window.addEventListener('nlLogout', () => {
|
||||
console.log('User logged out');
|
||||
// Clear your application's UI state
|
||||
// Redirect to login page, etc.
|
||||
});
|
||||
```
|
||||
|
||||
The logout system works consistently across all authentication methods (extension, local keys, NIP-46, etc.) and all UI components (floating tab, modal, embedded).
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
}
|
||||
|
||||
#login-button:hover {
|
||||
background: #0052a3;
|
||||
opacity: 0.8;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -49,9 +49,12 @@
|
||||
<script src="../lite/nostr-lite.js"></script>
|
||||
|
||||
<script>
|
||||
let isAuthenticated = false;
|
||||
let currentUser = null;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await window.NOSTR_LOGIN_LITE.init({
|
||||
theme: 'default',
|
||||
|
||||
methods: {
|
||||
extension: true,
|
||||
local: true,
|
||||
@@ -65,10 +68,66 @@
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('login-button').addEventListener('click', () => {
|
||||
window.NOSTR_LOGIN_LITE.launch('login');
|
||||
});
|
||||
// Listen for authentication events
|
||||
window.addEventListener('nlMethodSelected', handleAuthEvent);
|
||||
window.addEventListener('nlLogout', handleLogoutEvent);
|
||||
|
||||
// Check for existing authentication state
|
||||
checkAuthState();
|
||||
|
||||
// Initialize button
|
||||
updateButtonState();
|
||||
});
|
||||
|
||||
function handleAuthEvent(event) {
|
||||
const { pubkey, method } = event.detail;
|
||||
console.log(`Authenticated with ${method}, pubkey: ${pubkey}`);
|
||||
|
||||
isAuthenticated = true;
|
||||
currentUser = event.detail;
|
||||
updateButtonState();
|
||||
}
|
||||
|
||||
function handleLogoutEvent() {
|
||||
console.log('Logout event received');
|
||||
|
||||
isAuthenticated = false;
|
||||
currentUser = null;
|
||||
updateButtonState();
|
||||
}
|
||||
|
||||
function checkAuthState() {
|
||||
// Check if user is already authenticated (from persistent storage)
|
||||
try {
|
||||
// Try to get public key - this will work if already authenticated
|
||||
window.nostr.getPublicKey().then(pubkey => {
|
||||
console.log('Found existing authentication, pubkey:', pubkey);
|
||||
isAuthenticated = true;
|
||||
currentUser = { pubkey, method: 'persistent' };
|
||||
updateButtonState();
|
||||
}).catch(error => {
|
||||
console.log('No existing authentication found:', error.message);
|
||||
// User is not authenticated, button stays in login state
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('No existing authentication found');
|
||||
// User is not authenticated, button stays in login state
|
||||
}
|
||||
}
|
||||
|
||||
function updateButtonState() {
|
||||
const button = document.getElementById('login-button');
|
||||
|
||||
if (isAuthenticated) {
|
||||
button.textContent = 'Logout';
|
||||
button.onclick = () => window.NOSTR_LOGIN_LITE.logout();
|
||||
button.style.background = '#dc3545'; // Red for logout
|
||||
} else {
|
||||
button.textContent = 'Login';
|
||||
button.onclick = () => window.NOSTR_LOGIN_LITE.launch('login');
|
||||
button.style.background = '#0066cc'; // Blue for login
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
methods: {
|
||||
extension: true,
|
||||
local: true,
|
||||
seedphrase: true,
|
||||
readonly: true,
|
||||
connect: true,
|
||||
remote: true,
|
||||
|
||||
@@ -51,19 +51,20 @@
|
||||
await window.NOSTR_LOGIN_LITE.init({
|
||||
theme: 'default',
|
||||
darkMode: false,
|
||||
relays: [relayUrl, 'wss://relay.damus.io'],
|
||||
methods: {
|
||||
extension: true,
|
||||
local: true,
|
||||
readonly: true,
|
||||
seedphrase: true,
|
||||
connect: true, // Enables "Nostr Connect" (NIP-46)
|
||||
remote: true, // Also needed for "Nostr Connect" compatibility
|
||||
otp: true // Enables "DM/OTP"
|
||||
},
|
||||
floatingTab: {
|
||||
enabled: true,
|
||||
hPosition: 0.80, // 95% from left
|
||||
vPosition: 0.01, // 50% from top (center)
|
||||
hPosition: .98, // 95% from left
|
||||
vPosition: 0, // 50% from top (center)
|
||||
getUserInfo: true, // Fetch user profiles
|
||||
getUserRelay: ['wss://relay.laantungir.net'], // Custom relays for profiles
|
||||
appearance: {
|
||||
style: 'minimal',
|
||||
theme: 'auto',
|
||||
@@ -88,6 +89,7 @@
|
||||
console.log('SUCCESS', 'NOSTR_LOGIN_LITE initialized successfully');
|
||||
|
||||
window.addEventListener('nlMethodSelected', handleAuthEvent);
|
||||
window.addEventListener('nlLogout', handleLogoutEvent);
|
||||
|
||||
} catch (error) {
|
||||
console.log('ERROR', `Initialization failed: ${error.message}`);
|
||||
@@ -97,7 +99,7 @@
|
||||
|
||||
|
||||
function handleAuthEvent(event) {
|
||||
const {pubkey, method, error } = event.detail;
|
||||
const { pubkey, method, error } = event.detail;
|
||||
console.log('INFO', `Auth event received: method=${method}`);
|
||||
|
||||
if (method && pubkey) {
|
||||
@@ -112,6 +114,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
function handleLogoutEvent() {
|
||||
console.log('INFO', 'Logout event received');
|
||||
// Clear local UI state
|
||||
userPubkey = null;
|
||||
document.getElementById('profile-name').textContent = '';
|
||||
document.getElementById('profile-about').textContent = '';
|
||||
document.getElementById('profile-pubkey').textContent = '';
|
||||
document.getElementById('profile-picture').src = '';
|
||||
}
|
||||
|
||||
// Load user profile using nostr-tools pool
|
||||
async function loadUserProfile() {
|
||||
if (!userPubkey) return;
|
||||
@@ -171,7 +183,7 @@
|
||||
async function logout() {
|
||||
console.log('INFO', 'Logging out...');
|
||||
try {
|
||||
await nlLite.logout();
|
||||
window.NOSTR_LOGIN_LITE.logout();
|
||||
console.log('SUCCESS', 'Logged out successfully');
|
||||
} catch (error) {
|
||||
console.log('ERROR', `Logout failed: ${error.message}`);
|
||||
|
||||
@@ -37,10 +37,11 @@
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await window.NOSTR_LOGIN_LITE.init({
|
||||
theme: 'dark',
|
||||
theme: 'default',
|
||||
methods: {
|
||||
extension: true,
|
||||
local: true,
|
||||
seedphrase:true,
|
||||
readonly: true,
|
||||
connect: true,
|
||||
remote: true,
|
||||
@@ -48,12 +49,11 @@
|
||||
},
|
||||
floatingTab: {
|
||||
enabled: true,
|
||||
hPosition: 0.7, // 0.0-1.0 or '95%' from left
|
||||
vPosition: 0.5, // 0.0-1.0 or '50%' from top
|
||||
hPosition: 1, // 0.0-1.0 or '95%' from left
|
||||
vPosition: 0, // 0.0-1.0 or '50%' from top
|
||||
appearance: {
|
||||
style: 'pill', // 'pill', 'square', 'circle', 'minimal'
|
||||
theme: 'auto', // 'auto' follows main theme
|
||||
icon: '[LOGIN]', // Now uses text-based icons like [LOGIN], [KEY], [NET]
|
||||
style: 'square', // 'pill', 'square', 'circle', 'minimal'
|
||||
// icon: '[LOGIN]', // Now uses text-based icons like [LOGIN], [KEY], [NET]
|
||||
text: 'Login'
|
||||
},
|
||||
behavior: {
|
||||
|
||||
534
examples/session-isolation-test.html
Normal file
534
examples/session-isolation-test.html
Normal file
@@ -0,0 +1,534 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Session Isolation Test - NOSTR LOGIN LITE</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Courier New', monospace;
|
||||
margin: 20px;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.status-panel {
|
||||
background: #f8f9fa;
|
||||
border: 2px solid #dee2e6;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.info-box {
|
||||
background: #e7f3ff;
|
||||
border: 2px solid #0066cc;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.isolated-notice {
|
||||
background: #f8d7da;
|
||||
border: 2px solid #dc3545;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
button {
|
||||
background: white;
|
||||
color: black;
|
||||
border: 2px solid black;
|
||||
border-radius: 8px;
|
||||
padding: 10px 20px;
|
||||
margin: 5px;
|
||||
cursor: pointer;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
border-color: red;
|
||||
}
|
||||
|
||||
button:active {
|
||||
background: red;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.mode-indicator {
|
||||
font-weight: bold;
|
||||
padding: 8px 16px;
|
||||
border-radius: 4px;
|
||||
border: 2px solid #dc3545;
|
||||
background: #f8d7da;
|
||||
display: inline-block;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: #f8f9fa;
|
||||
border: 1px solid #e9ecef;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
overflow-x: auto;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>🔐 Session Isolation Test</h1>
|
||||
|
||||
<div class="info-box">
|
||||
<h3>📋 Test Instructions</h3>
|
||||
<ol>
|
||||
<li><strong>Isolated Session:</strong> Each tab/window has independent authentication</li>
|
||||
<li>Login in this tab/window - it will persist on refresh</li>
|
||||
<li>Open new windows/tabs - they will start unauthenticated</li>
|
||||
<li>Login with different users in different windows simultaneously</li>
|
||||
<li>Refresh any window - authentication persists within that window only</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div class="mode-indicator">
|
||||
🔒 ISOLATED MODE (sessionStorage)
|
||||
</div>
|
||||
|
||||
<div class="isolated-notice">
|
||||
<strong>🚨 Session Isolation Active:</strong>
|
||||
<p>This tab uses sessionStorage - authentication is isolated to this window only. Refreshing will maintain your login state, but other tabs/windows are independent.</p>
|
||||
</div>
|
||||
|
||||
<div class="status-panel">
|
||||
<h3>Authentication Status</h3>
|
||||
<div id="auth-status">Not authenticated</div>
|
||||
<div id="auth-details"></div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>Actions</h3>
|
||||
<button onclick="login()">Login</button>
|
||||
<button onclick="logout()">Logout</button>
|
||||
<button onclick="checkStatus()">Check Status</button>
|
||||
<button onclick="testSigning()">Test Signing</button>
|
||||
<button onclick="openNewWindow()">Open New Window</button>
|
||||
<button onclick="debugAuthentication()" style="border-color: orange;">Debug Auth State</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>Storage Inspector</h3>
|
||||
<button onclick="inspectStorage()">Inspect SessionStorage</button>
|
||||
<button onclick="clearStorage()">Clear Session Storage</button>
|
||||
<div id="storage-content"></div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>Test Results</h3>
|
||||
<div id="results"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="../lite/nostr.bundle.js"></script>
|
||||
<script src="../lite/nostr-lite.js"></script>
|
||||
|
||||
<script>
|
||||
let nostrLiteInstance = null;
|
||||
|
||||
// Initialize in isolated mode (always)
|
||||
initializeIsolatedMode();
|
||||
|
||||
async function initializeIsolatedMode() {
|
||||
try {
|
||||
console.log('Initializing NOSTR_LOGIN_LITE in ISOLATED mode...');
|
||||
|
||||
nostrLiteInstance = await window.NOSTR_LOGIN_LITE.init({
|
||||
theme: 'default',
|
||||
persistence: true,
|
||||
isolateSession: true, // Always isolated - each tab/window independent
|
||||
methods: {
|
||||
extension: true,
|
||||
local: true,
|
||||
readonly: true,
|
||||
connect: true,
|
||||
otp: true
|
||||
},
|
||||
floatingTab: {
|
||||
enabled: true,
|
||||
hPosition: 0.95,
|
||||
vPosition: 0.1,
|
||||
appearance: {
|
||||
style: 'pill',
|
||||
icon: '🔒',
|
||||
text: 'ISOLATED',
|
||||
iconOnly: false
|
||||
},
|
||||
behavior: {
|
||||
hideWhenAuthenticated: false,
|
||||
showUserInfo: true,
|
||||
autoSlide: true
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
checkStatus();
|
||||
|
||||
console.log('NOSTR_LOGIN_LITE initialized successfully in ISOLATED mode');
|
||||
console.log('Authentication will persist on refresh within this tab only');
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize NOSTR_LOGIN_LITE:', error);
|
||||
document.getElementById('results').innerHTML =
|
||||
`<div style="color: red;">Initialization Error: ${error.message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function login() {
|
||||
window.NOSTR_LOGIN_LITE.launch('login');
|
||||
}
|
||||
|
||||
function logout() {
|
||||
window.NOSTR_LOGIN_LITE.logout();
|
||||
setTimeout(checkStatus, 100);
|
||||
}
|
||||
|
||||
function debugAuthentication() {
|
||||
console.log('=== AUTHENTICATION DEBUG ===');
|
||||
|
||||
// Check global storage-based authentication state (SINGLE SOURCE OF TRUTH)
|
||||
const authState = window.NOSTR_LOGIN_LITE.getAuthState();
|
||||
console.log('🔍 GLOBAL getAuthState():', authState);
|
||||
console.log('🔍 Derived isAuthenticated():', !!authState);
|
||||
console.log('🔍 Derived getUserInfo():', authState);
|
||||
|
||||
// Check window.nostr (should sync with global state)
|
||||
console.log('window.nostr exists:', !!window.nostr);
|
||||
console.log('window.nostr constructor:', window.nostr?.constructor?.name);
|
||||
console.log('window.nostr.authState (getter):', window.nostr?.authState);
|
||||
|
||||
// Check NOSTR_LOGIN_LITE instance
|
||||
const instance = window.NOSTR_LOGIN_LITE?._instance;
|
||||
console.log('NOSTR_LOGIN_LITE instance exists:', !!instance);
|
||||
console.log('Instance hasExtension:', instance?.hasExtension);
|
||||
console.log('Instance facadeInstalled:', instance?.facadeInstalled);
|
||||
|
||||
// Check floating tab state (now queries global getAuthState() only)
|
||||
const floatingTab = instance?.floatingTab;
|
||||
console.log('FloatingTab exists:', !!floatingTab);
|
||||
if (floatingTab) {
|
||||
const tabAuthState = floatingTab._getAuthState();
|
||||
console.log('FloatingTab _getAuthState():', tabAuthState);
|
||||
console.log('FloatingTab derived authenticated:', !!tabAuthState);
|
||||
}
|
||||
|
||||
// Check session storage directly
|
||||
const sessionKeys = [];
|
||||
const storageKey = 'nostr_login_lite_auth';
|
||||
const sessionAuthData = sessionStorage.getItem(storageKey);
|
||||
const localAuthData = localStorage.getItem(storageKey);
|
||||
|
||||
for (let i = 0; i < sessionStorage.length; i++) {
|
||||
const key = sessionStorage.key(i);
|
||||
if (key && key.startsWith('nl_')) {
|
||||
const value = sessionStorage.getItem(key);
|
||||
sessionKeys.push({ key, valueLength: value?.length || 0, hasValue: !!value });
|
||||
}
|
||||
}
|
||||
console.log('SessionStorage nl_ keys:', sessionKeys);
|
||||
console.log('SessionStorage auth data:', !!sessionAuthData);
|
||||
console.log('LocalStorage auth data:', !!localAuthData);
|
||||
|
||||
// Display debug results
|
||||
let debugHTML = '<h4>🔍 Storage-Based Authentication Debug</h4>';
|
||||
debugHTML += '<div style="font-family: monospace; font-size: 12px; background: #f8f9fa; padding: 10px; border-radius: 4px;">';
|
||||
debugHTML += `<strong>🎯 GLOBAL getAuthState():</strong> ${!!authState} ${authState ? `(${authState.method})` : ''}<br>`;
|
||||
debugHTML += `<strong>🎯 Derived isAuthenticated():</strong> ${!!authState}<br>`;
|
||||
debugHTML += `<strong>🎯 Derived getUserInfo():</strong> ${!!authState}<br>`;
|
||||
debugHTML += `<strong>window.nostr exists:</strong> ${!!window.nostr} (${window.nostr?.constructor?.name})<br>`;
|
||||
debugHTML += `<strong>window.nostr.authState (getter):</strong> ${!!window.nostr?.authState}<br>`;
|
||||
debugHTML += `<strong>FloatingTab queries getAuthState():</strong> ${!!floatingTab?._getAuthState()}<br>`;
|
||||
debugHTML += `<strong>SessionStorage 'nostr_login_lite_auth':</strong> ${!!sessionAuthData}<br>`;
|
||||
debugHTML += `<strong>LocalStorage 'nostr_login_lite_auth':</strong> ${!!localAuthData}<br>`;
|
||||
debugHTML += `<strong>Session storage nl_ keys:</strong> ${sessionKeys.length}<br>`;
|
||||
debugHTML += `<strong>Instance hasExtension:</strong> ${instance?.hasExtension}<br>`;
|
||||
debugHTML += `<strong>Facade installed:</strong> ${instance?.facadeInstalled}<br>`;
|
||||
debugHTML += '</div>';
|
||||
debugHTML += '<p><strong>Check the browser console for detailed debug output.</strong></p>';
|
||||
debugHTML += '<p><strong>NEW Architecture:</strong> Global functions query localStorage/sessionStorage directly as single source of truth</p>';
|
||||
|
||||
// Check for consistency issues
|
||||
const derivedAuth = !!authState;
|
||||
const floatingTabAuth = !!floatingTab?._getAuthState();
|
||||
|
||||
if (floatingTabAuth !== derivedAuth) {
|
||||
debugHTML += '<p style="color: red;"><strong>🚨 MISMATCH DETECTED:</strong> FloatingTab and global getAuthState() disagree!</p>';
|
||||
debugHTML += '<p>Both should query the same storage - check implementation.</p>';
|
||||
} else if (sessionAuthData && !derivedAuth) {
|
||||
debugHTML += '<p style="color: orange;"><strong>⚠️ PARSING ISSUE:</strong> Session data exists but getAuthState() returns null!</p>';
|
||||
debugHTML += '<p>Check getAuthState() function - it may not be parsing the stored data correctly.</p>';
|
||||
} else if (!sessionAuthData && !localAuthData && derivedAuth) {
|
||||
debugHTML += '<p style="color: orange;"><strong>⚠️ STORAGE ISSUE:</strong> No storage data but getAuthState() returns data!</p>';
|
||||
debugHTML += '<p>getAuthState() may be reading from unexpected sources.</p>';
|
||||
}
|
||||
|
||||
document.getElementById('results').innerHTML = debugHTML;
|
||||
}
|
||||
|
||||
async function checkStatus() {
|
||||
try {
|
||||
console.log('🔍 Checking authentication status using GLOBAL functions...');
|
||||
|
||||
// Use the single global storage-based authentication state function
|
||||
const authState = window.NOSTR_LOGIN_LITE.getAuthState();
|
||||
|
||||
console.log('🔍 GLOBAL getAuthState():', authState);
|
||||
console.log('🔍 Derived isAuthenticated():', !!authState);
|
||||
console.log('🔍 Derived getUserInfo():', authState);
|
||||
console.log('🔍 window.nostr:', !!window.nostr);
|
||||
console.log('🔍 window.nostr.constructor:', window.nostr?.constructor?.name);
|
||||
|
||||
// Check storage directly for debugging
|
||||
const storageKey = 'nostr_login_lite_auth';
|
||||
const sessionAuthData = sessionStorage.getItem(storageKey);
|
||||
const localAuthData = localStorage.getItem(storageKey);
|
||||
console.log('🔍 sessionStorage auth data:', !!sessionAuthData);
|
||||
console.log('🔍 localStorage auth data:', !!localAuthData);
|
||||
|
||||
if (authState) {
|
||||
let pubkey = null;
|
||||
try {
|
||||
if (window.nostr) {
|
||||
pubkey = await window.nostr.getPublicKey();
|
||||
} else if (authState.pubkey) {
|
||||
pubkey = authState.pubkey;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Could not get pubkey:', err.message);
|
||||
pubkey = authState.pubkey;
|
||||
}
|
||||
|
||||
const method = authState.method;
|
||||
|
||||
console.log('✅ Authentication detected via GLOBAL functions - method:', method, 'pubkey:', pubkey?.slice(0, 8) + '...');
|
||||
|
||||
document.getElementById('auth-status').innerHTML =
|
||||
`<strong style="color: green;">✅ Authenticated (Session Isolated)</strong>`;
|
||||
document.getElementById('auth-details').innerHTML =
|
||||
`<strong>Method:</strong> ${method}<br>
|
||||
<strong>Public Key:</strong> ${pubkey ? `${pubkey.slice(0, 16)}...${pubkey.slice(-8)}` : 'Available in authState'}<br>
|
||||
<strong>Storage:</strong> ${sessionAuthData ? 'sessionStorage' : 'localStorage'} (${sessionAuthData ? 'isolated to this tab' : 'shared across tabs'})<br>
|
||||
<strong>Persistence:</strong> Survives refresh${sessionAuthData ? ', isolated from other tabs' : ', shared with other tabs'}<br>
|
||||
<strong>Debug:</strong> Global getAuthState() returns valid data`;
|
||||
} else if (sessionAuthData || localAuthData) {
|
||||
// We have storage data but getAuthState() returns null
|
||||
console.log('⚠️ Storage data exists but getAuthState() returns null');
|
||||
|
||||
document.getElementById('auth-status').innerHTML =
|
||||
`<strong style="color: orange;">⚠️ Authentication data found but not parsed</strong>`;
|
||||
document.getElementById('auth-details').innerHTML =
|
||||
`<strong>Storage:</strong> ${sessionAuthData ? 'sessionStorage' : 'localStorage'} has authentication data<br>
|
||||
<strong>Issue:</strong> getAuthState() returns null<br>
|
||||
<strong>Debug:</strong> Storage data: session=${!!sessionAuthData}, local=${!!localAuthData}<br>
|
||||
<strong>Solution:</strong> Check getAuthState() function implementation`;
|
||||
} else {
|
||||
console.log('❌ No authentication detected via getAuthState()');
|
||||
|
||||
document.getElementById('auth-status').innerHTML =
|
||||
`<strong style="color: red;">❌ Not authenticated</strong>`;
|
||||
document.getElementById('auth-details').innerHTML =
|
||||
`<strong>Storage:</strong> sessionStorage (isolated to this tab)<br>
|
||||
<strong>Status:</strong> Ready for login - will persist on refresh<br>
|
||||
<strong>Debug:</strong> getAuthState() returns no authentication data`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error checking status:', error);
|
||||
|
||||
document.getElementById('auth-status').innerHTML =
|
||||
`<strong style="color: orange;">⚠️ Error checking status</strong>`;
|
||||
document.getElementById('auth-details').innerHTML =
|
||||
`Error: ${error.message}<br>
|
||||
<strong>Debug:</strong> Check browser console for details`;
|
||||
}
|
||||
}
|
||||
|
||||
async function testSigning() {
|
||||
try {
|
||||
// Use global authentication state to check if authenticated
|
||||
const authState = window.NOSTR_LOGIN_LITE.getAuthState();
|
||||
if (!authState) {
|
||||
throw new Error('Not authenticated (checked via global getAuthState())');
|
||||
}
|
||||
|
||||
if (!window.nostr) {
|
||||
throw new Error('window.nostr not available for signing');
|
||||
}
|
||||
|
||||
const event = {
|
||||
kind: 1,
|
||||
content: `Test message from ISOLATED session - ${new Date().toISOString()}`,
|
||||
tags: [],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
};
|
||||
|
||||
const signedEvent = await window.nostr.signEvent(event);
|
||||
|
||||
document.getElementById('results').innerHTML =
|
||||
`<h4>✅ Signing Test Successful (Session Isolated)</h4>
|
||||
<p>This signature was created using the storage-based authentication system.</p>
|
||||
<p><strong>Authentication Method:</strong> getAuthState() confirmed authentication before signing</p>
|
||||
<pre>${JSON.stringify(signedEvent, null, 2)}</pre>`;
|
||||
|
||||
} catch (error) {
|
||||
document.getElementById('results').innerHTML =
|
||||
`<h4>❌ Signing Test Failed</h4>
|
||||
<p style="color: red;">${error.message}</p>
|
||||
<p><strong>Debug Info:</strong></p>
|
||||
<ul>
|
||||
<li>getAuthState(): ${!!window.NOSTR_LOGIN_LITE.getAuthState()}</li>
|
||||
<li>window.nostr exists: ${!!window.nostr}</li>
|
||||
<li>Auth method: ${JSON.stringify(window.NOSTR_LOGIN_LITE.getAuthState()?.method || null)}</li>
|
||||
</ul>`;
|
||||
}
|
||||
}
|
||||
|
||||
function openNewWindow() {
|
||||
const newWindow = window.open(
|
||||
window.location.href,
|
||||
'_blank',
|
||||
'width=900,height=700,scrollbars=yes,resizable=yes'
|
||||
);
|
||||
|
||||
if (newWindow) {
|
||||
document.getElementById('results').innerHTML =
|
||||
`<h4>🪟 New Window Opened - Independent Session</h4>
|
||||
<p><strong>Session Isolation Test:</strong></p>
|
||||
<ol>
|
||||
<li>The new window starts unauthenticated (independent session)</li>
|
||||
<li>Login in the new window with a different method or user</li>
|
||||
<li>Both windows maintain separate authentication states</li>
|
||||
<li>Refresh either window - authentication persists within that window only</li>
|
||||
<li>Close a window - its authentication is lost (sessionStorage cleared)</li>
|
||||
</ol>
|
||||
<p><strong>Expected Behavior:</strong> Each window/tab has completely independent authentication that persists on refresh but doesn't leak to other windows.</p>`;
|
||||
} else {
|
||||
document.getElementById('results').innerHTML =
|
||||
`<h4>❌ Failed to Open Window</h4>
|
||||
<p>Please allow popups and try again</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function inspectStorage() {
|
||||
const sessionStorage_keys = [];
|
||||
|
||||
// Inspect sessionStorage (our isolated storage)
|
||||
for (let i = 0; i < sessionStorage.length; i++) {
|
||||
const key = sessionStorage.key(i);
|
||||
if (key && key.startsWith('nl_')) {
|
||||
sessionStorage_keys.push({
|
||||
key,
|
||||
value: sessionStorage.getItem(key)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let content = '<h4>📊 Session Storage Inspection</h4>';
|
||||
content += '<p><strong>Note:</strong> This tab uses sessionStorage for isolation - data here is independent of other tabs/windows.</p>';
|
||||
|
||||
content += '<h5>sessionStorage (This tab only):</h5>';
|
||||
if (sessionStorage_keys.length === 0) {
|
||||
content += '<p style="color: #666;">No authentication data found in this session</p>';
|
||||
} else {
|
||||
content += '<p style="color: green;">✅ Authentication data found (persists on refresh)</p>';
|
||||
content += '<pre>' + JSON.stringify(sessionStorage_keys, null, 2) + '</pre>';
|
||||
}
|
||||
|
||||
// Show what would be in localStorage if we weren't using isolation
|
||||
const localStorage_keys = [];
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
if (key && key.startsWith('nl_')) {
|
||||
localStorage_keys.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
content += '<h5>localStorage (Not used in isolated mode):</h5>';
|
||||
if (localStorage_keys.length === 0) {
|
||||
content += '<p style="color: #666;">No NOSTR_LOGIN_LITE data (expected in isolated mode)</p>';
|
||||
} else {
|
||||
content += '<p style="color: orange;">⚠️ Found some data - might be from non-isolated sessions</p>';
|
||||
}
|
||||
|
||||
document.getElementById('storage-content').innerHTML = content;
|
||||
}
|
||||
|
||||
function clearStorage() {
|
||||
// Clear only sessionStorage (our isolated storage)
|
||||
const sessionKeys = [];
|
||||
|
||||
for (let i = 0; i < sessionStorage.length; i++) {
|
||||
const key = sessionStorage.key(i);
|
||||
if (key && key.startsWith('nl_')) {
|
||||
sessionKeys.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
sessionKeys.forEach(key => sessionStorage.removeItem(key));
|
||||
|
||||
document.getElementById('storage-content').innerHTML =
|
||||
`<h4>🧹 Session Storage Cleared</h4>
|
||||
<p>Removed ${sessionKeys.length} authentication items from this tab's sessionStorage</p>
|
||||
<p><strong>Result:</strong> This tab is now logged out, but other tabs are unaffected</p>`;
|
||||
|
||||
// Update status
|
||||
setTimeout(checkStatus, 100);
|
||||
}
|
||||
|
||||
// Listen for authentication events
|
||||
window.addEventListener('nlMethodSelected', (event) => {
|
||||
console.log('Authentication successful in isolated session:', event.detail);
|
||||
setTimeout(checkStatus, 100);
|
||||
|
||||
document.getElementById('results').innerHTML =
|
||||
`<h4>✅ Authentication Successful (Session Isolated)</h4>
|
||||
<p><strong>Method:</strong> ${event.detail.method}</p>
|
||||
<p><strong>Storage:</strong> sessionStorage (isolated to this tab)</p>
|
||||
<p><strong>Persistence:</strong> Will survive refresh, won't affect other tabs</p>
|
||||
<p><strong>Test:</strong> Open a new tab - it should start unauthenticated</p>`;
|
||||
});
|
||||
|
||||
window.addEventListener('nlLogout', (event) => {
|
||||
console.log('Logout detected in isolated session:', event.detail);
|
||||
setTimeout(checkStatus, 100);
|
||||
|
||||
document.getElementById('results').innerHTML =
|
||||
`<h4>👋 Logged Out (Session Isolated)</h4>
|
||||
<p>Authentication cleared from this tab's sessionStorage only</p>
|
||||
<p><strong>Result:</strong> Other tabs remain unaffected by this logout</p>`;
|
||||
});
|
||||
|
||||
// Check status on page load (should restore from sessionStorage if available)
|
||||
window.addEventListener('load', () => {
|
||||
setTimeout(checkStatus, 500);
|
||||
|
||||
// Show persistence message if we're restoring authentication
|
||||
if (sessionStorage.getItem('nl_auth_state') || sessionStorage.getItem('nl_current')) {
|
||||
setTimeout(() => {
|
||||
document.getElementById('results').innerHTML =
|
||||
`<h4>🔄 Session Restored</h4>
|
||||
<p>Authentication state restored from sessionStorage on page load</p>
|
||||
<p><strong>Isolation confirmed:</strong> This tab's login state is independent</p>`;
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
184
examples/sign.html
Normal file
184
examples/sign.html
Normal file
@@ -0,0 +1,184 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>NIP-07 Signing Test</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div>
|
||||
<div id="status"></div>
|
||||
|
||||
<div id="test-section" style="display:none;">
|
||||
<button id="sign-button">Sign Event</button>
|
||||
<button id="encrypt-button">Test NIP-04 Encrypt</button>
|
||||
<button id="decrypt-button">Test NIP-04 Decrypt</button>
|
||||
<div id="results"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="../lite/nostr.bundle.js"></script>
|
||||
<script src="../lite/nostr-lite.js"></script>
|
||||
|
||||
<script>
|
||||
let testPubkey = 'npub1damus9dqe7g7jqn45kjcjgsv0vxjqnk8cxjkf8gqjwm8t8qjm7cqm3z7l';
|
||||
let ciphertext = '';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await window.NOSTR_LOGIN_LITE.init({
|
||||
theme: 'default',
|
||||
methods: {
|
||||
extension: true,
|
||||
local: true,
|
||||
readonly: true,
|
||||
connect: true,
|
||||
remote: true,
|
||||
otp: true
|
||||
},
|
||||
floatingTab: {
|
||||
enabled: true,
|
||||
hPosition: 1, // 0.0-1.0 or '95%' from left
|
||||
vPosition: 0, // 0.0-1.0 or '50%' from top
|
||||
appearance: {
|
||||
style: 'pill', // 'pill', 'square', 'circle', 'minimal'
|
||||
icon: '', // Clean display without icon placeholders
|
||||
text: 'Login'
|
||||
},
|
||||
behavior: {
|
||||
hideWhenAuthenticated: false,
|
||||
showUserInfo: true,
|
||||
autoSlide: true
|
||||
},
|
||||
getUserInfo: true, // Enable profile fetching
|
||||
getUserRelay: [ // Specific relays for profile fetching
|
||||
'wss://relay.laantungir.net'
|
||||
]
|
||||
}});
|
||||
|
||||
|
||||
// document.getElementById('login-button').addEventListener('click', () => {
|
||||
// window.NOSTR_LOGIN_LITE.launch('login');
|
||||
// });
|
||||
|
||||
window.addEventListener('nlMethodSelected', (event) => {
|
||||
document.getElementById('status').textContent = `Authenticated with: ${event.detail.method}`;
|
||||
document.getElementById('test-section').style.display = 'block';
|
||||
});
|
||||
|
||||
document.getElementById('sign-button').addEventListener('click', testSigning);
|
||||
document.getElementById('encrypt-button').addEventListener('click', testEncryption);
|
||||
document.getElementById('decrypt-button').addEventListener('click', testDecryption);
|
||||
});
|
||||
|
||||
async function testSigning() {
|
||||
try {
|
||||
console.log('=== DEBUGGING SIGN EVENT START ===');
|
||||
console.log('testSigning: window.nostr is:', window.nostr);
|
||||
console.log('testSigning: window.nostr constructor:', window.nostr?.constructor?.name);
|
||||
console.log('testSigning: window.nostr === our facade?', window.nostr?.constructor?.name === 'WindowNostr');
|
||||
|
||||
// Get user public key for comparison
|
||||
const userPubkey = await window.nostr.getPublicKey();
|
||||
console.log('User public key:', userPubkey);
|
||||
|
||||
// Check auth state if our facade
|
||||
if (window.nostr?.constructor?.name === 'WindowNostr') {
|
||||
console.log('WindowNostr authState:', window.nostr.authState);
|
||||
console.log('WindowNostr authenticatedExtension:', window.nostr.authenticatedExtension);
|
||||
console.log('WindowNostr existingNostr:', window.nostr.existingNostr);
|
||||
}
|
||||
|
||||
const event = {
|
||||
kind: 1,
|
||||
content: 'Hello from NIP-07!',
|
||||
tags: [],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
};
|
||||
|
||||
console.log('=== EVENT BEING SENT TO EXTENSION ===');
|
||||
console.log('Event object:', JSON.stringify(event, null, 2));
|
||||
console.log('Event keys:', Object.keys(event));
|
||||
console.log('Event kind type:', typeof event.kind, event.kind);
|
||||
console.log('Event content type:', typeof event.content, event.content);
|
||||
console.log('Event tags type:', typeof event.tags, event.tags);
|
||||
console.log('Event created_at type:', typeof event.created_at, event.created_at);
|
||||
console.log('Event created_at value:', event.created_at);
|
||||
|
||||
// Check if created_at is within reasonable bounds
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const timeDiff = Math.abs(event.created_at - now);
|
||||
console.log('Time difference from now (seconds):', timeDiff);
|
||||
console.log('Event timestamp as Date:', new Date(event.created_at * 1000));
|
||||
|
||||
// Additional debugging for user-specific issues
|
||||
console.log('=== USER-SPECIFIC DEBUG INFO ===');
|
||||
console.log('User pubkey length:', userPubkey?.length);
|
||||
console.log('User pubkey format check (hex):', /^[a-fA-F0-9]{64}$/.test(userPubkey));
|
||||
|
||||
// Try to get user profile info if available
|
||||
try {
|
||||
const profileEvent = {
|
||||
kinds: [0],
|
||||
authors: [userPubkey],
|
||||
limit: 1
|
||||
};
|
||||
console.log('Would query profile with filter:', profileEvent);
|
||||
} catch (profileErr) {
|
||||
console.log('Profile query setup failed:', profileErr);
|
||||
}
|
||||
|
||||
console.log('=== ABOUT TO CALL EXTENSION SIGN EVENT ===');
|
||||
const signedEvent = await window.nostr.signEvent(event);
|
||||
|
||||
console.log('=== SIGN EVENT SUCCESSFUL ===');
|
||||
console.log('Signed event:', JSON.stringify(signedEvent, null, 2));
|
||||
console.log('Signed event keys:', Object.keys(signedEvent));
|
||||
console.log('Signature present:', !!signedEvent.sig);
|
||||
console.log('ID present:', !!signedEvent.id);
|
||||
console.log('Pubkey matches user:', signedEvent.pubkey === userPubkey);
|
||||
|
||||
document.getElementById('results').innerHTML = `<h3>Signed Event:</h3><pre>${JSON.stringify(signedEvent, null, 2)}</pre>`;
|
||||
|
||||
console.log('=== DEBUGGING SIGN EVENT END ===');
|
||||
} catch (error) {
|
||||
console.error('=== SIGN EVENT ERROR ===');
|
||||
console.error('Error message:', error.message);
|
||||
console.error('Error stack:', error.stack);
|
||||
console.error('Error object:', error);
|
||||
|
||||
document.getElementById('results').innerHTML = `<h3>Sign Error:</h3><pre>${error.message}</pre><pre>${error.stack}</pre>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function testEncryption() {
|
||||
try {
|
||||
const plaintext = 'Secret message for testing';
|
||||
const pubkey = await window.nostr.getPublicKey();
|
||||
|
||||
ciphertext = await window.nostr.nip04.encrypt(pubkey, plaintext);
|
||||
document.getElementById('results').innerHTML = `<h3>Encrypted:</h3><pre>${ciphertext}</pre>`;
|
||||
} catch (error) {
|
||||
document.getElementById('results').innerHTML = `<h3>Encrypt Error:</h3><pre>${error.message}</pre>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function testDecryption() {
|
||||
try {
|
||||
if (!ciphertext) {
|
||||
document.getElementById('results').innerHTML = `<h3>Decrypt Error:</h3><pre>No ciphertext available. Run encrypt first.</pre>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const pubkey = await window.nostr.getPublicKey();
|
||||
const decrypted = await window.nostr.nip04.decrypt(pubkey, ciphertext);
|
||||
document.getElementById('results').innerHTML = `<h3>Decrypted:</h3><pre>${decrypted}</pre>`;
|
||||
} catch (error) {
|
||||
document.getElementById('results').innerHTML = `<h3>Decrypt Error:</h3><pre>${error.message}</pre>`;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
1735
lite/build.js
1735
lite/build.js
File diff suppressed because it is too large
Load Diff
2398
lite/nostr-lite.js
2398
lite/nostr-lite.js
File diff suppressed because it is too large
Load Diff
5472
lite/nostr.bundle.js
5472
lite/nostr.bundle.js
File diff suppressed because it is too large
Load Diff
659
lite/ui/modal.js
659
lite/ui/modal.js
@@ -58,7 +58,7 @@ class Modal {
|
||||
overflow: hidden;
|
||||
`;
|
||||
} else {
|
||||
// Modal content: centered with margin
|
||||
// Modal content: centered with margin, no fixed height
|
||||
modalContent.style.cssText = `
|
||||
position: relative;
|
||||
background: var(--nl-secondary-color);
|
||||
@@ -68,7 +68,6 @@ class Modal {
|
||||
margin: 50px auto;
|
||||
border-radius: var(--nl-border-radius, 15px);
|
||||
border: var(--nl-border-width) solid var(--nl-primary-color);
|
||||
max-height: 600px;
|
||||
overflow: hidden;
|
||||
`;
|
||||
}
|
||||
@@ -105,7 +104,7 @@ class Modal {
|
||||
closeButton.style.cssText = `
|
||||
background: var(--nl-secondary-color);
|
||||
border: var(--nl-border-width) solid var(--nl-primary-color);
|
||||
border-radius: var(--nl-border-radius);
|
||||
border-radius: 4px;
|
||||
font-size: 28px;
|
||||
color: var(--nl-primary-color);
|
||||
cursor: pointer;
|
||||
@@ -133,8 +132,6 @@ class Modal {
|
||||
this.modalBody = document.createElement('div');
|
||||
this.modalBody.style.cssText = `
|
||||
padding: 24px;
|
||||
overflow-y: auto;
|
||||
max-height: 500px;
|
||||
background: transparent;
|
||||
font-family: var(--nl-font-family, 'Courier New', monospace);
|
||||
`;
|
||||
@@ -223,6 +220,16 @@ class Modal {
|
||||
});
|
||||
}
|
||||
|
||||
// Seed Phrase option - only show if explicitly enabled
|
||||
if (this.options?.methods?.seedphrase === true) {
|
||||
options.push({
|
||||
type: 'seedphrase',
|
||||
title: 'Seed Phrase',
|
||||
description: 'Import from mnemonic seed phrase',
|
||||
icon: '🌱'
|
||||
});
|
||||
}
|
||||
|
||||
// Nostr Connect option (check both 'connect' and 'remote' for compatibility)
|
||||
if (this.options?.methods?.connect !== false && this.options?.methods?.remote !== false) {
|
||||
options.push({
|
||||
@@ -280,6 +287,19 @@ class Modal {
|
||||
button.style.background = 'var(--nl-secondary-color)';
|
||||
};
|
||||
|
||||
const iconDiv = document.createElement('div');
|
||||
// Remove the icon entirely - no emojis or text-based icons
|
||||
iconDiv.textContent = '';
|
||||
iconDiv.style.cssText = `
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
margin-right: 16px;
|
||||
width: 0px;
|
||||
text-align: center;
|
||||
color: var(--nl-primary-color);
|
||||
font-family: var(--nl-font-family, 'Courier New', monospace);
|
||||
`;
|
||||
|
||||
const contentDiv = document.createElement('div');
|
||||
contentDiv.style.cssText = 'flex: 1; text-align: left;';
|
||||
|
||||
@@ -303,6 +323,7 @@ class Modal {
|
||||
contentDiv.appendChild(titleDiv);
|
||||
contentDiv.appendChild(descDiv);
|
||||
|
||||
button.appendChild(iconDiv);
|
||||
button.appendChild(contentDiv);
|
||||
this.modalBody.appendChild(button);
|
||||
});
|
||||
@@ -319,6 +340,9 @@ class Modal {
|
||||
case 'local':
|
||||
this._showLocalKeyScreen();
|
||||
break;
|
||||
case 'seedphrase':
|
||||
this._showSeedPhraseScreen();
|
||||
break;
|
||||
case 'connect':
|
||||
this._showConnectScreen();
|
||||
break;
|
||||
@@ -332,23 +356,62 @@ class Modal {
|
||||
}
|
||||
|
||||
_handleExtension() {
|
||||
// Detect all available real extensions
|
||||
const availableExtensions = this._detectAllExtensions();
|
||||
// SIMPLIFIED ARCHITECTURE: Check for single extension at window.nostr or preserved extension
|
||||
let extension = null;
|
||||
|
||||
console.log(`Modal: Found ${availableExtensions.length} extensions:`, availableExtensions.map(e => e.displayName));
|
||||
|
||||
if (availableExtensions.length === 0) {
|
||||
console.log('Modal: No real extensions found');
|
||||
this._showExtensionRequired();
|
||||
} else if (availableExtensions.length === 1) {
|
||||
// Single extension - use it directly without showing choice UI
|
||||
console.log('Modal: Single extension detected, using it directly:', availableExtensions[0].displayName);
|
||||
this._tryExtensionLogin(availableExtensions[0].extension);
|
||||
} else {
|
||||
// Multiple extensions - show choice UI
|
||||
console.log('Modal: Multiple extensions detected, showing choice UI for', availableExtensions.length, 'extensions');
|
||||
this._showExtensionChoice(availableExtensions);
|
||||
// Check if NostrLite instance has a preserved extension (real extension detected at init)
|
||||
if (window.NOSTR_LOGIN_LITE?._instance?.preservedExtension) {
|
||||
extension = window.NOSTR_LOGIN_LITE._instance.preservedExtension;
|
||||
console.log('Modal: Using preserved extension:', extension.constructor?.name);
|
||||
}
|
||||
// Otherwise check current window.nostr
|
||||
else if (window.nostr && this._isRealExtension(window.nostr)) {
|
||||
extension = window.nostr;
|
||||
console.log('Modal: Using current window.nostr extension:', extension.constructor?.name);
|
||||
}
|
||||
|
||||
if (!extension) {
|
||||
console.log('Modal: No extension detected yet, waiting for deferred detection...');
|
||||
|
||||
// DEFERRED EXTENSION CHECK: Extensions like nos2x might load after our library
|
||||
let attempts = 0;
|
||||
const maxAttempts = 10; // Try for 2 seconds
|
||||
const checkForExtension = () => {
|
||||
attempts++;
|
||||
|
||||
// Check again for preserved extension (might be set by deferred detection)
|
||||
if (window.NOSTR_LOGIN_LITE?._instance?.preservedExtension) {
|
||||
extension = window.NOSTR_LOGIN_LITE._instance.preservedExtension;
|
||||
console.log('Modal: Found preserved extension after waiting:', extension.constructor?.name);
|
||||
this._tryExtensionLogin(extension);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check current window.nostr again
|
||||
if (window.nostr && this._isRealExtension(window.nostr)) {
|
||||
extension = window.nostr;
|
||||
console.log('Modal: Found extension at window.nostr after waiting:', extension.constructor?.name);
|
||||
this._tryExtensionLogin(extension);
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep trying or give up
|
||||
if (attempts < maxAttempts) {
|
||||
setTimeout(checkForExtension, 200);
|
||||
} else {
|
||||
console.log('Modal: No browser extension found after waiting 2 seconds');
|
||||
this._showExtensionRequired();
|
||||
}
|
||||
};
|
||||
|
||||
// Start checking after a brief delay
|
||||
setTimeout(checkForExtension, 200);
|
||||
return;
|
||||
}
|
||||
|
||||
// Use the single detected extension directly - no choice UI
|
||||
console.log('Modal: Single extension mode - using extension directly');
|
||||
this._tryExtensionLogin(extension);
|
||||
}
|
||||
|
||||
_detectAllExtensions() {
|
||||
@@ -394,17 +457,38 @@ class Modal {
|
||||
|
||||
// Also check window.nostr but be extra careful to avoid our library
|
||||
console.log('Modal: Checking window.nostr:', !!window.nostr, window.nostr?.constructor?.name);
|
||||
if (window.nostr && this._isRealExtension(window.nostr) && !seenExtensions.has(window.nostr)) {
|
||||
extensions.push({
|
||||
name: 'window.nostr',
|
||||
displayName: 'Extension (window.nostr)',
|
||||
icon: '🔑',
|
||||
extension: window.nostr
|
||||
});
|
||||
seenExtensions.add(window.nostr);
|
||||
console.log(`Modal: ✓ Detected extension at window.nostr: ${window.nostr.constructor?.name}`);
|
||||
} else if (window.nostr) {
|
||||
console.log(`Modal: ✗ Filtered out window.nostr (${window.nostr.constructor?.name}) - likely our library`);
|
||||
|
||||
if (window.nostr) {
|
||||
// Check if window.nostr is our WindowNostr facade with a preserved extension
|
||||
if (window.nostr.constructor?.name === 'WindowNostr' && window.nostr.existingNostr) {
|
||||
console.log('Modal: Found WindowNostr facade, checking existingNostr for preserved extension');
|
||||
const preservedExtension = window.nostr.existingNostr;
|
||||
console.log('Modal: Preserved extension:', !!preservedExtension, preservedExtension?.constructor?.name);
|
||||
|
||||
if (preservedExtension && this._isRealExtension(preservedExtension) && !seenExtensions.has(preservedExtension)) {
|
||||
extensions.push({
|
||||
name: 'window.nostr.existingNostr',
|
||||
displayName: 'Extension (preserved by WindowNostr)',
|
||||
icon: '🔑',
|
||||
extension: preservedExtension
|
||||
});
|
||||
seenExtensions.add(preservedExtension);
|
||||
console.log(`Modal: ✓ Detected preserved extension: ${preservedExtension.constructor?.name}`);
|
||||
}
|
||||
}
|
||||
// Check if window.nostr is directly a real extension (not our facade)
|
||||
else if (this._isRealExtension(window.nostr) && !seenExtensions.has(window.nostr)) {
|
||||
extensions.push({
|
||||
name: 'window.nostr',
|
||||
displayName: 'Extension (window.nostr)',
|
||||
icon: '🔑',
|
||||
extension: window.nostr
|
||||
});
|
||||
seenExtensions.add(window.nostr);
|
||||
console.log(`Modal: ✓ Detected extension at window.nostr: ${window.nostr.constructor?.name}`);
|
||||
} else {
|
||||
console.log(`Modal: ✗ Filtered out window.nostr (${window.nostr.constructor?.name}) - not a real extension`);
|
||||
}
|
||||
}
|
||||
|
||||
return extensions;
|
||||
@@ -994,6 +1078,63 @@ class Modal {
|
||||
}
|
||||
|
||||
_setAuthMethod(method, options = {}) {
|
||||
// SINGLE-EXTENSION ARCHITECTURE: Handle method switching
|
||||
console.log('Modal: _setAuthMethod called with:', method, options);
|
||||
|
||||
// CRITICAL: Never install facade for extension methods - leave window.nostr as the extension
|
||||
if (method === 'extension') {
|
||||
console.log('Modal: Extension method - NOT installing facade, leaving window.nostr as extension');
|
||||
|
||||
// Emit auth method selection directly for extension
|
||||
const event = new CustomEvent('nlMethodSelected', {
|
||||
detail: { method, ...options }
|
||||
});
|
||||
window.dispatchEvent(event);
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// For non-extension methods, we need to ensure WindowNostr facade is available
|
||||
console.log('Modal: Non-extension method detected:', method);
|
||||
|
||||
// Check if we have a preserved extension but no WindowNostr facade installed
|
||||
const hasPreservedExtension = !!window.NOSTR_LOGIN_LITE?._instance?.preservedExtension;
|
||||
const hasWindowNostrFacade = window.nostr?.constructor?.name === 'WindowNostr';
|
||||
|
||||
console.log('Modal: Method switching check:');
|
||||
console.log(' method:', method);
|
||||
console.log(' hasPreservedExtension:', hasPreservedExtension);
|
||||
console.log(' hasWindowNostrFacade:', hasWindowNostrFacade);
|
||||
console.log(' current window.nostr constructor:', window.nostr?.constructor?.name);
|
||||
|
||||
// If we have a preserved extension but no facade, install facade for method switching
|
||||
if (hasPreservedExtension && !hasWindowNostrFacade) {
|
||||
console.log('Modal: Installing WindowNostr facade for method switching (non-extension authentication)');
|
||||
|
||||
// Get the NostrLite instance and install facade with preserved extension
|
||||
const nostrLiteInstance = window.NOSTR_LOGIN_LITE?._instance;
|
||||
if (nostrLiteInstance && typeof nostrLiteInstance._installFacade === 'function') {
|
||||
const preservedExtension = nostrLiteInstance.preservedExtension;
|
||||
console.log('Modal: Installing facade with preserved extension:', preservedExtension?.constructor?.name);
|
||||
|
||||
nostrLiteInstance._installFacade(preservedExtension);
|
||||
console.log('Modal: WindowNostr facade installed for method switching');
|
||||
} else {
|
||||
console.error('Modal: Cannot access NostrLite instance or _installFacade method');
|
||||
}
|
||||
}
|
||||
|
||||
// If no extension at all, ensure facade is installed for local/NIP-46/readonly methods
|
||||
else if (!hasPreservedExtension && !hasWindowNostrFacade) {
|
||||
console.log('Modal: Installing WindowNostr facade for non-extension methods (no extension detected)');
|
||||
|
||||
const nostrLiteInstance = window.NOSTR_LOGIN_LITE?._instance;
|
||||
if (nostrLiteInstance && typeof nostrLiteInstance._installFacade === 'function') {
|
||||
nostrLiteInstance._installFacade();
|
||||
console.log('Modal: WindowNostr facade installed for non-extension methods');
|
||||
}
|
||||
}
|
||||
|
||||
// Emit auth method selection
|
||||
const event = new CustomEvent('nlMethodSelected', {
|
||||
detail: { method, ...options }
|
||||
@@ -1027,8 +1168,13 @@ class Modal {
|
||||
title.style.cssText = 'margin: 0 0 16px 0; font-size: 18px; font-weight: 600;';
|
||||
|
||||
const message = document.createElement('p');
|
||||
message.textContent = 'Please install a Nostr browser extension like Alby or getflattr and refresh the page.';
|
||||
message.style.cssText = 'margin-bottom: 20px; color: #6b7280;';
|
||||
message.innerHTML = `
|
||||
Please install a Nostr browser extension and refresh the page.<br><br>
|
||||
<strong>Important:</strong> If you have multiple extensions installed, please disable all but one to avoid conflicts.
|
||||
<br><br>
|
||||
Popular extensions: Alby, nos2x, Flamingo
|
||||
`;
|
||||
message.style.cssText = 'margin-bottom: 20px; color: #6b7280; font-size: 14px; line-height: 1.4;';
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
backButton.textContent = 'Back';
|
||||
@@ -1043,10 +1189,6 @@ class Modal {
|
||||
_showConnectScreen() {
|
||||
this.modalBody.innerHTML = '';
|
||||
|
||||
const title = document.createElement('h3');
|
||||
title.textContent = 'Connect to NIP-46 Remote Signer';
|
||||
title.style.cssText = 'margin: 0 0 16px 0; font-size: 18px; font-weight: 600;';
|
||||
|
||||
const description = document.createElement('p');
|
||||
description.textContent = 'Connect to a remote signer (bunker) server to use its keys for signing.';
|
||||
description.style.cssText = 'margin-bottom: 20px; color: #6b7280; font-size: 14px;';
|
||||
@@ -1071,28 +1213,67 @@ class Modal {
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
|
||||
const urlLabel = document.createElement('label');
|
||||
urlLabel.textContent = 'Remote URL (optional):';
|
||||
urlLabel.style.cssText = 'display: block; margin-bottom: 8px; font-weight: 500;';
|
||||
|
||||
const urlInput = document.createElement('input');
|
||||
urlInput.type = 'url';
|
||||
urlInput.placeholder = 'ws://localhost:8080 (default)';
|
||||
urlInput.style.cssText = `
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 16px;
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
|
||||
// Users will enter the bunker URL manually from their bunker setup
|
||||
// Add real-time bunker key validation
|
||||
const formatHint = document.createElement('div');
|
||||
formatHint.style.cssText = 'margin-bottom: 16px; font-size: 12px; color: #6b7280; min-height: 16px;';
|
||||
|
||||
const connectButton = document.createElement('button');
|
||||
connectButton.textContent = 'Connect to Bunker';
|
||||
connectButton.onclick = () => this._handleNip46Connect(pubkeyInput.value, urlInput.value);
|
||||
connectButton.style.cssText = this._getButtonStyle();
|
||||
connectButton.disabled = true;
|
||||
connectButton.onclick = () => {
|
||||
if (!connectButton.disabled) {
|
||||
this._handleNip46Connect(pubkeyInput.value);
|
||||
}
|
||||
};
|
||||
|
||||
// Set initial disabled state
|
||||
connectButton.style.cssText = `
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: var(--nl-border-width) solid var(--nl-muted-color);
|
||||
border-radius: var(--nl-border-radius);
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
cursor: not-allowed;
|
||||
transition: all 0.2s;
|
||||
font-family: var(--nl-font-family, 'Courier New', monospace);
|
||||
background: var(--nl-secondary-color);
|
||||
color: var(--nl-muted-color);
|
||||
margin-bottom: 12px;
|
||||
`;
|
||||
|
||||
pubkeyInput.oninput = () => {
|
||||
const value = pubkeyInput.value.trim();
|
||||
if (!value) {
|
||||
formatHint.textContent = '';
|
||||
// Disable button
|
||||
connectButton.disabled = true;
|
||||
connectButton.style.borderColor = 'var(--nl-muted-color)';
|
||||
connectButton.style.color = 'var(--nl-muted-color)';
|
||||
connectButton.style.cursor = 'not-allowed';
|
||||
return;
|
||||
}
|
||||
|
||||
const isValid = this._validateBunkerKey(value);
|
||||
if (isValid) {
|
||||
formatHint.textContent = '✅ Valid bunker connection format detected';
|
||||
formatHint.style.color = '#059669';
|
||||
// Enable button
|
||||
connectButton.disabled = false;
|
||||
connectButton.style.borderColor = 'var(--nl-primary-color)';
|
||||
connectButton.style.color = 'var(--nl-primary-color)';
|
||||
connectButton.style.cursor = 'pointer';
|
||||
} else {
|
||||
formatHint.textContent = '❌ Invalid format - must be bunker://, npub, or 64-char hex';
|
||||
formatHint.style.color = '#dc2626';
|
||||
// Disable button
|
||||
connectButton.disabled = true;
|
||||
connectButton.style.borderColor = 'var(--nl-muted-color)';
|
||||
connectButton.style.color = 'var(--nl-muted-color)';
|
||||
connectButton.style.cursor = 'not-allowed';
|
||||
}
|
||||
};
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
backButton.textContent = 'Back';
|
||||
@@ -1101,27 +1282,60 @@ class Modal {
|
||||
|
||||
formGroup.appendChild(label);
|
||||
formGroup.appendChild(pubkeyInput);
|
||||
formGroup.appendChild(urlLabel);
|
||||
formGroup.appendChild(urlInput);
|
||||
formGroup.appendChild(formatHint);
|
||||
|
||||
this.modalBody.appendChild(title);
|
||||
this.modalBody.appendChild(description);
|
||||
this.modalBody.appendChild(formGroup);
|
||||
this.modalBody.appendChild(connectButton);
|
||||
this.modalBody.appendChild(backButton);
|
||||
}
|
||||
|
||||
_handleNip46Connect(bunkerPubkey, bunkerUrl) {
|
||||
_validateBunkerKey(bunkerKey) {
|
||||
try {
|
||||
const trimmed = bunkerKey.trim();
|
||||
|
||||
// Check for bunker:// format
|
||||
if (trimmed.startsWith('bunker://')) {
|
||||
// Should have format: bunker://pubkey or bunker://pubkey?param=value
|
||||
const match = trimmed.match(/^bunker:\/\/([0-9a-fA-F]{64})(\?.*)?$/);
|
||||
return !!match;
|
||||
}
|
||||
|
||||
// Check for npub format
|
||||
if (trimmed.startsWith('npub1') && trimmed.length === 63) {
|
||||
try {
|
||||
if (window.NostrTools?.nip19) {
|
||||
const decoded = window.NostrTools.nip19.decode(trimmed);
|
||||
return decoded.type === 'npub';
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for hex format (64 characters, valid hex)
|
||||
if (trimmed.length === 64 && /^[a-fA-F0-9]{64}$/.test(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.log('Bunker key validation failed:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_handleNip46Connect(bunkerPubkey) {
|
||||
if (!bunkerPubkey || !bunkerPubkey.length) {
|
||||
this._showError('Bunker pubkey is required');
|
||||
return;
|
||||
}
|
||||
|
||||
this._showNip46Connecting(bunkerPubkey, bunkerUrl);
|
||||
this._performNip46Connect(bunkerPubkey, bunkerUrl);
|
||||
this._showNip46Connecting(bunkerPubkey);
|
||||
this._performNip46Connect(bunkerPubkey);
|
||||
}
|
||||
|
||||
_showNip46Connecting(bunkerPubkey, bunkerUrl) {
|
||||
_showNip46Connecting(bunkerPubkey) {
|
||||
this.modalBody.innerHTML = '';
|
||||
|
||||
const title = document.createElement('h3');
|
||||
@@ -1139,9 +1353,8 @@ class Modal {
|
||||
bunkerInfo.style.cssText = 'background: #f1f5f9; padding: 12px; border-radius: 6px; margin-bottom: 20px; font-size: 14px;';
|
||||
bunkerInfo.innerHTML = `
|
||||
<strong>Connecting to bunker:</strong><br>
|
||||
Pubkey: <code style="word-break: break-all;">${displayPubkey}</code><br>
|
||||
Relay: <code style="word-break: break-all;">${bunkerUrl || 'ws://localhost:8080'}</code><br>
|
||||
<small style="color: #6b7280;">If this relay is offline, the bunker server may be unavailable.</small>
|
||||
Connection: <code style="word-break: break-all;">${displayPubkey}</code><br>
|
||||
<small style="color: #6b7280;">Connection string contains all necessary relay information.</small>
|
||||
`;
|
||||
|
||||
const connectingDiv = document.createElement('div');
|
||||
@@ -1158,9 +1371,9 @@ class Modal {
|
||||
this.modalBody.appendChild(connectingDiv);
|
||||
}
|
||||
|
||||
async _performNip46Connect(bunkerPubkey, bunkerUrl) {
|
||||
async _performNip46Connect(bunkerPubkey) {
|
||||
try {
|
||||
console.log('Starting NIP-46 connection to bunker:', bunkerPubkey, bunkerUrl);
|
||||
console.log('Starting NIP-46 connection to bunker:', bunkerPubkey);
|
||||
|
||||
// Check if nostr-tools NIP-46 is available
|
||||
if (!window.NostrTools?.nip46) {
|
||||
@@ -1181,9 +1394,9 @@ class Modal {
|
||||
const localSecretKey = window.NostrTools.generateSecretKey();
|
||||
console.log('Generated local client keypair for NIP-46 session');
|
||||
|
||||
// Use nostr-tools BunkerSigner constructor
|
||||
// Use nostr-tools BunkerSigner factory method (not constructor - it's private)
|
||||
console.log('Creating nip46 BunkerSigner...');
|
||||
const signer = new window.NostrTools.nip46.BunkerSigner(localSecretKey, bunkerPointer, {
|
||||
const signer = window.NostrTools.nip46.BunkerSigner.fromBunker(localSecretKey, bunkerPointer, {
|
||||
onauth: (url) => {
|
||||
console.log('Received auth URL from bunker:', url);
|
||||
// Open auth URL in popup or redirect
|
||||
@@ -1260,6 +1473,312 @@ class Modal {
|
||||
this._setAuthMethod('readonly');
|
||||
}
|
||||
|
||||
_showSeedPhraseScreen() {
|
||||
this.modalBody.innerHTML = '';
|
||||
|
||||
const description = document.createElement('p');
|
||||
description.innerHTML = 'Enter your 12 or 24-word mnemonic seed phrase to derive Nostr accounts, or <span id="generate-new" style="text-decoration: underline; cursor: pointer; color: var(--nl-primary-color);">generate new</span>.';
|
||||
description.style.cssText = 'margin-bottom: 12px; color: #6b7280; font-size: 14px;';
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
// Remove default placeholder text as requested
|
||||
textarea.placeholder = '';
|
||||
textarea.style.cssText = `
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
padding: 12px;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 12px;
|
||||
resize: none;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
|
||||
// Add real-time mnemonic validation
|
||||
const formatHint = document.createElement('div');
|
||||
formatHint.style.cssText = 'margin-bottom: 16px; font-size: 12px; color: #6b7280; min-height: 16px;';
|
||||
|
||||
const importButton = document.createElement('button');
|
||||
importButton.textContent = 'Import Accounts';
|
||||
importButton.disabled = true;
|
||||
importButton.onclick = () => {
|
||||
if (!importButton.disabled) {
|
||||
this._importFromSeedPhrase(textarea.value);
|
||||
}
|
||||
};
|
||||
|
||||
// Set initial disabled state
|
||||
importButton.style.cssText = `
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: var(--nl-border-width) solid var(--nl-muted-color);
|
||||
border-radius: var(--nl-border-radius);
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
cursor: not-allowed;
|
||||
transition: all 0.2s;
|
||||
font-family: var(--nl-font-family, 'Courier New', monospace);
|
||||
background: var(--nl-secondary-color);
|
||||
color: var(--nl-muted-color);
|
||||
`;
|
||||
|
||||
textarea.oninput = () => {
|
||||
const value = textarea.value.trim();
|
||||
if (!value) {
|
||||
formatHint.textContent = '';
|
||||
// Disable button
|
||||
importButton.disabled = true;
|
||||
importButton.style.borderColor = 'var(--nl-muted-color)';
|
||||
importButton.style.color = 'var(--nl-muted-color)';
|
||||
importButton.style.cursor = 'not-allowed';
|
||||
return;
|
||||
}
|
||||
|
||||
const isValid = this._validateMnemonic(value);
|
||||
if (isValid) {
|
||||
const wordCount = value.split(/\s+/).length;
|
||||
formatHint.textContent = `✅ Valid ${wordCount}-word mnemonic detected`;
|
||||
formatHint.style.color = '#059669';
|
||||
// Enable button
|
||||
importButton.disabled = false;
|
||||
importButton.style.borderColor = 'var(--nl-primary-color)';
|
||||
importButton.style.color = 'var(--nl-primary-color)';
|
||||
importButton.style.cursor = 'pointer';
|
||||
} else {
|
||||
formatHint.textContent = '❌ Invalid mnemonic - must be 12 or 24 valid BIP-39 words';
|
||||
formatHint.style.color = '#dc2626';
|
||||
// Disable button
|
||||
importButton.disabled = true;
|
||||
importButton.style.borderColor = 'var(--nl-muted-color)';
|
||||
importButton.style.color = 'var(--nl-muted-color)';
|
||||
importButton.style.cursor = 'not-allowed';
|
||||
}
|
||||
};
|
||||
|
||||
const backButton = document.createElement('button');
|
||||
backButton.textContent = 'Back';
|
||||
backButton.onclick = () => this._renderLoginOptions();
|
||||
backButton.style.cssText = this._getButtonStyle('secondary') + 'margin-top: 12px;';
|
||||
|
||||
this.modalBody.appendChild(description);
|
||||
this.modalBody.appendChild(textarea);
|
||||
this.modalBody.appendChild(formatHint);
|
||||
this.modalBody.appendChild(importButton);
|
||||
this.modalBody.appendChild(backButton);
|
||||
|
||||
// Add click handler for the "generate new" link
|
||||
const generateLink = document.getElementById('generate-new');
|
||||
if (generateLink) {
|
||||
generateLink.addEventListener('mouseenter', () => {
|
||||
generateLink.style.color = 'var(--nl-accent-color)';
|
||||
});
|
||||
generateLink.addEventListener('mouseleave', () => {
|
||||
generateLink.style.color = 'var(--nl-primary-color)';
|
||||
});
|
||||
generateLink.addEventListener('click', () => {
|
||||
this._generateNewSeedPhrase(textarea, formatHint);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
_generateNewSeedPhrase(textarea, formatHint) {
|
||||
try {
|
||||
// Check if NIP-06 is available
|
||||
if (!window.NostrTools?.nip06) {
|
||||
throw new Error('NIP-06 not available in bundle');
|
||||
}
|
||||
|
||||
// Generate a random 12-word mnemonic using NostrTools
|
||||
const mnemonic = window.NostrTools.nip06.generateSeedWords();
|
||||
|
||||
// Set the generated mnemonic in the textarea
|
||||
textarea.value = mnemonic;
|
||||
|
||||
// Trigger the oninput event to properly validate and enable the button
|
||||
if (textarea.oninput) {
|
||||
textarea.oninput();
|
||||
}
|
||||
|
||||
console.log('Generated new seed phrase:', mnemonic.split(/\s+/).length, 'words');
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to generate seed phrase:', error);
|
||||
formatHint.textContent = '❌ Failed to generate seed phrase - NIP-06 not available';
|
||||
formatHint.style.color = '#dc2626';
|
||||
}
|
||||
}
|
||||
|
||||
_validateMnemonic(mnemonic) {
|
||||
try {
|
||||
// Check if NIP-06 is available
|
||||
if (!window.NostrTools?.nip06) {
|
||||
console.error('NIP-06 not available in bundle');
|
||||
return false;
|
||||
}
|
||||
|
||||
const words = mnemonic.trim().split(/\s+/);
|
||||
|
||||
// Must be 12 or 24 words
|
||||
if (words.length !== 12 && words.length !== 24) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Try to validate using NostrTools nip06 - this will throw if invalid
|
||||
window.NostrTools.nip06.privateKeyFromSeedWords(mnemonic, '', 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.log('Mnemonic validation failed:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_importFromSeedPhrase(mnemonic) {
|
||||
try {
|
||||
const trimmed = mnemonic.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error('Please enter a mnemonic seed phrase');
|
||||
}
|
||||
|
||||
// Validate the mnemonic
|
||||
if (!this._validateMnemonic(trimmed)) {
|
||||
throw new Error('Invalid mnemonic. Please enter a valid 12 or 24-word BIP-39 seed phrase');
|
||||
}
|
||||
|
||||
// Generate accounts 0-5 using NIP-06
|
||||
const accounts = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
try {
|
||||
const privateKey = window.NostrTools.nip06.privateKeyFromSeedWords(trimmed, '', i);
|
||||
const publicKey = window.NostrTools.getPublicKey(privateKey);
|
||||
const nsec = window.NostrTools.nip19.nsecEncode(privateKey);
|
||||
const npub = window.NostrTools.nip19.npubEncode(publicKey);
|
||||
|
||||
accounts.push({
|
||||
index: i,
|
||||
privateKey,
|
||||
publicKey,
|
||||
nsec,
|
||||
npub
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Failed to derive account ${i}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (accounts.length === 0) {
|
||||
throw new Error('Failed to derive any accounts from seed phrase');
|
||||
}
|
||||
|
||||
console.log(`Successfully derived ${accounts.length} accounts from seed phrase`);
|
||||
this._showAccountSelection(accounts);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Seed phrase import failed:', error);
|
||||
this._showError('Seed phrase import failed: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
_showAccountSelection(accounts) {
|
||||
this.modalBody.innerHTML = '';
|
||||
|
||||
const description = document.createElement('p');
|
||||
description.textContent = `Select which account to use (${accounts.length} accounts derived from seed phrase):`;
|
||||
description.style.cssText = 'margin-bottom: 20px; color: #6b7280; font-size: 14px;';
|
||||
|
||||
this.modalBody.appendChild(description);
|
||||
|
||||
// Create table for account selection
|
||||
const table = document.createElement('table');
|
||||
table.style.cssText = `
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 20px;
|
||||
font-family: var(--nl-font-family, 'Courier New', monospace);
|
||||
font-size: 12px;
|
||||
`;
|
||||
|
||||
// Table header
|
||||
const thead = document.createElement('thead');
|
||||
thead.innerHTML = `
|
||||
<tr style="background: #f3f4f6;">
|
||||
<th style="padding: 8px; text-align: center; border: 1px solid #d1d5db; font-weight: bold;">#</th>
|
||||
<th style="padding: 8px; text-align: center; border: 1px solid #d1d5db; font-weight: bold;">Use</th>
|
||||
</tr>
|
||||
`;
|
||||
table.appendChild(thead);
|
||||
|
||||
// Table body
|
||||
const tbody = document.createElement('tbody');
|
||||
accounts.forEach(account => {
|
||||
const row = document.createElement('tr');
|
||||
row.style.cssText = 'border: 1px solid #d1d5db;';
|
||||
|
||||
const indexCell = document.createElement('td');
|
||||
indexCell.textContent = account.index;
|
||||
indexCell.style.cssText = 'padding: 8px; text-align: center; border: 1px solid #d1d5db; font-weight: bold;';
|
||||
|
||||
const actionCell = document.createElement('td');
|
||||
actionCell.style.cssText = 'padding: 8px; border: 1px solid #d1d5db;';
|
||||
|
||||
// Show truncated npub in the button
|
||||
const truncatedNpub = `${account.npub.slice(0, 12)}...${account.npub.slice(-8)}`;
|
||||
|
||||
const selectButton = document.createElement('button');
|
||||
selectButton.textContent = truncatedNpub;
|
||||
selectButton.onclick = () => this._selectAccount(account);
|
||||
selectButton.style.cssText = `
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
font-size: 11px;
|
||||
background: var(--nl-secondary-color);
|
||||
color: var(--nl-primary-color);
|
||||
border: 1px solid var(--nl-primary-color);
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-family: 'Courier New', monospace;
|
||||
text-align: center;
|
||||
`;
|
||||
selectButton.onmouseover = () => {
|
||||
selectButton.style.borderColor = 'var(--nl-accent-color)';
|
||||
};
|
||||
selectButton.onmouseout = () => {
|
||||
selectButton.style.borderColor = 'var(--nl-primary-color)';
|
||||
};
|
||||
|
||||
actionCell.appendChild(selectButton);
|
||||
|
||||
row.appendChild(indexCell);
|
||||
row.appendChild(actionCell);
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
table.appendChild(tbody);
|
||||
|
||||
this.modalBody.appendChild(table);
|
||||
|
||||
// Back button
|
||||
const backButton = document.createElement('button');
|
||||
backButton.textContent = 'Back to Seed Phrase';
|
||||
backButton.onclick = () => this._showSeedPhraseScreen();
|
||||
backButton.style.cssText = this._getButtonStyle('secondary');
|
||||
|
||||
this.modalBody.appendChild(backButton);
|
||||
}
|
||||
|
||||
_selectAccount(account) {
|
||||
console.log('Selected account:', account.index, account.npub);
|
||||
|
||||
// Use the same auth method as local keys, but with seedphrase identifier
|
||||
this._setAuthMethod('local', {
|
||||
secret: account.nsec,
|
||||
pubkey: account.publicKey,
|
||||
source: 'seedphrase',
|
||||
accountIndex: account.index
|
||||
});
|
||||
}
|
||||
|
||||
_showOtpScreen() {
|
||||
// Placeholder for OTP functionality
|
||||
this._showError('OTP/DM not yet implemented - coming soon!');
|
||||
|
||||
413
login_logic.md
Normal file
413
login_logic.md
Normal file
@@ -0,0 +1,413 @@
|
||||
# NOSTR_LOGIN_LITE - Login Logic Analysis
|
||||
|
||||
This document explains the complete login and authentication flow for the NOSTR_LOGIN_LITE library, including how state is maintained upon page refresh.
|
||||
|
||||
## System Architecture Overview
|
||||
|
||||
The library uses a **modular authentication architecture** with these key components:
|
||||
|
||||
1. **FloatingTab** - UI component for login trigger and status display
|
||||
2. **Modal** - UI component for authentication method selection
|
||||
3. **NostrLite** - Main library coordinator and facade manager
|
||||
4. **WindowNostr** - NIP-07 compliant facade for non-extension methods
|
||||
5. **AuthManager** - Persistent state management with encryption
|
||||
6. **Extension Bridge** - Browser extension detection and management
|
||||
|
||||
## Authentication Flow Diagrams
|
||||
|
||||
### Initial Page Load Flow
|
||||
|
||||
```
|
||||
┌─────────────────────┐
|
||||
│ Page Loads │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ NOSTR_LOGIN_LITE │
|
||||
│ .init() called │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐ YES ┌─────────────────────┐
|
||||
│ Real extension │──────────▶│ Extension-First │
|
||||
│ detected? │ │ Mode: Don't install │
|
||||
└─────────┬───────────┘ │ facade │
|
||||
│ NO └─────────────────────┘
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ Install WindowNostr │
|
||||
│ facade for local/ │
|
||||
│ NIP-46/readonly │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐ YES ┌─────────────────────┐
|
||||
│ Persistence │──────────▶│ _attemptAuthRestore │
|
||||
│ enabled? │ │ called │
|
||||
└─────────┬───────────┘ └─────────┬───────────┘
|
||||
│ NO │
|
||||
▼ ▼
|
||||
┌─────────────────────┐ ┌─────────────────────┐
|
||||
│ Initialization │ │ Check storage for │
|
||||
│ complete │ │ saved auth state │
|
||||
└─────────────────────┘ └─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐ YES
|
||||
│ Valid auth state │────────┐
|
||||
│ found? │ │
|
||||
└─────────┬───────────┘ │
|
||||
│ NO │
|
||||
▼ ▼
|
||||
┌─────────────────────┐ ┌─────────────────────┐
|
||||
│ Show login UI │ │ Restore auth & │
|
||||
│ (FloatingTab,etc) │ │ dispatch events │
|
||||
└─────────────────────┘ └─────────────────────┘
|
||||
```
|
||||
|
||||
### User-Initiated Login Flow
|
||||
|
||||
```
|
||||
┌─────────────────────┐ ┌─────────────────────┐
|
||||
│ User clicks │ │ User clicks │
|
||||
│ FloatingTab │ │ Login Button │
|
||||
└─────────┬───────────┘ └─────────┬───────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────────────────┐ │
|
||||
│ Extension │ │
|
||||
│ available? │ │
|
||||
└─────────┬───────────┘ │
|
||||
│ YES │
|
||||
▼ │
|
||||
┌─────────────────────┐ │
|
||||
│ Auto-try extension │ │
|
||||
│ authentication │ │
|
||||
└─────────┬───────────┘ │
|
||||
│ SUCCESS │
|
||||
▼ │
|
||||
┌─────────────────────┐ │
|
||||
│ Authentication │ │
|
||||
│ complete │◀──────────────────┘
|
||||
└─────────────────────┘ │ FAIL OR ALWAYS
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ Open Modal with │
|
||||
│ method selection: │
|
||||
│ • Extension │
|
||||
│ • Local Key │
|
||||
│ • NIP-46 Connect │
|
||||
│ • Read-only │
|
||||
│ • OTP/DM │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ User selects method │
|
||||
│ and completes auth │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ Authentication │
|
||||
│ complete │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
### Authentication Storage & Persistence Flow
|
||||
|
||||
```
|
||||
┌─────────────────────┐
|
||||
│ Authentication │
|
||||
│ successful │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ nlMethodSelected │
|
||||
│ event dispatched │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐ Extension? ┌─────────────────────┐
|
||||
│ AuthManager. │─────────────────▶│ Store verification │
|
||||
│ saveAuthState() │ │ data only (no │
|
||||
└─────────┬───────────┘ │ secrets) │
|
||||
│ Local Key? └─────────────────────┘
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ Encrypt secret key │
|
||||
│ with session │
|
||||
│ password + AES-GCM │
|
||||
└─────────┬───────────┘
|
||||
│ NIP-46?
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ Store connection │
|
||||
│ parameters (no │
|
||||
│ secrets) │
|
||||
└─────────┬───────────┘
|
||||
│ Read-only?
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ Store method only │
|
||||
│ (no secrets) │
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐ isolateSession? ┌─────────────────────┐
|
||||
│ Choose storage: │─────────YES─────────▶│ sessionStorage │
|
||||
│ localStorage vs │ │ (per-window) │
|
||||
│ sessionStorage │◀────────NO───────────┤ │
|
||||
└─────────┬───────────┘ └─────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ localStorage │
|
||||
│ (cross-window) │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
## Key Decision Points and Logic
|
||||
|
||||
### 1. Extension Detection Logic (Line 994-1046)
|
||||
|
||||
**Function:** `NostrLite._isRealExtension(obj)`
|
||||
|
||||
```javascript
|
||||
// Conservative extension detection
|
||||
if (!obj || typeof obj !== 'object') return false;
|
||||
if (typeof obj.getPublicKey !== 'function' || typeof obj.signEvent !== 'function') return false;
|
||||
|
||||
// Exclude our own classes
|
||||
const constructorName = obj.constructor?.name;
|
||||
if (constructorName === 'WindowNostr' || constructorName === 'NostrLite') return false;
|
||||
if (obj === window.NostrTools) return false;
|
||||
|
||||
// Look for extension indicators
|
||||
const extensionIndicators = [
|
||||
'_isEnabled', 'enabled', 'kind', '_eventEmitter', '_scope',
|
||||
'_requests', '_pubkey', 'name', 'version', 'description'
|
||||
];
|
||||
const hasIndicators = extensionIndicators.some(prop => obj.hasOwnProperty(prop));
|
||||
const hasExtensionConstructor = constructorName &&
|
||||
constructorName !== 'Object' &&
|
||||
constructorName !== 'Function';
|
||||
|
||||
return hasIndicators || hasExtensionConstructor;
|
||||
```
|
||||
|
||||
### 2. Facade Installation Decision (Line 942-972)
|
||||
|
||||
**Function:** `NostrLite._setupWindowNostrFacade()`
|
||||
|
||||
```
|
||||
Extension detected? ──YES──▶ DON'T install facade
|
||||
Store reference for persistence
|
||||
│
|
||||
NO
|
||||
▼
|
||||
Install WindowNostr facade ──▶ Handle local/NIP-46/readonly methods
|
||||
```
|
||||
|
||||
### 3. FloatingTab Click Behavior (Line 351-369)
|
||||
|
||||
**Current UX Inconsistency Issue:**
|
||||
|
||||
```javascript
|
||||
async _handleClick() {
|
||||
if (this.isAuthenticated && this.options.behavior.showUserInfo) {
|
||||
this._showUserMenu(); // Show user options
|
||||
} else {
|
||||
// INCONSISTENCY: Auto-tries extension instead of opening modal
|
||||
if (window.nostr && this._isRealExtension(window.nostr)) {
|
||||
await this._tryExtensionLogin(window.nostr); // Automatic extension attempt
|
||||
} else {
|
||||
if (this.modal) {
|
||||
this.modal.open({ startScreen: 'login' }); // Fallback to modal
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Comparison with Login Button behavior:**
|
||||
- Login Button: **Always** opens modal for user choice
|
||||
- FloatingTab: **Auto-tries extension first**, only shows modal if denied
|
||||
|
||||
### 4. Authentication Restoration on Page Refresh
|
||||
|
||||
**Two-Path System:**
|
||||
|
||||
#### Path 1: Extension Mode (Line 1115-1173)
|
||||
```javascript
|
||||
async _attemptExtensionRestore() {
|
||||
const authManager = new AuthManager({ isolateSession: this.options?.isolateSession });
|
||||
const storedAuth = await authManager.restoreAuthState();
|
||||
|
||||
if (!storedAuth || storedAuth.method !== 'extension') return null;
|
||||
|
||||
// Verify extension still works with same pubkey
|
||||
if (!window.nostr || !this._isRealExtension(window.nostr)) return null;
|
||||
|
||||
const currentPubkey = await window.nostr.getPublicKey();
|
||||
if (currentPubkey !== storedAuth.pubkey) return null;
|
||||
|
||||
// Dispatch nlAuthRestored event for UI updates
|
||||
window.dispatchEvent(new CustomEvent('nlAuthRestored', { detail: extensionAuth }));
|
||||
}
|
||||
```
|
||||
|
||||
#### Path 2: Non-Extension Mode (Line 1080-1098)
|
||||
```javascript
|
||||
// Uses facade's restoreAuthState method
|
||||
if (this.facadeInstalled && window.nostr?.restoreAuthState) {
|
||||
const restoredAuth = await window.nostr.restoreAuthState();
|
||||
|
||||
if (restoredAuth) {
|
||||
// Handle NIP-46 reconnection if needed
|
||||
if (restoredAuth.requiresReconnection) {
|
||||
this._showReconnectionPrompt(restoredAuth);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Storage Strategy (Line 1408-1414)
|
||||
|
||||
**Storage Type Selection:**
|
||||
```javascript
|
||||
if (options.isolateSession) {
|
||||
this.storage = sessionStorage; // Per-window isolation
|
||||
} else {
|
||||
this.storage = localStorage; // Cross-window persistence
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Event-Driven State Synchronization
|
||||
|
||||
**Key Events:**
|
||||
- `nlMethodSelected` - Dispatched when user completes authentication
|
||||
- `nlAuthRestored` - Dispatched when authentication is restored from storage
|
||||
- `nlLogout` - Dispatched when user logs out
|
||||
- `nlReconnectionRequired` - Dispatched when NIP-46 needs reconnection
|
||||
|
||||
**Event Listeners:**
|
||||
- FloatingTab listens to all auth events for UI updates (Line 271-295)
|
||||
- WindowNostr listens to nlMethodSelected/nlLogout for state management (Line 823-869)
|
||||
|
||||
## State Persistence Security Model
|
||||
|
||||
### By Authentication Method:
|
||||
|
||||
**Extension:**
|
||||
- ✅ Store: pubkey, verification metadata
|
||||
- ❌ Never store: extension object, secrets
|
||||
- 🔒 Security: Minimal data, 1-hour expiry
|
||||
|
||||
**Local Key:**
|
||||
- ✅ Store: encrypted secret key, pubkey
|
||||
- 🔒 Security: AES-GCM encryption with session-specific password
|
||||
- 🔑 Session password stored in sessionStorage (cleared on tab close)
|
||||
|
||||
**NIP-46:**
|
||||
- ✅ Store: connection parameters, pubkey
|
||||
- ❌ Never store: session secrets
|
||||
- 🔄 Requires: User reconnection on restore
|
||||
|
||||
**Read-only:**
|
||||
- ✅ Store: method type, pubkey
|
||||
- ❌ No secrets to store
|
||||
|
||||
## Current Issues Identified
|
||||
|
||||
### UX Inconsistency (THE MAIN ISSUE)
|
||||
**Problem:** FloatingTab and Login Button have different click behaviors
|
||||
- **FloatingTab:** Auto-tries extension → Falls back to modal if denied
|
||||
- **Login Button:** Always opens modal for user choice
|
||||
|
||||
**Impact:**
|
||||
- Confusing user experience
|
||||
- Inconsistent interaction patterns
|
||||
- Users don't get consistent choice of authentication method
|
||||
|
||||
**Root Cause:** Line 358-367 in FloatingTab._handleClick() method
|
||||
|
||||
### Proposed Solutions:
|
||||
|
||||
#### Option 1: Make FloatingTab Consistent (Recommended)
|
||||
```javascript
|
||||
async _handleClick() {
|
||||
if (this.isAuthenticated && this.options.behavior.showUserInfo) {
|
||||
this._showUserMenu();
|
||||
} else {
|
||||
// Always open modal - consistent with login button
|
||||
if (this.modal) {
|
||||
this.modal.open({ startScreen: 'login' });
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Option 2: Add Configuration Option
|
||||
```javascript
|
||||
floatingTab: {
|
||||
behavior: {
|
||||
autoTryExtension: false, // Default to consistent behavior
|
||||
// ... other options
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ⚠️ IMPLEMENTATION STATUS: READY FOR CODE CHANGES
|
||||
|
||||
**User Decision:** FloatingTab should behave exactly like login buttons - always open modal for authentication method selection.
|
||||
|
||||
**Required Changes:**
|
||||
1. **File:** `lite/build.js`
|
||||
2. **Method:** `FloatingTab._handleClick()` (lines 351-369)
|
||||
3. **Action:** Remove extension auto-detection, always open modal
|
||||
|
||||
**Current Code to Replace (lines 358-367):**
|
||||
```javascript
|
||||
// Check if extension is available for direct login
|
||||
if (window.nostr && this._isRealExtension(window.nostr)) {
|
||||
console.log('FloatingTab: Extension available, attempting direct extension login');
|
||||
await this._tryExtensionLogin(window.nostr);
|
||||
} else {
|
||||
// Open login modal
|
||||
if (this.modal) {
|
||||
this.modal.open({ startScreen: 'login' });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Replacement Code:**
|
||||
```javascript
|
||||
// Always open login modal (consistent with login buttons)
|
||||
if (this.modal) {
|
||||
this.modal.open({ startScreen: 'login' });
|
||||
}
|
||||
```
|
||||
|
||||
**Critical Safety Notes:**
|
||||
- ✅ **DO NOT** change `_checkExistingAuth()` method (lines 299-349) - this handles automatic restoration on page refresh
|
||||
- ✅ **ONLY** change the click handler to remove manual extension detection
|
||||
- ✅ Authentication restoration will continue to work properly via the separate restoration system
|
||||
- ✅ Extension detection logic remains intact for other purposes (storage, verification, etc.)
|
||||
|
||||
**After Implementation:**
|
||||
- Rebuild the library with `node lite/build.js`
|
||||
- Test that both floating tab and login buttons behave identically
|
||||
- Verify that automatic login restoration on page refresh still works properly
|
||||
|
||||
## Important Notes
|
||||
|
||||
1. **Extension-First Architecture:** The system never interferes with real browser extensions
|
||||
2. **Dual Storage Support:** Supports both per-window (sessionStorage) and cross-window (localStorage) persistence
|
||||
3. **Security-First:** Sensitive data is always encrypted or not stored
|
||||
4. **Event-Driven:** All components communicate via custom events
|
||||
5. **Automatic Restoration:** Authentication state is automatically restored on page refresh when possible
|
||||
|
||||
The login logic is complex due to supporting multiple authentication methods, security requirements, and different storage strategies, but it provides a flexible and secure authentication system for Nostr applications.
|
||||
1
nostr-tools
Submodule
1
nostr-tools
Submodule
Submodule nostr-tools added at 23aebbd341
@@ -9,7 +9,7 @@
|
||||
--nl-primary-color: #000000;
|
||||
--nl-secondary-color: #ffffff;
|
||||
--nl-accent-color: #ff0000;
|
||||
--nl-muted-color: #666666;
|
||||
--nl-muted-color: #CCCCCC;
|
||||
--nl-font-family: "Courier New", Courier, monospace;
|
||||
--nl-border-radius: 15px;
|
||||
--nl-border-width: 3px;
|
||||
|
||||
Reference in New Issue
Block a user