04/16 Upload codebase
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
from flask import Flask, render_template
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_login import LoginManager
|
||||
from flask_wtf.csrf import CSRFProtect
|
||||
from flask_limiter import Limiter
|
||||
from flask_limiter.util import get_remote_address
|
||||
from flask_cors import CORS
|
||||
|
||||
from .config import config
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
login_manager = LoginManager()
|
||||
csrf = CSRFProtect()
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
|
||||
|
||||
def create_app(config_name: str = 'development') -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
# Extensions
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
login_manager.init_app(app)
|
||||
csrf.init_app(app)
|
||||
limiter.init_app(app)
|
||||
CORS(app, resources={r'/api/*': {'origins': '*'}})
|
||||
|
||||
# Ensure all models are imported so SQLAlchemy knows about them
|
||||
from .models.user import User
|
||||
from .models.folder import Folder
|
||||
from .models.vault_item import VaultItem
|
||||
from .models.token_blacklist import TokenBlacklist
|
||||
from .models.shared_item import SharedItem
|
||||
from .models.emergency_access import EmergencyAccess
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id):
|
||||
return User.query.get(int(user_id))
|
||||
|
||||
# Blueprints
|
||||
from .routes.auth import auth_bp
|
||||
from .routes.vault import vault_bp
|
||||
from .routes.folders import folders_bp
|
||||
from .routes.sharing import sharing_bp
|
||||
from .routes.emergency import emergency_bp
|
||||
|
||||
app.register_blueprint(auth_bp, url_prefix='/api/auth')
|
||||
app.register_blueprint(vault_bp, url_prefix='/api/vault')
|
||||
app.register_blueprint(folders_bp, url_prefix='/api/folders')
|
||||
app.register_blueprint(sharing_bp, url_prefix='/api/sharing')
|
||||
app.register_blueprint(emergency_bp, url_prefix='/api/emergency')
|
||||
|
||||
# Exempt all API blueprints from CSRF — JWT bearer tokens make CSRF irrelevant
|
||||
csrf.exempt(auth_bp)
|
||||
csrf.exempt(vault_bp)
|
||||
csrf.exempt(folders_bp)
|
||||
csrf.exempt(sharing_bp)
|
||||
csrf.exempt(emergency_bp)
|
||||
|
||||
# Page-serving routes
|
||||
@app.route('/')
|
||||
@app.route('/login')
|
||||
def login_page():
|
||||
return render_template('auth/login.html')
|
||||
|
||||
@app.route('/register')
|
||||
def register_page():
|
||||
return render_template('auth/register.html')
|
||||
|
||||
@app.route('/vault')
|
||||
def vault_page():
|
||||
return render_template('vault/index.html')
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,52 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class BaseConfig:
|
||||
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-change-me')
|
||||
JWT_SECRET_KEY = os.environ.get('JWT_SECRET_KEY', 'jwt-secret-change-me')
|
||||
JWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=15)
|
||||
JWT_REFRESH_TOKEN_EXPIRES = timedelta(days=7)
|
||||
|
||||
SQLALCHEMY_DATABASE_URI = (
|
||||
'mysql+pymysql://{user}:{password}@{host}:{port}/{db}?charset=utf8mb4'.format(
|
||||
user=os.environ.get('MYSQL_USER', 'passkeeper'),
|
||||
password=os.environ.get('MYSQL_PASSWORD', ''),
|
||||
host=os.environ.get('MYSQL_HOST', '127.0.0.1'),
|
||||
port=os.environ.get('MYSQL_PORT', '3306'),
|
||||
db=os.environ.get('MYSQL_DB', 'passkeeper'),
|
||||
)
|
||||
)
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
|
||||
WTF_CSRF_ENABLED = True
|
||||
WTF_CSRF_TIME_LIMIT = 3600
|
||||
|
||||
ARGON2_TIME_COST = int(os.environ.get('ARGON2_TIME_COST', 3))
|
||||
ARGON2_MEMORY_COST = int(os.environ.get('ARGON2_MEMORY_COST', 65536))
|
||||
ARGON2_PARALLELISM = int(os.environ.get('ARGON2_PARALLELISM', 4))
|
||||
|
||||
RATELIMIT_STORAGE_URI = 'memory://'
|
||||
|
||||
|
||||
class DevelopmentConfig(BaseConfig):
|
||||
DEBUG = True
|
||||
RATELIMIT_ENABLED = False
|
||||
|
||||
|
||||
class ProductionConfig(BaseConfig):
|
||||
DEBUG = False
|
||||
RATELIMIT_ENABLED = True
|
||||
# Force HTTPS in production
|
||||
SESSION_COOKIE_SECURE = True
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = 'Lax'
|
||||
|
||||
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'production': ProductionConfig,
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy.dialects.mysql import INTEGER
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class EmergencyAccess(db.Model):
|
||||
"""
|
||||
Emergency access grant from a vault owner (grantor) to a trusted contact (grantee).
|
||||
|
||||
Status flow:
|
||||
invited → grantee calls /accept → accepted
|
||||
accepted → grantor calls /provide → ready (enc_vault stored)
|
||||
ready → grantee calls /request → pending (wait timer starts)
|
||||
pending → grantor calls /deny → ready (reset, grantee can request again)
|
||||
pending (wait_days elapsed) → grantable (grantee fetches vault)
|
||||
|
||||
Zero-knowledge: enc_vault is a JSON array of vault items re-encrypted by the grantor
|
||||
using the ECDH shared secret (grantor private key + grantee public key).
|
||||
"""
|
||||
__tablename__ = 'emergency_access'
|
||||
|
||||
id = db.Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)
|
||||
grantor_id = db.Column(
|
||||
INTEGER(unsigned=True),
|
||||
db.ForeignKey('users.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
)
|
||||
grantee_email = db.Column(db.String(255), nullable=False)
|
||||
grantee_id = db.Column(
|
||||
INTEGER(unsigned=True),
|
||||
db.ForeignKey('users.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
)
|
||||
wait_days = db.Column(db.Integer, default=7, nullable=False)
|
||||
# invited | accepted | ready | pending | denied
|
||||
status = db.Column(db.String(20), default='invited', nullable=False)
|
||||
request_initiated_at = db.Column(db.DateTime, nullable=True)
|
||||
# JSON string: [{ id, name, item_type, enc_data, iv }, ...]
|
||||
enc_vault = db.Column(db.Text, nullable=True)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
@property
|
||||
def wait_elapsed(self):
|
||||
"""True if the wait period has passed since the access request."""
|
||||
if self.status != 'pending' or not self.request_initiated_at:
|
||||
return False
|
||||
return datetime.utcnow() >= self.request_initiated_at + timedelta(days=self.wait_days)
|
||||
|
||||
def to_dict(self, grantor_email=None):
|
||||
return {
|
||||
'id': self.id,
|
||||
'grantor_id': self.grantor_id,
|
||||
'grantor_email': grantor_email,
|
||||
'grantee_email': self.grantee_email,
|
||||
'grantee_id': self.grantee_id,
|
||||
'wait_days': self.wait_days,
|
||||
'status': self.status,
|
||||
'wait_elapsed': self.wait_elapsed,
|
||||
'request_initiated_at': (
|
||||
self.request_initiated_at.isoformat() if self.request_initiated_at else None
|
||||
),
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
from sqlalchemy.dialects.mysql import INTEGER
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class Folder(db.Model):
|
||||
__tablename__ = 'folders'
|
||||
|
||||
id = db.Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)
|
||||
user_id = db.Column(INTEGER(unsigned=True), db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
name = db.Column(db.String(128), nullable=False)
|
||||
|
||||
vault_items = db.relationship('VaultItem', backref='folder', lazy='dynamic')
|
||||
|
||||
def to_dict(self):
|
||||
return {'id': self.id, 'name': self.name}
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Folder {self.name}>'
|
||||
@@ -0,0 +1,58 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy.dialects.mysql import INTEGER
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class SharedItem(db.Model):
|
||||
"""
|
||||
A vault item shared by one user with another.
|
||||
|
||||
Zero-knowledge: enc_data is re-encrypted by the SENDER using the ECDH shared
|
||||
secret derived from sender's private key + recipient's P-256 public key.
|
||||
The server stores only the ciphertext — it cannot decrypt it.
|
||||
"""
|
||||
__tablename__ = 'shared_items'
|
||||
|
||||
id = db.Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)
|
||||
item_id = db.Column(
|
||||
INTEGER(unsigned=True),
|
||||
db.ForeignKey('vault_items.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
)
|
||||
owner_id = db.Column(
|
||||
INTEGER(unsigned=True),
|
||||
db.ForeignKey('users.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
)
|
||||
recipient_email = db.Column(db.String(255), nullable=False)
|
||||
recipient_id = db.Column(
|
||||
INTEGER(unsigned=True),
|
||||
db.ForeignKey('users.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
)
|
||||
# Plaintext metadata — not sensitive, used for display before decryption
|
||||
item_name = db.Column(db.String(255), nullable=False)
|
||||
item_type = db.Column(db.String(20), nullable=False, default='password')
|
||||
# ECDH-encrypted payload
|
||||
enc_data = db.Column(db.Text, nullable=False)
|
||||
iv = db.Column(db.String(64), nullable=False)
|
||||
|
||||
accepted = db.Column(db.Boolean, default=False, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'item_id': self.item_id,
|
||||
'owner_id': self.owner_id,
|
||||
'recipient_email': self.recipient_email,
|
||||
'recipient_id': self.recipient_id,
|
||||
'item_name': self.item_name,
|
||||
'item_type': self.item_type,
|
||||
'enc_data': self.enc_data,
|
||||
'iv': self.iv,
|
||||
'accepted': self.accepted,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy.dialects.mysql import INTEGER
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class TokenBlacklist(db.Model):
|
||||
"""Revoked JWT identifiers. Access and refresh tokens are added on logout."""
|
||||
__tablename__ = 'token_blacklist'
|
||||
|
||||
id = db.Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)
|
||||
jti = db.Column(db.String(36), unique=True, nullable=False, index=True)
|
||||
user_id = db.Column(INTEGER(unsigned=True), nullable=False)
|
||||
expires_at = db.Column(db.DateTime, nullable=False)
|
||||
|
||||
@classmethod
|
||||
def is_blacklisted(cls, jti: str) -> bool:
|
||||
entry = cls.query.filter_by(jti=jti).first()
|
||||
if not entry:
|
||||
return False
|
||||
# Automatically ignore expired entries (they can be cleaned up later)
|
||||
return entry.expires_at > datetime.utcnow()
|
||||
|
||||
@classmethod
|
||||
def cleanup_expired(cls):
|
||||
"""Delete entries that have already expired — call occasionally to keep table small."""
|
||||
cls.query.filter(cls.expires_at <= datetime.utcnow()).delete()
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,45 @@
|
||||
from datetime import datetime
|
||||
from flask_login import UserMixin
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
from sqlalchemy.dialects.mysql import INTEGER
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class User(db.Model, UserMixin):
|
||||
__tablename__ = 'users'
|
||||
|
||||
id = db.Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)
|
||||
email = db.Column(db.String(255), unique=True, nullable=False, index=True)
|
||||
# master_hash: Argon2id hash of the client-derived PBKDF2 auth_hash
|
||||
# The raw master password is NEVER sent to or stored on the server.
|
||||
master_hash = db.Column(db.String(255), nullable=False)
|
||||
# enc_key_salt: random 16-byte salt (base64) generated at registration.
|
||||
# Returned to the client on login so it can re-derive the AES-256-GCM vault key.
|
||||
# The server never uses this for decryption — it is opaque to us.
|
||||
enc_key_salt = db.Column(db.String(64), nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
||||
last_login = db.Column(db.DateTime, nullable=True)
|
||||
# TOTP / MFA
|
||||
totp_secret = db.Column(db.String(64), nullable=True)
|
||||
totp_enabled = db.Column(db.Boolean, default=False, nullable=False)
|
||||
# ECDH P-256 sharing keypair
|
||||
# Public key: raw uncompressed point (65 bytes), base64-encoded, stored plaintext
|
||||
sharing_public_key = db.Column(db.Text, nullable=True)
|
||||
# Private key: JWK, AES-256-GCM encrypted with the user's vault key
|
||||
sharing_private_key_enc = db.Column(db.Text, nullable=True)
|
||||
sharing_private_key_iv = db.Column(db.String(64), nullable=True)
|
||||
|
||||
folders = db.relationship('Folder', backref='owner', lazy='dynamic', cascade='all, delete-orphan')
|
||||
vault_items = db.relationship('VaultItem', backref='owner', lazy='dynamic', cascade='all, delete-orphan')
|
||||
|
||||
def check_password(self, auth_hash: str) -> bool:
|
||||
ph = PasswordHasher()
|
||||
try:
|
||||
return ph.verify(self.master_hash, auth_hash)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
def __repr__(self):
|
||||
return f'<User {self.email}>'
|
||||
@@ -0,0 +1,52 @@
|
||||
from datetime import datetime
|
||||
import enum
|
||||
|
||||
from sqlalchemy.dialects.mysql import INTEGER
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class ItemType(str, enum.Enum):
|
||||
PASSWORD = 'password'
|
||||
NOTE = 'note'
|
||||
ADDRESS = 'address'
|
||||
CARD = 'card'
|
||||
BANK = 'bank'
|
||||
SSN = 'ssn'
|
||||
PASSKEY = 'passkey'
|
||||
|
||||
|
||||
class VaultItem(db.Model):
|
||||
__tablename__ = 'vault_items'
|
||||
|
||||
id = db.Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)
|
||||
user_id = db.Column(INTEGER(unsigned=True), db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
folder_id = db.Column(INTEGER(unsigned=True), db.ForeignKey('folders.id', ondelete='SET NULL'), nullable=True)
|
||||
item_type = db.Column(db.String(20), nullable=False, default=ItemType.PASSWORD.value)
|
||||
# name is stored in plaintext for display in the vault list.
|
||||
# All other sensitive fields (username, password, URL, notes, etc.)
|
||||
# are inside enc_data and are encrypted client-side with AES-256-GCM.
|
||||
name = db.Column(db.String(255), nullable=False)
|
||||
enc_data = db.Column(db.Text, nullable=False) # base64-encoded AES-256-GCM ciphertext
|
||||
iv = db.Column(db.String(64), nullable=False) # base64-encoded 12-byte GCM nonce
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
def to_dict(self):
|
||||
# item_type is stored as a plain string; handle both str and enum safely
|
||||
item_type = self.item_type
|
||||
if isinstance(item_type, ItemType):
|
||||
item_type = item_type.value
|
||||
return {
|
||||
'id': self.id,
|
||||
'item_type': item_type,
|
||||
'name': self.name,
|
||||
'folder_id': self.folder_id,
|
||||
'enc_data': self.enc_data,
|
||||
'iv': self.iv,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
return f'<VaultItem {self.name}>'
|
||||
@@ -0,0 +1,241 @@
|
||||
import re
|
||||
import time
|
||||
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from app import db, limiter
|
||||
from app.models.user import User
|
||||
from app.services.auth_service import (
|
||||
hash_auth_token,
|
||||
verify_auth_token,
|
||||
generate_tokens,
|
||||
generate_mfa_token,
|
||||
decode_token,
|
||||
blacklist_token,
|
||||
require_jwt,
|
||||
)
|
||||
|
||||
auth_bp = Blueprint('auth', __name__)
|
||||
|
||||
EMAIL_RE = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
|
||||
|
||||
|
||||
@auth_bp.route('/register', methods=['POST'])
|
||||
@limiter.limit('10 per minute')
|
||||
def register():
|
||||
data = request.get_json(silent=True) or {}
|
||||
email = (data.get('email') or '').strip().lower()
|
||||
auth_hash = data.get('auth_hash', '')
|
||||
enc_key_salt = data.get('enc_key_salt', '')
|
||||
|
||||
if not email or not EMAIL_RE.match(email):
|
||||
return jsonify({'error': 'Invalid email address'}), 400
|
||||
if not auth_hash:
|
||||
return jsonify({'error': 'auth_hash is required'}), 400
|
||||
if not enc_key_salt:
|
||||
return jsonify({'error': 'enc_key_salt is required'}), 400
|
||||
|
||||
if User.query.filter_by(email=email).first():
|
||||
return jsonify({'error': 'Email already registered'}), 409
|
||||
|
||||
master_hash = hash_auth_token(auth_hash)
|
||||
user = User(email=email, master_hash=master_hash, enc_key_salt=enc_key_salt)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'message': 'Account created successfully'}), 201
|
||||
|
||||
|
||||
@auth_bp.route('/login', methods=['POST'])
|
||||
@limiter.limit('10 per minute')
|
||||
def login():
|
||||
data = request.get_json(silent=True) or {}
|
||||
email = (data.get('email') or '').strip().lower()
|
||||
auth_hash = data.get('auth_hash', '')
|
||||
|
||||
time.sleep(0.1) # mitigate timing-based user enumeration
|
||||
|
||||
if not email or not auth_hash:
|
||||
return jsonify({'error': 'Email and auth_hash are required'}), 400
|
||||
|
||||
user = User.query.filter_by(email=email).first()
|
||||
if not user or not verify_auth_token(auth_hash, user.master_hash):
|
||||
return jsonify({'error': 'Invalid email or password'}), 401
|
||||
|
||||
from datetime import datetime
|
||||
user.last_login = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# MFA gate: if enabled, issue a short-lived mfa_token instead of full tokens
|
||||
if user.totp_enabled:
|
||||
mfa_token = generate_mfa_token(user.id)
|
||||
return jsonify({
|
||||
'mfa_required': True,
|
||||
'mfa_token': mfa_token,
|
||||
'enc_key_salt': user.enc_key_salt,
|
||||
}), 200
|
||||
|
||||
tokens = generate_tokens(user.id)
|
||||
return jsonify({
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
'enc_key_salt': user.enc_key_salt,
|
||||
}), 200
|
||||
|
||||
|
||||
@auth_bp.route('/logout', methods=['POST'])
|
||||
def logout():
|
||||
"""Blacklist both the access token (from header) and refresh token (from body)."""
|
||||
auth_header = request.headers.get('Authorization', '')
|
||||
if auth_header.startswith('Bearer '):
|
||||
blacklist_token(auth_header[7:], 'access')
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
refresh_token = data.get('refresh_token', '')
|
||||
if refresh_token:
|
||||
blacklist_token(refresh_token, 'refresh')
|
||||
|
||||
return jsonify({'message': 'Logged out'}), 200
|
||||
|
||||
|
||||
@auth_bp.route('/refresh', methods=['POST'])
|
||||
@limiter.limit('30 per minute')
|
||||
def refresh():
|
||||
data = request.get_json(silent=True) or {}
|
||||
refresh_token = data.get('refresh_token', '')
|
||||
if not refresh_token:
|
||||
return jsonify({'error': 'refresh_token is required'}), 400
|
||||
|
||||
try:
|
||||
payload = decode_token(refresh_token, expected_type='refresh')
|
||||
except Exception:
|
||||
return jsonify({'error': 'Invalid or expired refresh token'}), 401
|
||||
|
||||
# Rotate: blacklist old refresh token and issue fresh pair
|
||||
blacklist_token(refresh_token, 'refresh')
|
||||
tokens = generate_tokens(int(payload['sub']))
|
||||
return jsonify({
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
}), 200
|
||||
|
||||
|
||||
# ── MFA / TOTP endpoints ─────────────────────────────────────────────────────
|
||||
|
||||
@auth_bp.route('/mfa/setup', methods=['GET'])
|
||||
@require_jwt
|
||||
def mfa_setup():
|
||||
"""Generate a new TOTP secret and return QR code (as base64 PNG data URI)."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
if user.totp_enabled:
|
||||
return jsonify({'error': 'MFA is already enabled'}), 400
|
||||
|
||||
import pyotp
|
||||
import qrcode
|
||||
import io
|
||||
import base64
|
||||
|
||||
secret = pyotp.random_base32()
|
||||
uri = pyotp.TOTP(secret).provisioning_uri(
|
||||
name=user.email,
|
||||
issuer_name='PassKeeper',
|
||||
)
|
||||
|
||||
img = qrcode.make(uri)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format='PNG')
|
||||
qr_b64 = base64.b64encode(buf.getvalue()).decode()
|
||||
|
||||
return jsonify({
|
||||
'secret': secret,
|
||||
'qr_code': f'data:image/png;base64,{qr_b64}',
|
||||
'uri': uri,
|
||||
}), 200
|
||||
|
||||
|
||||
@auth_bp.route('/mfa/enable', methods=['POST'])
|
||||
@require_jwt
|
||||
def mfa_enable():
|
||||
"""Enable MFA after verifying the first TOTP code."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
if user.totp_enabled:
|
||||
return jsonify({'error': 'MFA is already enabled'}), 400
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
secret = (data.get('secret') or '').strip()
|
||||
totp_code = (data.get('totp_code') or '').strip()
|
||||
|
||||
if not secret or not totp_code:
|
||||
return jsonify({'error': 'secret and totp_code are required'}), 400
|
||||
|
||||
import pyotp
|
||||
if not pyotp.TOTP(secret).verify(totp_code, valid_window=1):
|
||||
return jsonify({'error': 'Invalid verification code'}), 400
|
||||
|
||||
user.totp_secret = secret
|
||||
user.totp_enabled = True
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'message': 'MFA enabled successfully'}), 200
|
||||
|
||||
|
||||
@auth_bp.route('/mfa/disable', methods=['POST'])
|
||||
@require_jwt
|
||||
def mfa_disable():
|
||||
"""Disable MFA after verifying the current TOTP code."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
if not user.totp_enabled:
|
||||
return jsonify({'error': 'MFA is not enabled'}), 400
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
totp_code = (data.get('totp_code') or '').strip()
|
||||
|
||||
import pyotp
|
||||
if not pyotp.TOTP(user.totp_secret).verify(totp_code, valid_window=1):
|
||||
return jsonify({'error': 'Invalid verification code'}), 400
|
||||
|
||||
user.totp_secret = None
|
||||
user.totp_enabled = False
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'message': 'MFA disabled'}), 200
|
||||
|
||||
|
||||
@auth_bp.route('/mfa/verify', methods=['POST'])
|
||||
@limiter.limit('10 per minute')
|
||||
def mfa_verify():
|
||||
"""Complete MFA login: verify TOTP code and exchange mfa_token for real tokens."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
mfa_token = data.get('mfa_token', '')
|
||||
totp_code = (data.get('totp_code') or '').strip()
|
||||
|
||||
if not mfa_token or not totp_code:
|
||||
return jsonify({'error': 'mfa_token and totp_code are required'}), 400
|
||||
|
||||
try:
|
||||
payload = decode_token(mfa_token, expected_type='mfa', check_blacklist=True)
|
||||
except Exception:
|
||||
return jsonify({'error': 'Invalid or expired MFA token'}), 401
|
||||
|
||||
user = User.query.get(int(payload['sub']))
|
||||
if not user or not user.totp_enabled:
|
||||
return jsonify({'error': 'MFA not configured for this account'}), 400
|
||||
|
||||
import pyotp
|
||||
if not pyotp.TOTP(user.totp_secret).verify(totp_code, valid_window=1):
|
||||
return jsonify({'error': 'Invalid verification code'}), 400
|
||||
|
||||
# One-time use: blacklist the mfa_token
|
||||
blacklist_token(mfa_token, 'mfa')
|
||||
|
||||
tokens = generate_tokens(user.id)
|
||||
return jsonify({
|
||||
'access_token': tokens['access_token'],
|
||||
'refresh_token': tokens['refresh_token'],
|
||||
}), 200
|
||||
|
||||
|
||||
@auth_bp.route('/mfa/status', methods=['GET'])
|
||||
@require_jwt
|
||||
def mfa_status():
|
||||
user = User.query.get(g.current_user_id)
|
||||
return jsonify({'totp_enabled': user.totp_enabled}), 200
|
||||
@@ -0,0 +1,216 @@
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.models.emergency_access import EmergencyAccess
|
||||
from app.services.auth_service import require_jwt
|
||||
|
||||
emergency_bp = Blueprint('emergency', __name__)
|
||||
|
||||
|
||||
@emergency_bp.route('', methods=['GET'])
|
||||
@require_jwt
|
||||
def list_emergency():
|
||||
"""Return emergency access records both as grantor and as grantee."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
|
||||
grants = EmergencyAccess.query.filter_by(grantor_id=user.id).order_by(
|
||||
EmergencyAccess.created_at.desc()
|
||||
).all()
|
||||
|
||||
access = EmergencyAccess.query.filter(
|
||||
db.or_(
|
||||
EmergencyAccess.grantee_email == user.email,
|
||||
EmergencyAccess.grantee_id == user.id,
|
||||
)
|
||||
).order_by(EmergencyAccess.created_at.desc()).all()
|
||||
|
||||
return jsonify({
|
||||
'grants': [ea.to_dict(grantor_email=user.email) for ea in grants],
|
||||
'access': [_ea_as_grantee(ea) for ea in access],
|
||||
}), 200
|
||||
|
||||
|
||||
def _ea_as_grantee(ea: EmergencyAccess) -> dict:
|
||||
grantor = User.query.get(ea.grantor_id)
|
||||
d = ea.to_dict(grantor_email=grantor.email if grantor else None)
|
||||
d['grantor_public_key'] = grantor.sharing_public_key if grantor else None
|
||||
return d
|
||||
|
||||
|
||||
@emergency_bp.route('', methods=['POST'])
|
||||
@require_jwt
|
||||
def create_emergency():
|
||||
"""Grantor creates an emergency access invitation for a trusted contact."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
grantee_email = (data.get('grantee_email') or '').strip().lower()
|
||||
wait_days = int(data.get('wait_days', 7))
|
||||
|
||||
if not grantee_email:
|
||||
return jsonify({'error': 'grantee_email is required'}), 400
|
||||
if not (1 <= wait_days <= 90):
|
||||
return jsonify({'error': 'wait_days must be between 1 and 90'}), 400
|
||||
|
||||
owner = User.query.get(g.current_user_id)
|
||||
if owner.email == grantee_email:
|
||||
return jsonify({'error': 'Cannot designate yourself as emergency contact'}), 400
|
||||
|
||||
# No duplicate active grants
|
||||
existing = EmergencyAccess.query.filter(
|
||||
EmergencyAccess.grantor_id == g.current_user_id,
|
||||
EmergencyAccess.grantee_email == grantee_email,
|
||||
EmergencyAccess.status != 'denied',
|
||||
).first()
|
||||
if existing:
|
||||
return jsonify({'error': 'Emergency access already set up for this contact'}), 409
|
||||
|
||||
grantee = User.query.filter_by(email=grantee_email).first()
|
||||
ea = EmergencyAccess(
|
||||
grantor_id=g.current_user_id,
|
||||
grantee_email=grantee_email,
|
||||
grantee_id=grantee.id if grantee else None,
|
||||
wait_days=wait_days,
|
||||
)
|
||||
db.session.add(ea)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify(ea.to_dict(grantor_email=owner.email)), 201
|
||||
|
||||
|
||||
@emergency_bp.route('/<int:ea_id>', methods=['DELETE'])
|
||||
@require_jwt
|
||||
def delete_emergency(ea_id):
|
||||
"""Grantor removes an emergency access grant."""
|
||||
ea = EmergencyAccess.query.filter_by(id=ea_id, grantor_id=g.current_user_id).first()
|
||||
if not ea:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
db.session.delete(ea)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Emergency access removed'}), 200
|
||||
|
||||
|
||||
@emergency_bp.route('/<int:ea_id>/accept', methods=['POST'])
|
||||
@require_jwt
|
||||
def accept_emergency(ea_id):
|
||||
"""Grantee accepts an emergency access invitation."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
ea = EmergencyAccess.query.filter(
|
||||
EmergencyAccess.id == ea_id,
|
||||
EmergencyAccess.status == 'invited',
|
||||
db.or_(
|
||||
EmergencyAccess.grantee_email == user.email,
|
||||
EmergencyAccess.grantee_id == user.id,
|
||||
),
|
||||
).first()
|
||||
if not ea:
|
||||
return jsonify({'error': 'Not found or not in invited state'}), 404
|
||||
|
||||
ea.status = 'accepted'
|
||||
ea.grantee_id = user.id
|
||||
db.session.commit()
|
||||
|
||||
return jsonify(_ea_as_grantee(ea)), 200
|
||||
|
||||
|
||||
@emergency_bp.route('/<int:ea_id>/provide', methods=['POST'])
|
||||
@require_jwt
|
||||
def provide_vault(ea_id):
|
||||
"""
|
||||
Grantor provides the ECDH-encrypted vault snapshot for emergency recovery.
|
||||
|
||||
The client re-encrypts each vault item's plaintext with the ECDH shared secret
|
||||
(grantor private key + grantee public key) and sends the JSON array as enc_vault.
|
||||
"""
|
||||
ea = EmergencyAccess.query.filter_by(id=ea_id, grantor_id=g.current_user_id).first()
|
||||
if not ea:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
if ea.status not in ('accepted', 'ready'):
|
||||
return jsonify({'error': 'Emergency access must be in accepted or ready state'}), 400
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
enc_vault = data.get('enc_vault', '')
|
||||
if not enc_vault:
|
||||
return jsonify({'error': 'enc_vault (JSON array) is required'}), 400
|
||||
|
||||
ea.enc_vault = enc_vault
|
||||
ea.status = 'ready'
|
||||
db.session.commit()
|
||||
|
||||
grantor = User.query.get(g.current_user_id)
|
||||
return jsonify(ea.to_dict(grantor_email=grantor.email)), 200
|
||||
|
||||
|
||||
@emergency_bp.route('/<int:ea_id>/request', methods=['POST'])
|
||||
@require_jwt
|
||||
def request_access(ea_id):
|
||||
"""Grantee initiates an access request, starting the wait-period clock."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
ea = EmergencyAccess.query.filter(
|
||||
EmergencyAccess.id == ea_id,
|
||||
EmergencyAccess.status == 'ready',
|
||||
db.or_(
|
||||
EmergencyAccess.grantee_email == user.email,
|
||||
EmergencyAccess.grantee_id == user.id,
|
||||
),
|
||||
).first()
|
||||
if not ea:
|
||||
return jsonify({'error': 'Not found or not in ready state'}), 404
|
||||
|
||||
ea.status = 'pending'
|
||||
ea.request_initiated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
return jsonify(_ea_as_grantee(ea)), 200
|
||||
|
||||
|
||||
@emergency_bp.route('/<int:ea_id>/deny', methods=['POST'])
|
||||
@require_jwt
|
||||
def deny_access(ea_id):
|
||||
"""Grantor denies a pending access request (resets to ready)."""
|
||||
ea = EmergencyAccess.query.filter_by(id=ea_id, grantor_id=g.current_user_id).first()
|
||||
if not ea:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
if ea.status != 'pending':
|
||||
return jsonify({'error': 'No pending request to deny'}), 400
|
||||
|
||||
ea.status = 'ready'
|
||||
ea.request_initiated_at = None
|
||||
db.session.commit()
|
||||
|
||||
grantor = User.query.get(g.current_user_id)
|
||||
return jsonify(ea.to_dict(grantor_email=grantor.email)), 200
|
||||
|
||||
|
||||
@emergency_bp.route('/<int:ea_id>/vault', methods=['GET'])
|
||||
@require_jwt
|
||||
def get_emergency_vault(ea_id):
|
||||
"""
|
||||
Grantee retrieves the encrypted vault snapshot after the wait period has elapsed.
|
||||
Also returns the grantor's public key so the client can derive the ECDH secret.
|
||||
"""
|
||||
user = User.query.get(g.current_user_id)
|
||||
ea = EmergencyAccess.query.filter(
|
||||
EmergencyAccess.id == ea_id,
|
||||
db.or_(
|
||||
EmergencyAccess.grantee_email == user.email,
|
||||
EmergencyAccess.grantee_id == user.id,
|
||||
),
|
||||
).first()
|
||||
if not ea:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
if not ea.wait_elapsed:
|
||||
if ea.request_initiated_at:
|
||||
elapsed_secs = (datetime.utcnow() - ea.request_initiated_at).total_seconds()
|
||||
days_left = max(0, ea.wait_days - elapsed_secs / 86400)
|
||||
else:
|
||||
days_left = ea.wait_days
|
||||
return jsonify({
|
||||
'error': f'Wait period not yet elapsed ({days_left:.1f} day(s) remaining)'
|
||||
}), 403
|
||||
|
||||
grantor = User.query.get(ea.grantor_id)
|
||||
return jsonify({
|
||||
'enc_vault': ea.enc_vault,
|
||||
'grantor_public_key': grantor.sharing_public_key if grantor else None,
|
||||
}), 200
|
||||
@@ -0,0 +1,54 @@
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from app import db
|
||||
from app.models.folder import Folder
|
||||
from app.services.auth_service import require_jwt
|
||||
|
||||
folders_bp = Blueprint('folders', __name__)
|
||||
|
||||
|
||||
@folders_bp.route('', methods=['GET'])
|
||||
@require_jwt
|
||||
def list_folders():
|
||||
folders = Folder.query.filter_by(user_id=g.current_user_id).order_by(Folder.name.asc()).all()
|
||||
return jsonify([f.to_dict() for f in folders]), 200
|
||||
|
||||
|
||||
@folders_bp.route('', methods=['POST'])
|
||||
@require_jwt
|
||||
def create_folder():
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = (data.get('name') or '').strip()
|
||||
if not name:
|
||||
return jsonify({'error': 'name is required'}), 400
|
||||
|
||||
folder = Folder(user_id=g.current_user_id, name=name)
|
||||
db.session.add(folder)
|
||||
db.session.commit()
|
||||
return jsonify(folder.to_dict()), 201
|
||||
|
||||
|
||||
@folders_bp.route('/<int:folder_id>', methods=['PUT'])
|
||||
@require_jwt
|
||||
def update_folder(folder_id):
|
||||
folder = Folder.query.filter_by(id=folder_id, user_id=g.current_user_id).first()
|
||||
if not folder:
|
||||
return jsonify({'error': 'Folder not found'}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = (data.get('name') or '').strip()
|
||||
if not name:
|
||||
return jsonify({'error': 'name is required'}), 400
|
||||
folder.name = name
|
||||
db.session.commit()
|
||||
return jsonify(folder.to_dict()), 200
|
||||
|
||||
|
||||
@folders_bp.route('/<int:folder_id>', methods=['DELETE'])
|
||||
@require_jwt
|
||||
def delete_folder(folder_id):
|
||||
folder = Folder.query.filter_by(id=folder_id, user_id=g.current_user_id).first()
|
||||
if not folder:
|
||||
return jsonify({'error': 'Folder not found'}), 404
|
||||
db.session.delete(folder)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Folder deleted'}), 200
|
||||
@@ -0,0 +1,203 @@
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.models.shared_item import SharedItem
|
||||
from app.services.auth_service import require_jwt
|
||||
|
||||
sharing_bp = Blueprint('sharing', __name__)
|
||||
|
||||
|
||||
# ── Sharing keypair management ────────────────────────────────────────────────
|
||||
|
||||
@sharing_bp.route('/keys', methods=['GET'])
|
||||
@require_jwt
|
||||
def get_my_keys():
|
||||
"""Return current user's encrypted sharing private key (to decrypt client-side)."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
if not user.sharing_public_key:
|
||||
return jsonify({'keys_setup': False}), 200
|
||||
return jsonify({
|
||||
'keys_setup': True,
|
||||
'public_key': user.sharing_public_key,
|
||||
'private_key_enc': user.sharing_private_key_enc,
|
||||
'private_key_iv': user.sharing_private_key_iv,
|
||||
}), 200
|
||||
|
||||
|
||||
@sharing_bp.route('/keys', methods=['POST'])
|
||||
@require_jwt
|
||||
def store_my_keys():
|
||||
"""Store ECDH keypair. Public key plaintext; private key encrypted with vault key."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
public_key = data.get('public_key', '').strip()
|
||||
private_key_enc = data.get('private_key_enc', '').strip()
|
||||
private_key_iv = data.get('private_key_iv', '').strip()
|
||||
|
||||
if not public_key or not private_key_enc or not private_key_iv:
|
||||
return jsonify({'error': 'public_key, private_key_enc, and private_key_iv are required'}), 400
|
||||
|
||||
user = User.query.get(g.current_user_id)
|
||||
user.sharing_public_key = public_key
|
||||
user.sharing_private_key_enc = private_key_enc
|
||||
user.sharing_private_key_iv = private_key_iv
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'message': 'Sharing keys stored'}), 200
|
||||
|
||||
|
||||
@sharing_bp.route('/public-key', methods=['GET'])
|
||||
@require_jwt
|
||||
def get_public_key():
|
||||
"""Look up another user's ECDH public key by email (needed to create a share)."""
|
||||
email = (request.args.get('email') or '').strip().lower()
|
||||
if not email:
|
||||
return jsonify({'error': 'email query param is required'}), 400
|
||||
|
||||
user = User.query.filter_by(email=email).first()
|
||||
if not user:
|
||||
return jsonify({'error': 'User not found'}), 404
|
||||
if not user.sharing_public_key:
|
||||
return jsonify({'error': 'User has not set up sharing keys yet'}), 404
|
||||
|
||||
return jsonify({
|
||||
'user_id': user.id,
|
||||
'email': user.email,
|
||||
'public_key': user.sharing_public_key,
|
||||
}), 200
|
||||
|
||||
|
||||
# ── Outgoing shares ───────────────────────────────────────────────────────────
|
||||
|
||||
@sharing_bp.route('', methods=['GET'])
|
||||
@require_jwt
|
||||
def list_outgoing():
|
||||
"""List all items the current user has shared with others."""
|
||||
shares = (
|
||||
SharedItem.query
|
||||
.filter_by(owner_id=g.current_user_id)
|
||||
.order_by(SharedItem.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
result = []
|
||||
for s in shares:
|
||||
d = s.to_dict()
|
||||
recipient = User.query.get(s.recipient_id) if s.recipient_id else None
|
||||
d['recipient_name'] = recipient.email if recipient else s.recipient_email
|
||||
result.append(d)
|
||||
return jsonify(result), 200
|
||||
|
||||
|
||||
@sharing_bp.route('', methods=['POST'])
|
||||
@require_jwt
|
||||
def create_share():
|
||||
"""
|
||||
Share a vault item with another user.
|
||||
|
||||
The caller must already have:
|
||||
1. Fetched the recipient's public key via GET /api/sharing/public-key?email=...
|
||||
2. Loaded their own ECDH private key (decrypted client-side with vault key)
|
||||
3. Derived the ECDH shared secret
|
||||
4. Re-encrypted the item's plaintext with that shared secret → enc_data, iv
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
item_id = data.get('item_id')
|
||||
recipient_email = (data.get('recipient_email') or '').strip().lower()
|
||||
enc_data = data.get('enc_data', '')
|
||||
iv = data.get('iv', '')
|
||||
item_name = (data.get('item_name') or '').strip()
|
||||
item_type = data.get('item_type', 'password')
|
||||
|
||||
if not all([item_id, recipient_email, enc_data, iv, item_name]):
|
||||
return jsonify({'error': 'item_id, recipient_email, enc_data, iv, item_name are required'}), 400
|
||||
|
||||
owner = User.query.get(g.current_user_id)
|
||||
if owner.email == recipient_email:
|
||||
return jsonify({'error': 'Cannot share an item with yourself'}), 400
|
||||
|
||||
# Verify the item belongs to the current user
|
||||
from app.models.vault_item import VaultItem
|
||||
item = VaultItem.query.filter_by(id=item_id, user_id=g.current_user_id).first()
|
||||
if not item:
|
||||
return jsonify({'error': 'Item not found'}), 404
|
||||
|
||||
recipient = User.query.filter_by(email=recipient_email).first()
|
||||
|
||||
share = SharedItem(
|
||||
item_id=item_id,
|
||||
owner_id=g.current_user_id,
|
||||
recipient_email=recipient_email,
|
||||
recipient_id=recipient.id if recipient else None,
|
||||
item_name=item_name,
|
||||
item_type=item_type,
|
||||
enc_data=enc_data,
|
||||
iv=iv,
|
||||
)
|
||||
db.session.add(share)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify(share.to_dict()), 201
|
||||
|
||||
|
||||
@sharing_bp.route('/<int:share_id>', methods=['DELETE'])
|
||||
@require_jwt
|
||||
def delete_share(share_id):
|
||||
share = SharedItem.query.filter_by(id=share_id, owner_id=g.current_user_id).first()
|
||||
if not share:
|
||||
return jsonify({'error': 'Share not found'}), 404
|
||||
db.session.delete(share)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Share removed'}), 200
|
||||
|
||||
|
||||
# ── Inbox (received shares) ───────────────────────────────────────────────────
|
||||
|
||||
@sharing_bp.route('/inbox', methods=['GET'])
|
||||
@require_jwt
|
||||
def inbox():
|
||||
"""List all items shared with the current user."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
shares = (
|
||||
SharedItem.query
|
||||
.filter(
|
||||
db.or_(
|
||||
SharedItem.recipient_email == user.email,
|
||||
SharedItem.recipient_id == user.id,
|
||||
)
|
||||
)
|
||||
.order_by(SharedItem.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
result = []
|
||||
for s in shares:
|
||||
d = s.to_dict()
|
||||
owner = User.query.get(s.owner_id)
|
||||
d['owner_email'] = owner.email if owner else 'Unknown'
|
||||
d['owner_public_key'] = owner.sharing_public_key if owner else None
|
||||
result.append(d)
|
||||
return jsonify(result), 200
|
||||
|
||||
|
||||
@sharing_bp.route('/inbox/<int:share_id>/accept', methods=['POST'])
|
||||
@require_jwt
|
||||
def accept_share(share_id):
|
||||
"""Mark a received share as accepted (links recipient_id if not already set)."""
|
||||
user = User.query.get(g.current_user_id)
|
||||
share = SharedItem.query.filter(
|
||||
SharedItem.id == share_id,
|
||||
db.or_(
|
||||
SharedItem.recipient_email == user.email,
|
||||
SharedItem.recipient_id == user.id,
|
||||
),
|
||||
).first()
|
||||
if not share:
|
||||
return jsonify({'error': 'Share not found'}), 404
|
||||
|
||||
share.accepted = True
|
||||
share.recipient_id = user.id
|
||||
db.session.commit()
|
||||
|
||||
d = share.to_dict()
|
||||
owner = User.query.get(share.owner_id)
|
||||
d['owner_email'] = owner.email if owner else 'Unknown'
|
||||
d['owner_public_key'] = owner.sharing_public_key if owner else None
|
||||
return jsonify(d), 200
|
||||
@@ -0,0 +1,95 @@
|
||||
from flask import Blueprint, request, jsonify, g
|
||||
from app import db
|
||||
from app.models.vault_item import VaultItem, ItemType
|
||||
from app.services.auth_service import require_jwt
|
||||
|
||||
vault_bp = Blueprint('vault', __name__)
|
||||
|
||||
VALID_TYPES = {t.value for t in ItemType}
|
||||
|
||||
|
||||
@vault_bp.route('', methods=['GET'])
|
||||
@require_jwt
|
||||
def list_items():
|
||||
items = VaultItem.query.filter_by(user_id=g.current_user_id).order_by(
|
||||
VaultItem.name.asc()
|
||||
).all()
|
||||
return jsonify([item.to_dict() for item in items]), 200
|
||||
|
||||
|
||||
@vault_bp.route('', methods=['POST'])
|
||||
@require_jwt
|
||||
def create_item():
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = (data.get('name') or '').strip()
|
||||
item_type = data.get('item_type', 'password')
|
||||
enc_data = data.get('enc_data', '')
|
||||
iv = data.get('iv', '')
|
||||
folder_id = data.get('folder_id')
|
||||
|
||||
if not name:
|
||||
return jsonify({'error': 'name is required'}), 400
|
||||
if item_type not in VALID_TYPES:
|
||||
return jsonify({'error': f'item_type must be one of {sorted(VALID_TYPES)}'}), 400
|
||||
if not enc_data or not iv:
|
||||
return jsonify({'error': 'enc_data and iv are required'}), 400
|
||||
|
||||
item = VaultItem(
|
||||
user_id=g.current_user_id,
|
||||
folder_id=folder_id,
|
||||
item_type=item_type, # stored as plain string
|
||||
name=name,
|
||||
enc_data=enc_data,
|
||||
iv=iv,
|
||||
)
|
||||
try:
|
||||
db.session.add(item)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': f'Database error: {str(e)}'}), 500
|
||||
return jsonify(item.to_dict()), 201
|
||||
|
||||
|
||||
@vault_bp.route('/<int:item_id>', methods=['GET'])
|
||||
@require_jwt
|
||||
def get_item(item_id):
|
||||
item = VaultItem.query.filter_by(id=item_id, user_id=g.current_user_id).first()
|
||||
if not item:
|
||||
return jsonify({'error': 'Item not found'}), 404
|
||||
return jsonify(item.to_dict()), 200
|
||||
|
||||
|
||||
@vault_bp.route('/<int:item_id>', methods=['PUT'])
|
||||
@require_jwt
|
||||
def update_item(item_id):
|
||||
item = VaultItem.query.filter_by(id=item_id, user_id=g.current_user_id).first()
|
||||
if not item:
|
||||
return jsonify({'error': 'Item not found'}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
if 'name' in data:
|
||||
name = data['name'].strip()
|
||||
if not name:
|
||||
return jsonify({'error': 'name cannot be empty'}), 400
|
||||
item.name = name
|
||||
if 'folder_id' in data:
|
||||
item.folder_id = data['folder_id']
|
||||
if 'enc_data' in data:
|
||||
item.enc_data = data['enc_data']
|
||||
if 'iv' in data:
|
||||
item.iv = data['iv']
|
||||
|
||||
db.session.commit()
|
||||
return jsonify(item.to_dict()), 200
|
||||
|
||||
|
||||
@vault_bp.route('/<int:item_id>', methods=['DELETE'])
|
||||
@require_jwt
|
||||
def delete_item(item_id):
|
||||
item = VaultItem.query.filter_by(id=item_id, user_id=g.current_user_id).first()
|
||||
if not item:
|
||||
return jsonify({'error': 'Item not found'}), 404
|
||||
db.session.delete(item)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Item deleted'}), 200
|
||||
@@ -0,0 +1,123 @@
|
||||
import uuid
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from functools import wraps
|
||||
|
||||
import jwt
|
||||
from flask import current_app, request, g, jsonify
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
|
||||
|
||||
def hash_auth_token(auth_hash: str) -> str:
|
||||
"""Hash the client-derived PBKDF2 auth_hash with Argon2id before storing."""
|
||||
ph = PasswordHasher(
|
||||
time_cost=current_app.config['ARGON2_TIME_COST'],
|
||||
memory_cost=current_app.config['ARGON2_MEMORY_COST'],
|
||||
parallelism=current_app.config['ARGON2_PARALLELISM'],
|
||||
)
|
||||
return ph.hash(auth_hash)
|
||||
|
||||
|
||||
def verify_auth_token(auth_hash: str, stored_hash: str) -> bool:
|
||||
ph = PasswordHasher()
|
||||
try:
|
||||
return ph.verify(stored_hash, auth_hash)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def generate_tokens(user_id: int) -> dict:
|
||||
"""Return access_token and refresh_token JWTs, each with a unique jti."""
|
||||
now = datetime.utcnow()
|
||||
secret = current_app.config['JWT_SECRET_KEY']
|
||||
access_payload = {
|
||||
'sub': str(user_id),
|
||||
'type': 'access',
|
||||
'jti': str(uuid.uuid4()),
|
||||
'iat': now,
|
||||
'exp': now + current_app.config['JWT_ACCESS_TOKEN_EXPIRES'],
|
||||
}
|
||||
refresh_payload = {
|
||||
'sub': str(user_id),
|
||||
'type': 'refresh',
|
||||
'jti': str(uuid.uuid4()),
|
||||
'iat': now,
|
||||
'exp': now + current_app.config['JWT_REFRESH_TOKEN_EXPIRES'],
|
||||
}
|
||||
return {
|
||||
'access_token': jwt.encode(access_payload, secret, algorithm='HS256'),
|
||||
'refresh_token': jwt.encode(refresh_payload, secret, algorithm='HS256'),
|
||||
}
|
||||
|
||||
|
||||
def generate_mfa_token(user_id: int) -> str:
|
||||
"""Short-lived (5-min) single-use token issued after password but before TOTP."""
|
||||
now = datetime.utcnow()
|
||||
payload = {
|
||||
'sub': str(user_id),
|
||||
'type': 'mfa',
|
||||
'jti': str(uuid.uuid4()),
|
||||
'iat': now,
|
||||
'exp': now + timedelta(minutes=5),
|
||||
}
|
||||
return jwt.encode(payload, current_app.config['JWT_SECRET_KEY'], algorithm='HS256')
|
||||
|
||||
|
||||
def decode_token(token: str, expected_type: str = 'access', check_blacklist: bool = True) -> dict:
|
||||
"""Decode and validate a JWT. Raises jwt.PyJWTError on any failure."""
|
||||
secret = current_app.config['JWT_SECRET_KEY']
|
||||
payload = jwt.decode(token, secret, algorithms=['HS256'])
|
||||
if payload.get('type') != expected_type:
|
||||
raise jwt.InvalidTokenError('Wrong token type')
|
||||
if check_blacklist:
|
||||
from app.models.token_blacklist import TokenBlacklist
|
||||
jti = payload.get('jti')
|
||||
if jti and TokenBlacklist.is_blacklisted(jti):
|
||||
raise jwt.InvalidTokenError('Token has been revoked')
|
||||
return payload
|
||||
|
||||
|
||||
def blacklist_token(token: str, token_type: str) -> None:
|
||||
"""Add a JWT's jti to the blacklist. Silently ignores invalid tokens."""
|
||||
try:
|
||||
payload = decode_token(token, expected_type=token_type, check_blacklist=False)
|
||||
jti = payload.get('jti')
|
||||
if not jti:
|
||||
return
|
||||
exp = payload.get('exp')
|
||||
expires_at = datetime.utcfromtimestamp(exp) if exp else datetime.utcnow() + timedelta(days=7)
|
||||
from app.models.token_blacklist import TokenBlacklist
|
||||
from app import db
|
||||
# Avoid duplicate if already blacklisted
|
||||
if not TokenBlacklist.query.filter_by(jti=jti).first():
|
||||
entry = TokenBlacklist(
|
||||
jti=jti,
|
||||
user_id=int(payload.get('sub', 0)),
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.session.add(entry)
|
||||
db.session.commit()
|
||||
# Opportunistic cleanup — runs in same transaction context
|
||||
TokenBlacklist.cleanup_expired()
|
||||
except Exception:
|
||||
pass # Never let blacklisting errors break the logout flow
|
||||
|
||||
|
||||
def require_jwt(f):
|
||||
"""Decorator: validates Bearer token and sets g.current_user_id."""
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
auth_header = request.headers.get('Authorization', '')
|
||||
if not auth_header.startswith('Bearer '):
|
||||
return jsonify({'error': 'Missing or invalid Authorization header'}), 401
|
||||
token = auth_header[7:]
|
||||
try:
|
||||
payload = decode_token(token, expected_type='access')
|
||||
except jwt.ExpiredSignatureError:
|
||||
return jsonify({'error': 'Token expired'}), 401
|
||||
except jwt.PyJWTError:
|
||||
return jsonify({'error': 'Invalid token'}), 401
|
||||
g.current_user_id = int(payload['sub'])
|
||||
return f(*args, **kwargs)
|
||||
return decorated
|
||||
@@ -0,0 +1,555 @@
|
||||
/* ── Reset & base ──────────────────────────────────────────────────── */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
:root {
|
||||
--color-bg: #f4f5f7;
|
||||
--color-surface: #ffffff;
|
||||
--color-primary: #d0021b;
|
||||
--color-primary-dark: #a80016;
|
||||
--color-text: #1a1a2e;
|
||||
--color-text-muted: #6b7280;
|
||||
--color-border: #e2e4e9;
|
||||
--color-sidebar-bg: #1e2235;
|
||||
--color-sidebar-text: #c8ccd8;
|
||||
--color-sidebar-hover: #2d3250;
|
||||
--color-sidebar-active: #d0021b;
|
||||
--radius: 8px;
|
||||
--shadow: 0 1px 4px rgba(0,0,0,.08), 0 2px 12px rgba(0,0,0,.05);
|
||||
--transition: 150ms ease;
|
||||
}
|
||||
|
||||
html, body { height: 100%; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; color: var(--color-text); background: var(--color-bg); }
|
||||
a { color: var(--color-primary); text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
button { cursor: pointer; font: inherit; border: none; background: none; }
|
||||
input, select, textarea { font: inherit; }
|
||||
ul { list-style: none; }
|
||||
|
||||
/* ── Utilities ───────────────────────────────────────────────────── */
|
||||
.hidden { display: none !important; }
|
||||
|
||||
/* ── Auth pages ──────────────────────────────────────────────────── */
|
||||
.auth-page { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: var(--color-bg); }
|
||||
|
||||
.auth-container { width: 100%; max-width: 420px; padding: 16px; }
|
||||
|
||||
.auth-card {
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
padding: 40px 36px;
|
||||
}
|
||||
|
||||
.auth-logo { display: flex; align-items: center; gap: 8px; margin-bottom: 28px; }
|
||||
.auth-logo .logo-icon { font-size: 28px; }
|
||||
.auth-logo .logo-text { font-size: 20px; font-weight: 700; color: var(--color-text); }
|
||||
|
||||
.auth-title { font-size: 22px; font-weight: 600; margin-bottom: 24px; }
|
||||
|
||||
.auth-footer { margin-top: 20px; text-align: center; color: var(--color-text-muted); }
|
||||
|
||||
/* ── Form elements ──────────────────────────────────────────────── */
|
||||
.form-group { margin-bottom: 16px; }
|
||||
.form-group label { display: block; margin-bottom: 6px; font-weight: 500; color: var(--color-text); }
|
||||
.form-group label .hint { font-weight: 400; color: var(--color-text-muted); font-size: 12px; }
|
||||
|
||||
.form-group input,
|
||||
.form-group select,
|
||||
.form-group textarea {
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
transition: border-color var(--transition);
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus,
|
||||
.form-group textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--color-primary);
|
||||
box-shadow: 0 0 0 3px rgba(208,2,27,.12);
|
||||
}
|
||||
|
||||
.input-with-toggle { position: relative; }
|
||||
.input-with-toggle input { padding-right: 40px; }
|
||||
.btn-show-pass {
|
||||
position: absolute; right: 10px; top: 50%; transform: translateY(-50%);
|
||||
background: none; border: none; cursor: pointer; font-size: 16px; opacity: .6;
|
||||
transition: opacity var(--transition);
|
||||
}
|
||||
.btn-show-pass:hover { opacity: 1; }
|
||||
|
||||
.form-error { color: #c00; background: #fff0f0; border: 1px solid #fcc; border-radius: var(--radius); padding: 8px 12px; margin-bottom: 12px; font-size: 13px; }
|
||||
|
||||
/* Buttons */
|
||||
.btn-primary {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
background: var(--color-primary); color: #fff;
|
||||
padding: 10px 20px; border-radius: var(--radius); font-weight: 600;
|
||||
transition: background var(--transition);
|
||||
}
|
||||
.btn-primary:hover { background: var(--color-primary-dark); }
|
||||
.btn-primary:disabled { opacity: .6; cursor: not-allowed; }
|
||||
.btn-full { width: 100%; }
|
||||
|
||||
.btn-secondary {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
background: var(--color-border); color: var(--color-text);
|
||||
padding: 10px 20px; border-radius: var(--radius); font-weight: 500;
|
||||
transition: background var(--transition);
|
||||
}
|
||||
.btn-secondary:hover { background: #d1d5dc; }
|
||||
|
||||
.btn-text { background: none; border: none; color: inherit; padding: 0; }
|
||||
|
||||
/* Notices */
|
||||
.notice-success { background: #e8f5e9; border: 1px solid #a5d6a7; color: #2e7d32; border-radius: var(--radius); padding: 10px 14px; margin-bottom: 16px; font-size: 13px; }
|
||||
.notice-info { background: #e3f2fd; border: 1px solid #90caf9; color: #1565c0; border-radius: var(--radius); padding: 10px 14px; margin-bottom: 16px; font-size: 13px; }
|
||||
|
||||
/* Password strength */
|
||||
.password-strength { margin-top: 6px; font-size: 12px; font-weight: 500; }
|
||||
.strength-1 { color: #c62828; }
|
||||
.strength-2 { color: #e65100; }
|
||||
.strength-3 { color: #f57f17; }
|
||||
.strength-4 { color: #2e7d32; }
|
||||
.strength-5 { color: #1b5e20; }
|
||||
|
||||
/* ── App layout (vault) ──────────────────────────────────────────── */
|
||||
.vault-page { height: 100vh; overflow: hidden; }
|
||||
|
||||
.app-layout { display: flex; height: 100vh; }
|
||||
|
||||
/* ── Sidebar ─────────────────────────────────────────────────────── */
|
||||
.sidebar {
|
||||
width: 220px;
|
||||
flex-shrink: 0;
|
||||
background: var(--color-sidebar-bg);
|
||||
color: var(--color-sidebar-text);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 18px 16px;
|
||||
border-bottom: 1px solid rgba(255,255,255,.08);
|
||||
}
|
||||
.sidebar-header .logo-icon { font-size: 22px; }
|
||||
.sidebar-header .logo-text { font-size: 16px; font-weight: 700; color: #fff; }
|
||||
|
||||
.sidebar-nav { flex: 1; padding: 8px 0; }
|
||||
|
||||
.sidebar-section-header {
|
||||
padding: 12px 16px 4px;
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .08em;
|
||||
color: rgba(255,255,255,.35);
|
||||
}
|
||||
|
||||
.sidebar-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 9px 16px;
|
||||
border-radius: 0;
|
||||
color: var(--color-sidebar-text);
|
||||
cursor: pointer;
|
||||
transition: background var(--transition);
|
||||
font-size: 14px;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
}
|
||||
.sidebar-item:hover { background: var(--color-sidebar-hover); }
|
||||
.sidebar-item.active { background: var(--color-sidebar-active); color: #fff; }
|
||||
.sidebar-icon { font-size: 16px; flex-shrink: 0; }
|
||||
|
||||
.sidebar-footer { padding: 12px 0; border-top: 1px solid rgba(255,255,255,.08); }
|
||||
|
||||
.folder-item { justify-content: space-between; }
|
||||
.folder-label { display: flex; align-items: center; gap: 10px; flex: 1; cursor: pointer; }
|
||||
.btn-delete-folder {
|
||||
background: none; border: none; cursor: pointer;
|
||||
font-size: 13px; opacity: 0; color: rgba(255,255,255,.6);
|
||||
transition: opacity var(--transition), color var(--transition);
|
||||
padding: 2px 4px; border-radius: 4px; flex-shrink: 0;
|
||||
}
|
||||
.folder-item:hover .btn-delete-folder { opacity: 1; }
|
||||
.btn-delete-folder:hover { color: #ff6b6b; }
|
||||
|
||||
.btn-new-folder {
|
||||
float: right; margin-right: 4px;
|
||||
background: none; border: none; color: rgba(255,255,255,.5);
|
||||
font-size: 16px; line-height: 1; cursor: pointer; padding: 0 4px;
|
||||
transition: color var(--transition);
|
||||
}
|
||||
.btn-new-folder:hover { color: #fff; }
|
||||
|
||||
.new-folder-row { padding: 4px 10px 4px 16px; }
|
||||
.new-folder-row form { display: flex; align-items: center; gap: 4px; }
|
||||
.new-folder-row input {
|
||||
flex: 1; padding: 5px 8px; border-radius: 4px; border: 1px solid rgba(255,255,255,.2);
|
||||
background: rgba(255,255,255,.1); color: #fff; font-size: 13px;
|
||||
}
|
||||
.new-folder-row input::placeholder { color: rgba(255,255,255,.4); }
|
||||
.new-folder-row input:focus { outline: none; border-color: rgba(255,255,255,.5); }
|
||||
.new-folder-row .btn-icon { color: rgba(255,255,255,.7); font-size: 14px; }
|
||||
.new-folder-row .btn-icon:hover { color: #fff; background: rgba(255,255,255,.1); }
|
||||
|
||||
/* ── Vault main ──────────────────────────────────────────────────── */
|
||||
.vault-main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: var(--color-bg);
|
||||
}
|
||||
|
||||
#view-vault, #view-security {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
position: relative;
|
||||
}
|
||||
#view-vault.hidden, #view-security.hidden { display: none; }
|
||||
|
||||
.vault-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 24px;
|
||||
background: var(--color-surface);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.vault-title { font-size: 18px; font-weight: 600; white-space: nowrap; }
|
||||
|
||||
.vault-toolbar { display: flex; align-items: center; gap: 12px; flex: 1; justify-content: flex-end; }
|
||||
|
||||
.search-wrapper {
|
||||
display: flex; align-items: center;
|
||||
background: var(--color-bg); border: 1px solid var(--color-border);
|
||||
border-radius: 20px; padding: 6px 14px; gap: 8px; flex: 1; max-width: 360px;
|
||||
}
|
||||
.search-icon { color: var(--color-text-muted); }
|
||||
#search-input { border: none; background: none; outline: none; flex: 1; font-size: 14px; }
|
||||
|
||||
.btn-fab {
|
||||
width: 40px; height: 40px; border-radius: 50%;
|
||||
background: var(--color-primary); color: #fff;
|
||||
font-size: 24px; font-weight: 300;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
box-shadow: 0 2px 8px rgba(208,2,27,.35);
|
||||
transition: background var(--transition), box-shadow var(--transition);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.btn-fab:hover { background: var(--color-primary-dark); box-shadow: 0 4px 14px rgba(208,2,27,.45); }
|
||||
|
||||
/* ── Vault list ──────────────────────────────────────────────────── */
|
||||
.vault-list { flex: 1; overflow-y: auto; padding: 12px 24px 24px; }
|
||||
|
||||
.vault-group-header {
|
||||
font-size: 12px; font-weight: 600; text-transform: uppercase;
|
||||
letter-spacing: .06em; color: var(--color-text-muted);
|
||||
padding: 16px 0 6px; border-bottom: 1px solid var(--color-border);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.vault-empty {
|
||||
text-align: center; color: var(--color-text-muted); padding: 60px 0; font-size: 15px;
|
||||
}
|
||||
|
||||
.vault-item {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 6px;
|
||||
cursor: pointer;
|
||||
transition: box-shadow var(--transition), border-color var(--transition);
|
||||
}
|
||||
.vault-item:hover { box-shadow: var(--shadow); border-color: #c9ccd4; }
|
||||
|
||||
.item-icon { font-size: 22px; flex-shrink: 0; }
|
||||
|
||||
.item-info { flex: 1; min-width: 0; }
|
||||
.item-name { display: block; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.item-sub { display: block; font-size: 12px; color: var(--color-text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
.item-actions { display: flex; gap: 4px; opacity: 0; transition: opacity var(--transition); }
|
||||
.vault-item:hover .item-actions { opacity: 1; }
|
||||
|
||||
.btn-icon {
|
||||
width: 30px; height: 30px; border-radius: 6px;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-size: 15px; color: var(--color-text-muted);
|
||||
transition: background var(--transition), color var(--transition);
|
||||
}
|
||||
.btn-icon:hover { background: var(--color-bg); color: var(--color-text); }
|
||||
|
||||
/* ── Spinner ─────────────────────────────────────────────────────── */
|
||||
.spinner-overlay {
|
||||
position: absolute; inset: 0;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: rgba(255,255,255,.7);
|
||||
z-index: 10;
|
||||
}
|
||||
.spinner-overlay.hidden { display: none; }
|
||||
.spinner {
|
||||
width: 36px; height: 36px;
|
||||
border: 3px solid var(--color-border);
|
||||
border-top-color: var(--color-primary);
|
||||
border-radius: 50%;
|
||||
animation: spin .7s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* ── Modal ───────────────────────────────────────────────────────── */
|
||||
.modal-overlay {
|
||||
position: fixed; inset: 0;
|
||||
background: rgba(0,0,0,.45);
|
||||
display: none; align-items: center; justify-content: center;
|
||||
z-index: 100;
|
||||
padding: 16px;
|
||||
}
|
||||
.modal-overlay.open { display: flex; }
|
||||
|
||||
.modal {
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 8px 40px rgba(0,0,0,.2);
|
||||
width: 100%; max-width: 480px;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
padding: 28px;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.modal-header h3 { font-size: 18px; font-weight: 600; }
|
||||
|
||||
.btn-close { font-size: 18px; color: var(--color-text-muted); padding: 4px; border-radius: 4px; }
|
||||
.btn-close:hover { background: var(--color-bg); color: var(--color-text); }
|
||||
|
||||
.modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
|
||||
|
||||
.required { color: var(--color-primary); }
|
||||
|
||||
/* ── Toast ───────────────────────────────────────────────────────── */
|
||||
.toast {
|
||||
position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%) translateY(20px);
|
||||
background: #1a1a2e; color: #fff;
|
||||
padding: 10px 20px; border-radius: 20px;
|
||||
font-size: 14px; font-weight: 500;
|
||||
opacity: 0; transition: opacity .25s, transform .25s;
|
||||
pointer-events: none; z-index: 200; white-space: nowrap;
|
||||
}
|
||||
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
.toast.toast-error { background: #c00; }
|
||||
|
||||
/* ── Unlock overlay ──────────────────────────────────────────────── */
|
||||
.modal-unlock { max-width: 380px; }
|
||||
.unlock-logo { margin-bottom: 16px; }
|
||||
.unlock-title { margin-bottom: 4px; }
|
||||
.unlock-subtitle { color: var(--color-text-muted); font-size: 13px; margin-bottom: 20px; }
|
||||
.btn-link { padding: 10px 20px; border-radius: var(--radius); text-decoration: none; }
|
||||
|
||||
/* ── Auth step hint ─────────────────────────────────────────────── */
|
||||
.auth-step-hint { color: var(--color-text-muted); font-size: 13px; margin-bottom: 16px; }
|
||||
#mfa-code { font-size: 22px; letter-spacing: .2em; text-align: center; }
|
||||
|
||||
/* ── Panel body (sharing / emergency) ───────────────────────────── */
|
||||
.panel-body { flex: 1; overflow-y: auto; padding: 20px 24px; }
|
||||
|
||||
/* ── Tabs ────────────────────────────────────────────────────────── */
|
||||
.panel-tabs { display: flex; gap: 4px; margin-bottom: 16px; border-bottom: 2px solid var(--color-border); padding-bottom: 0; }
|
||||
.tab-btn {
|
||||
padding: 8px 16px; border-radius: 6px 6px 0 0; font-size: 13px;
|
||||
font-weight: 500; color: var(--color-text-muted);
|
||||
border-bottom: 2px solid transparent; margin-bottom: -2px;
|
||||
transition: color var(--transition), border-color var(--transition);
|
||||
}
|
||||
.tab-btn:hover { color: var(--color-text); }
|
||||
.tab-btn.active { color: var(--color-primary); border-bottom-color: var(--color-primary); }
|
||||
|
||||
/* ── Share / Emergency lists ────────────────────────────────────── */
|
||||
.share-list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.share-item {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius); padding: 12px 14px;
|
||||
}
|
||||
.share-icon { font-size: 22px; flex-shrink: 0; }
|
||||
.share-info { flex: 1; min-width: 0; }
|
||||
.share-name { display: block; font-weight: 500; }
|
||||
.share-meta { display: block; font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
|
||||
.share-actions { display: flex; gap: 6px; align-items: center; flex-shrink: 0; }
|
||||
|
||||
/* ── Badges ──────────────────────────────────────────────────────── */
|
||||
.badge { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 12px; font-weight: 500; }
|
||||
.badge-warn { background: #fff8e1; color: #e65100; border: 1px solid #ffb74d; }
|
||||
.badge-info { background: #e3f2fd; color: #1565c0; border: 1px solid #90caf9; }
|
||||
|
||||
/* ── Settings modal ──────────────────────────────────────────────── */
|
||||
.modal-settings { max-width: 520px; }
|
||||
.settings-section { padding: 16px 0; border-bottom: 1px solid var(--color-border); }
|
||||
.settings-section:last-child { border-bottom: none; }
|
||||
.settings-section-title { font-size: 15px; font-weight: 600; margin-bottom: 8px; }
|
||||
.settings-desc { font-size: 13px; color: var(--color-text-muted); margin-bottom: 10px; line-height: 1.5; }
|
||||
.mfa-qr { display: block; margin: 12px auto; max-width: 180px; border: 1px solid var(--color-border); border-radius: 4px; }
|
||||
.mfa-secret-text { font-family: monospace; font-size: 12px; }
|
||||
.mfa-secret-text code { background: var(--color-bg); padding: 2px 6px; border-radius: 4px; user-select: all; }
|
||||
|
||||
/* ── Sort control ────────────────────────────────────────────────── */
|
||||
.sort-wrapper select {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 20px;
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
}
|
||||
.sort-wrapper select:focus { border-color: var(--color-primary); }
|
||||
|
||||
/* ── Modal item (wider for address/card forms) ───────────────────── */
|
||||
.modal-item { max-width: 540px; }
|
||||
|
||||
/* ── Multi-column form rows ──────────────────────────────────────── */
|
||||
.form-row { display: flex; gap: 12px; }
|
||||
.form-row .form-group { flex: 1; }
|
||||
|
||||
/* ── Btn small ───────────────────────────────────────────────────── */
|
||||
.btn-sm { padding: 5px 12px; font-size: 12px; border-radius: 6px; }
|
||||
|
||||
/* ── Security dashboard ──────────────────────────────────────────── */
|
||||
.security-dashboard {
|
||||
flex: 1; overflow-y: auto;
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.sec-notice {
|
||||
text-align: center; color: var(--color-text-muted);
|
||||
padding: 40px 0; font-size: 15px;
|
||||
}
|
||||
|
||||
.security-summary {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
align-items: center;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sec-score-card { text-align: center; flex-shrink: 0; }
|
||||
.sec-score {
|
||||
font-size: 56px; font-weight: 700; line-height: 1;
|
||||
}
|
||||
.sec-score.score-good { color: #2e7d32; }
|
||||
.sec-score.score-fair { color: #e65100; }
|
||||
.sec-score.score-poor { color: #c62828; }
|
||||
.sec-score-label { font-size: 16px; font-weight: 600; margin-top: 4px; }
|
||||
.sec-score-desc { font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
|
||||
|
||||
.sec-stats { display: flex; gap: 16px; flex-wrap: wrap; }
|
||||
.sec-stat {
|
||||
text-align: center;
|
||||
background: var(--color-bg);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px 20px;
|
||||
min-width: 80px;
|
||||
}
|
||||
.sec-stat-warn { border-color: #ffb74d; background: #fff8e1; }
|
||||
.sec-stat-info { border-color: #90caf9; background: #e3f2fd; }
|
||||
.sec-stat-ok { border-color: #a5d6a7; background: #e8f5e9; }
|
||||
.sec-stat-num { display: block; font-size: 28px; font-weight: 700; }
|
||||
.sec-stat-label { display: block; font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
|
||||
|
||||
.sec-section {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.sec-section-header {
|
||||
display: flex; align-items: flex-start; gap: 12px;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
background: var(--color-bg);
|
||||
}
|
||||
.sec-section-icon { font-size: 20px; flex-shrink: 0; }
|
||||
.sec-section-title { font-weight: 600; font-size: 15px; }
|
||||
.sec-section-desc { font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
|
||||
|
||||
.sec-item-list { padding: 0; }
|
||||
.sec-item {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 10px 20px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
.sec-item:last-child { border-bottom: none; }
|
||||
.sec-item-name { font-weight: 500; flex: 1; }
|
||||
.sec-item-sub { font-size: 12px; color: var(--color-text-muted); flex: 1; }
|
||||
|
||||
/* ── Item Detail Modal ───────────────────────────────────────────── */
|
||||
.modal-detail { max-height: 80vh; display: flex; flex-direction: column; }
|
||||
.detail-body { flex: 1; overflow-y: auto; padding: 4px 0; }
|
||||
.detail-field { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-bottom: 1px solid var(--color-border); }
|
||||
.detail-field:last-child { border-bottom: none; }
|
||||
.detail-label { font-size: 12px; color: var(--color-text-muted); width: 140px; flex-shrink: 0; padding-top: 4px; }
|
||||
.detail-val-row { display: flex; align-items: center; gap: 6px; flex: 1; flex-wrap: wrap; }
|
||||
.detail-val { font-size: 14px; word-break: break-all; }
|
||||
.detail-sensitive { display: inline-flex; align-items: center; font-family: monospace; font-size: 14px; }
|
||||
.detail-masked { letter-spacing: 2px; }
|
||||
.detail-actual { word-break: break-all; }
|
||||
.btn-reveal, .btn-copy-field { background: none; border: none; cursor: pointer; padding: 2px 4px; font-size: 14px; color: var(--color-text-muted); flex-shrink: 0; }
|
||||
.btn-reveal:hover, .btn-copy-field:hover { color: var(--color-primary); }
|
||||
|
||||
/* ── Emergency Vault Panel ───────────────────────────────────────── */
|
||||
.em-vault-panel { padding: 8px 0; }
|
||||
.em-vault-header { display: flex; align-items: center; justify-content: space-between; padding: 4px 0 16px; border-bottom: 2px solid var(--color-border); margin-bottom: 8px; }
|
||||
.em-vault-header h4 { margin: 0; font-size: 15px; font-weight: 600; }
|
||||
.em-vault-list { list-style: none; padding: 0; margin: 0; }
|
||||
.em-vault-item { border-bottom: 1px solid var(--color-border); }
|
||||
.em-vault-item:last-child { border-bottom: none; }
|
||||
.em-vault-item-header { display: flex; align-items: center; gap: 10px; width: 100%; background: none; border: none; padding: 12px 4px; cursor: pointer; text-align: left; }
|
||||
.em-vault-item-header:hover { background: var(--color-sidebar-hover); border-radius: var(--radius); }
|
||||
.em-vault-icon { font-size: 18px; flex-shrink: 0; }
|
||||
.em-vault-name { font-weight: 500; flex: 1; }
|
||||
.em-vault-type { font-size: 12px; color: var(--color-text-muted); }
|
||||
.em-vault-chevron { font-size: 12px; color: var(--color-text-muted); flex-shrink: 0; }
|
||||
.em-vault-item-body { padding: 0 8px 12px 36px; }
|
||||
.em-detail-body .detail-field { padding: 8px 0; }
|
||||
|
||||
/* ── Responsive ──────────────────────────────────────────────────── */
|
||||
@media (max-width: 640px) {
|
||||
.sidebar { width: 60px; }
|
||||
.sidebar-header .logo-text,
|
||||
.sidebar-label,
|
||||
.sidebar-section-header { display: none; }
|
||||
.sidebar-item { justify-content: center; padding: 12px 0; }
|
||||
.vault-header { padding: 12px 16px; }
|
||||
.vault-list { padding: 8px 16px 16px; }
|
||||
.sort-wrapper { display: none; }
|
||||
.form-row { flex-direction: column; gap: 0; }
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* auth.js — Register and Login flows (including TOTP MFA step)
|
||||
*
|
||||
* Master password never leaves the browser. Only the PBKDF2-derived authHash
|
||||
* is sent to the server for authentication.
|
||||
*/
|
||||
|
||||
const Auth = (() => {
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
function csrfToken() {
|
||||
const meta = document.querySelector('meta[name="csrf-token"]');
|
||||
return meta ? meta.content : '';
|
||||
}
|
||||
|
||||
function showError(formEl, message) {
|
||||
let el = formEl.querySelector('.form-error');
|
||||
if (!el) {
|
||||
el = document.createElement('p');
|
||||
el.className = 'form-error';
|
||||
formEl.prepend(el);
|
||||
}
|
||||
el.textContent = message;
|
||||
el.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function setLoading(btn, loading) {
|
||||
btn.disabled = loading;
|
||||
btn.textContent = loading ? btn.dataset.loadingText || 'Please wait…' : btn.dataset.originalText;
|
||||
}
|
||||
|
||||
// ── Register ─────────────────────────────────────────────────────────────
|
||||
|
||||
async function handleRegister(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const btn = form.querySelector('[type="submit"]');
|
||||
btn.dataset.originalText = btn.textContent;
|
||||
|
||||
const email = form.email.value.trim().toLowerCase();
|
||||
const password = form.password.value;
|
||||
const confirm = form.confirm_password.value;
|
||||
|
||||
if (password !== confirm) { showError(form, 'Passwords do not match.'); return; }
|
||||
if (password.length < 12) { showError(form, 'Master password must be at least 12 characters.'); return; }
|
||||
|
||||
setLoading(btn, true);
|
||||
try {
|
||||
const authHash = await Crypto.deriveAuthHash(password, email);
|
||||
const enc_key_salt = Crypto.generateSalt(16);
|
||||
|
||||
const res = await fetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken() },
|
||||
body: JSON.stringify({ email, auth_hash: authHash, enc_key_salt }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { showError(form, data.error || 'Registration failed.'); return; }
|
||||
window.location.href = '/login?registered=1';
|
||||
} catch (err) {
|
||||
showError(form, 'An unexpected error occurred. Please try again.');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(btn, false);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Login ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// Temporarily held between Step 1 and Step 2
|
||||
let _pendingMfaToken = null;
|
||||
let _pendingEncKeySalt = null;
|
||||
let _pendingPassword = null;
|
||||
|
||||
async function handleLogin(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const btn = form.querySelector('[type="submit"]');
|
||||
btn.dataset.originalText = btn.textContent;
|
||||
|
||||
const email = form.email.value.trim().toLowerCase();
|
||||
const password = form.password.value;
|
||||
|
||||
setLoading(btn, true);
|
||||
try {
|
||||
const authHash = await Crypto.deriveAuthHash(password, email);
|
||||
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken() },
|
||||
body: JSON.stringify({ email, auth_hash: authHash }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { showError(form, data.error || 'Invalid email or password.'); return; }
|
||||
|
||||
if (data.mfa_required) {
|
||||
// Step 2: collect TOTP code
|
||||
_pendingMfaToken = data.mfa_token;
|
||||
_pendingEncKeySalt = data.enc_key_salt;
|
||||
_pendingPassword = password;
|
||||
sessionStorage.setItem('enc_key_salt', data.enc_key_salt);
|
||||
showMfaStep();
|
||||
return;
|
||||
}
|
||||
|
||||
await completeLogin(password, data);
|
||||
} catch (err) {
|
||||
showError(form, 'An unexpected error occurred. Please try again.');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(btn, false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMfaVerify(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const btn = form.querySelector('[type="submit"]');
|
||||
btn.dataset.originalText = btn.textContent;
|
||||
const errEl = document.getElementById('mfa-error');
|
||||
errEl.classList.add('hidden');
|
||||
|
||||
const totp_code = document.getElementById('mfa-code').value.trim();
|
||||
if (!totp_code) return;
|
||||
|
||||
setLoading(btn, true);
|
||||
try {
|
||||
const res = await fetch('/api/auth/mfa/verify', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken() },
|
||||
body: JSON.stringify({ mfa_token: _pendingMfaToken, totp_code }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { errEl.classList.remove('hidden'); return; }
|
||||
|
||||
await completeLogin(_pendingPassword, {
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
enc_key_salt: _pendingEncKeySalt,
|
||||
});
|
||||
} catch (err) {
|
||||
errEl.classList.remove('hidden');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(btn, false);
|
||||
}
|
||||
}
|
||||
|
||||
async function completeLogin(password, data) {
|
||||
sessionStorage.setItem('access_token', data.access_token);
|
||||
localStorage.setItem('refresh_token', data.refresh_token);
|
||||
sessionStorage.setItem('enc_key_salt', data.enc_key_salt);
|
||||
|
||||
// Notify the browser extension (if installed) so it can share the session
|
||||
window.dispatchEvent(new CustomEvent('passkeeper:session', {
|
||||
detail: {
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
enc_key_salt: data.enc_key_salt,
|
||||
},
|
||||
}));
|
||||
|
||||
const vaultKey = await Crypto.deriveVaultKey(password, data.enc_key_salt);
|
||||
VaultSession.setKey(vaultKey);
|
||||
|
||||
window.location.href = '/vault';
|
||||
}
|
||||
|
||||
function showMfaStep() {
|
||||
document.getElementById('login-step-1').classList.add('hidden');
|
||||
document.getElementById('login-step-2').classList.remove('hidden');
|
||||
document.getElementById('mfa-code').focus();
|
||||
}
|
||||
|
||||
function hideMfaStep() {
|
||||
document.getElementById('login-step-2').classList.add('hidden');
|
||||
document.getElementById('login-step-1').classList.remove('hidden');
|
||||
document.getElementById('mfa-code').value = '';
|
||||
document.getElementById('mfa-error').classList.add('hidden');
|
||||
_pendingMfaToken = null;
|
||||
_pendingEncKeySalt = null;
|
||||
_pendingPassword = null;
|
||||
}
|
||||
|
||||
// ── Init ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function initPasswordToggle(btnId, inputId) {
|
||||
const btn = document.getElementById(btnId);
|
||||
const input = document.getElementById(inputId);
|
||||
if (btn && input) {
|
||||
btn.addEventListener('click', () => {
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function initStrengthMeter() {
|
||||
const input = document.getElementById('password');
|
||||
const bar = document.getElementById('strength-bar');
|
||||
if (!input || !bar) return;
|
||||
input.addEventListener('input', function () {
|
||||
const v = this.value;
|
||||
let score = 0;
|
||||
if (v.length >= 12) score++;
|
||||
if (v.length >= 16) score++;
|
||||
if (/[A-Z]/.test(v)) score++;
|
||||
if (/[0-9]/.test(v)) score++;
|
||||
if (/[^A-Za-z0-9]/.test(v)) score++;
|
||||
const labels = ['', 'Very weak', 'Weak', 'Fair', 'Strong', 'Very strong'];
|
||||
const classes = ['', 'strength-1', 'strength-2', 'strength-3', 'strength-4', 'strength-5'];
|
||||
bar.textContent = v ? labels[score] : '';
|
||||
bar.className = 'password-strength ' + (v ? classes[score] : '');
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
const registerForm = document.getElementById('register-form');
|
||||
if (registerForm) registerForm.addEventListener('submit', handleRegister);
|
||||
|
||||
const loginForm = document.getElementById('login-form');
|
||||
if (loginForm) loginForm.addEventListener('submit', handleLogin);
|
||||
|
||||
const mfaForm = document.getElementById('mfa-form');
|
||||
if (mfaForm) mfaForm.addEventListener('submit', handleMfaVerify);
|
||||
|
||||
document.getElementById('btn-back-to-password')?.addEventListener('click', hideMfaStep);
|
||||
|
||||
initPasswordToggle('toggle-login-pass', 'password');
|
||||
initPasswordToggle('toggle-reg-pass', 'password');
|
||||
initStrengthMeter();
|
||||
|
||||
if (window.location.search.includes('registered=1')) {
|
||||
const notice = document.getElementById('register-notice');
|
||||
if (notice) notice.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
return { init };
|
||||
})();
|
||||
|
||||
document.addEventListener('DOMContentLoaded', Auth.init);
|
||||
|
||||
// ── VaultSession — holds the vault key for the lifetime of the browser tab ──
|
||||
const VaultSession = (() => {
|
||||
let _vaultKey = null;
|
||||
function setKey(key) { _vaultKey = key; }
|
||||
function getKey() { return _vaultKey; }
|
||||
function clear() { _vaultKey = null; }
|
||||
return { setKey, getKey, clear };
|
||||
})();
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* crypto.js — Zero-knowledge cryptography layer
|
||||
*
|
||||
* All encryption/decryption runs in the browser using the Web Crypto API.
|
||||
* The vault key (AES-256-GCM) is derived from the master password client-side
|
||||
* and is NEVER sent to the server. The server only stores encrypted blobs.
|
||||
*
|
||||
* Key derivation chain:
|
||||
* authHash = PBKDF2(masterPassword, email, 100_000 iter, SHA-256) → sent to server for auth
|
||||
* vaultKey = PBKDF2(masterPassword, enc_key_salt, 600_000 iter, SHA-256) → stays in memory only
|
||||
*/
|
||||
|
||||
const Crypto = (() => {
|
||||
const subtle = window.crypto.subtle;
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
function strToBytes(str) {
|
||||
return new TextEncoder().encode(str);
|
||||
}
|
||||
|
||||
function base64ToBytes(b64) {
|
||||
const bin = atob(b64);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
let bin = '';
|
||||
bytes.forEach(b => (bin += String.fromCharCode(b)));
|
||||
return btoa(bin);
|
||||
}
|
||||
|
||||
// ── PBKDF2 key import ────────────────────────────────────────────────────
|
||||
|
||||
async function importPbkdf2Key(masterPassword) {
|
||||
return subtle.importKey(
|
||||
'raw',
|
||||
strToBytes(masterPassword),
|
||||
'PBKDF2',
|
||||
false, // not extractable
|
||||
['deriveBits', 'deriveKey']
|
||||
);
|
||||
}
|
||||
|
||||
// ── Auth hash (sent to server) ───────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Derive an auth token from the master password.
|
||||
* Used ONLY for server-side authentication — never for encryption.
|
||||
* Returns a base64 string safe to POST to /api/auth/login|register.
|
||||
*/
|
||||
async function deriveAuthHash(masterPassword, email) {
|
||||
const baseKey = await importPbkdf2Key(masterPassword);
|
||||
const bits = await subtle.deriveBits(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt: strToBytes(email.toLowerCase()),
|
||||
iterations: 100_000,
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
baseKey,
|
||||
256
|
||||
);
|
||||
return bytesToBase64(new Uint8Array(bits));
|
||||
}
|
||||
|
||||
// ── Vault key (stays in memory) ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Derive the AES-256-GCM vault key from the master password.
|
||||
* enc_key_salt is the base64-encoded 16-byte salt returned by the server on login.
|
||||
* The returned CryptoKey is marked extractable:false — raw bytes cannot be read back.
|
||||
*/
|
||||
async function deriveVaultKey(masterPassword, enc_key_salt) {
|
||||
const baseKey = await importPbkdf2Key(masterPassword);
|
||||
return subtle.deriveKey(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt: base64ToBytes(enc_key_salt),
|
||||
iterations: 600_000,
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
baseKey,
|
||||
{ name: 'AES-GCM', length: 256 },
|
||||
false, // extractable:false — key material cannot be exported
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
}
|
||||
|
||||
// ── Encrypt / Decrypt ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Encrypt a plain JS object with the vault key.
|
||||
* A fresh random 12-byte IV is generated for every call (required for GCM).
|
||||
* Returns { enc_data: base64, iv: base64 }
|
||||
*/
|
||||
async function encryptItem(vaultKey, plaintextObject) {
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = strToBytes(JSON.stringify(plaintextObject));
|
||||
const ciphertext = await subtle.encrypt(
|
||||
{ name: 'AES-GCM', iv },
|
||||
vaultKey,
|
||||
plaintext
|
||||
);
|
||||
return {
|
||||
enc_data: bytesToBase64(new Uint8Array(ciphertext)),
|
||||
iv: bytesToBase64(iv),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt an encrypted vault item back to a JS object.
|
||||
* enc_data and iv must be the base64 strings stored on the server.
|
||||
*/
|
||||
async function decryptItem(vaultKey, enc_data, iv) {
|
||||
const plaintext = await subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: base64ToBytes(iv) },
|
||||
vaultKey,
|
||||
base64ToBytes(enc_data)
|
||||
);
|
||||
return JSON.parse(new TextDecoder().decode(plaintext));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a cryptographically random base64 string (for enc_key_salt).
|
||||
* byteLength defaults to 16 (128-bit salt).
|
||||
*/
|
||||
function generateSalt(byteLength = 16) {
|
||||
return bytesToBase64(window.crypto.getRandomValues(new Uint8Array(byteLength)));
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────────
|
||||
|
||||
return { deriveAuthHash, deriveVaultKey, encryptItem, decryptItem, generateSalt };
|
||||
})();
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* sharing.js — ECDH P-256 cryptography for zero-knowledge item sharing
|
||||
*
|
||||
* Each user has a P-256 keypair:
|
||||
* - Public key : stored on server as base64 raw bytes (65-byte uncompressed point)
|
||||
* - Private key : stored on server as JWK, AES-256-GCM encrypted with the user's vault key
|
||||
*
|
||||
* When Alice shares with Bob:
|
||||
* 1. Alice fetches Bob's public key from the server
|
||||
* 2. Alice derives an ECDH shared secret: ECDH(Alice_priv, Bob_pub)
|
||||
* 3. Alice imports that shared secret as an AES-256-GCM key
|
||||
* 4. Alice encrypts the item's plaintext → (enc_data, iv)
|
||||
* 5. Alice POST /api/sharing with the ciphertext — server stores the blob
|
||||
*
|
||||
* When Bob decrypts:
|
||||
* 1. Bob fetches Alice's public key from the server (returned in inbox response)
|
||||
* 2. Bob derives the same ECDH shared secret: ECDH(Bob_priv, Alice_pub) ← commutative!
|
||||
* 3. Bob decrypts enc_data with the derived key
|
||||
*
|
||||
* The server only ever sees ciphertext. Zero-knowledge.
|
||||
*/
|
||||
|
||||
const SharingCrypto = (() => {
|
||||
const subtle = window.crypto.subtle;
|
||||
|
||||
// ── Helpers (same encoding as crypto.js) ─────────────────────────────────
|
||||
|
||||
function base64ToBytes(b64) {
|
||||
const bin = atob(b64);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
let bin = '';
|
||||
bytes.forEach(b => (bin += String.fromCharCode(b)));
|
||||
return btoa(bin);
|
||||
}
|
||||
|
||||
// ── Key generation ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate a fresh ECDH P-256 keypair.
|
||||
* Both keys are extractable so they can be exported/stored.
|
||||
*/
|
||||
async function generateKeyPair() {
|
||||
return subtle.generateKey(
|
||||
{ name: 'ECDH', namedCurve: 'P-256' },
|
||||
true,
|
||||
['deriveBits'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export the public key as raw bytes (uncompressed point, 65 bytes) → base64.
|
||||
* This is what gets stored on the server and shared with other users.
|
||||
*/
|
||||
async function exportPublicKey(publicKey) {
|
||||
const raw = await subtle.exportKey('raw', publicKey);
|
||||
return bytesToBase64(new Uint8Array(raw));
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt the private key JWK with the user's vault key (AES-256-GCM).
|
||||
* The resulting ciphertext is stored on the server — only the user can decrypt it.
|
||||
*/
|
||||
async function encryptPrivateKey(vaultKey, privateKey) {
|
||||
const jwk = await subtle.exportKey('jwk', privateKey);
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = new TextEncoder().encode(JSON.stringify(jwk));
|
||||
const ciphertext = await subtle.encrypt({ name: 'AES-GCM', iv }, vaultKey, plaintext);
|
||||
return {
|
||||
private_key_enc: bytesToBase64(new Uint8Array(ciphertext)),
|
||||
private_key_iv: bytesToBase64(iv),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt the private key JWK (fetched from server) using the user's vault key.
|
||||
* Returns a CryptoKey usable for ECDH deriveBits.
|
||||
*/
|
||||
async function decryptPrivateKey(vaultKey, private_key_enc, private_key_iv) {
|
||||
const plaintext = await subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: base64ToBytes(private_key_iv) },
|
||||
vaultKey,
|
||||
base64ToBytes(private_key_enc),
|
||||
);
|
||||
const jwk = JSON.parse(new TextDecoder().decode(plaintext));
|
||||
return subtle.importKey(
|
||||
'jwk',
|
||||
jwk,
|
||||
{ name: 'ECDH', namedCurve: 'P-256' },
|
||||
false,
|
||||
['deriveBits'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a remote user's public key from its base64 raw representation.
|
||||
*/
|
||||
async function importPublicKey(base64Raw) {
|
||||
return subtle.importKey(
|
||||
'raw',
|
||||
base64ToBytes(base64Raw),
|
||||
{ name: 'ECDH', namedCurve: 'P-256' },
|
||||
false,
|
||||
[], // public keys have no usages in WebCrypto ECDH
|
||||
);
|
||||
}
|
||||
|
||||
// ── Shared-secret derivation ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Derive an AES-256-GCM CryptoKey from the ECDH shared secret.
|
||||
* ECDH is commutative: ECDH(A_priv, B_pub) === ECDH(B_priv, A_pub).
|
||||
*/
|
||||
async function deriveSharedKey(myPrivateKey, theirPublicKey) {
|
||||
const bits = await subtle.deriveBits(
|
||||
{ name: 'ECDH', public: theirPublicKey },
|
||||
myPrivateKey,
|
||||
256,
|
||||
);
|
||||
return subtle.importKey(
|
||||
'raw',
|
||||
bits,
|
||||
{ name: 'AES-GCM' },
|
||||
false,
|
||||
['encrypt', 'decrypt'],
|
||||
);
|
||||
}
|
||||
|
||||
// ── Encrypt / Decrypt with shared key ────────────────────────────────────
|
||||
|
||||
async function encryptForShare(sharedKey, plaintextObject) {
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = new TextEncoder().encode(JSON.stringify(plaintextObject));
|
||||
const ciphertext = await subtle.encrypt({ name: 'AES-GCM', iv }, sharedKey, plaintext);
|
||||
return {
|
||||
enc_data: bytesToBase64(new Uint8Array(ciphertext)),
|
||||
iv: bytesToBase64(iv),
|
||||
};
|
||||
}
|
||||
|
||||
async function decryptShare(sharedKey, enc_data, iv) {
|
||||
const plaintext = await subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: base64ToBytes(iv) },
|
||||
sharedKey,
|
||||
base64ToBytes(enc_data),
|
||||
);
|
||||
return JSON.parse(new TextDecoder().decode(plaintext));
|
||||
}
|
||||
|
||||
// ── Public API ────────────────────────────────────────────────────────────
|
||||
|
||||
return {
|
||||
generateKeyPair,
|
||||
exportPublicKey,
|
||||
encryptPrivateKey,
|
||||
decryptPrivateKey,
|
||||
importPublicKey,
|
||||
deriveSharedKey,
|
||||
encryptForShare,
|
||||
decryptShare,
|
||||
};
|
||||
})();
|
||||
|
||||
/**
|
||||
* SharingSession — holds the decrypted ECDH private key for the tab lifetime.
|
||||
* Similar to VaultSession; cleared on sign-out.
|
||||
*/
|
||||
const SharingSession = (() => {
|
||||
let _privateKey = null;
|
||||
|
||||
function setKey(key) { _privateKey = key; }
|
||||
function getKey() { return _privateKey; }
|
||||
function clear() { _privateKey = null; }
|
||||
function isReady() { return _privateKey !== null; }
|
||||
|
||||
return { setKey, getKey, clear, isReady };
|
||||
})();
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,72 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Sign In — PassKeeper{% endblock %}
|
||||
{% block body_class %}auth-page{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<div class="auth-container">
|
||||
<div class="auth-card">
|
||||
<div class="auth-logo">
|
||||
<span class="logo-icon">🔒</span>
|
||||
<span class="logo-text">PassKeeper</span>
|
||||
</div>
|
||||
|
||||
<p id="register-notice" class="notice-success hidden">
|
||||
Account created! Please sign in.
|
||||
</p>
|
||||
|
||||
<!-- Step 1: Email + Master Password -->
|
||||
<div id="login-step-1">
|
||||
<h1 class="auth-title">Sign in</h1>
|
||||
<form id="login-form" novalidate>
|
||||
<div class="form-group">
|
||||
<label for="email">Email address</label>
|
||||
<input type="email" id="email" name="email" required
|
||||
autocomplete="email" placeholder="you@example.com">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Master password</label>
|
||||
<div class="input-with-toggle">
|
||||
<input type="password" id="password" name="password" required
|
||||
autocomplete="current-password" placeholder="Enter master password">
|
||||
<button type="button" class="btn-show-pass" id="toggle-login-pass"
|
||||
aria-label="Toggle password visibility">👁</button>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn-primary btn-full" data-loading-text="Verifying…">
|
||||
Sign in
|
||||
</button>
|
||||
</form>
|
||||
<p class="auth-footer">
|
||||
Don't have an account? <a href="/register">Create one</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: TOTP verification (hidden until MFA required) -->
|
||||
<div id="login-step-2" class="hidden">
|
||||
<h1 class="auth-title">Two-factor authentication</h1>
|
||||
<p class="auth-step-hint">Enter the 6-digit code from your authenticator app.</p>
|
||||
<form id="mfa-form" novalidate>
|
||||
<p id="mfa-error" class="form-error hidden">Invalid or expired code. Try again.</p>
|
||||
<div class="form-group">
|
||||
<label for="mfa-code">Authenticator code</label>
|
||||
<input type="text" id="mfa-code" name="mfa_code"
|
||||
inputmode="numeric" pattern="[0-9]{6}" maxlength="6"
|
||||
autocomplete="one-time-code" placeholder="000000">
|
||||
</div>
|
||||
<button type="submit" class="btn-primary btn-full" data-loading-text="Verifying…">
|
||||
Verify
|
||||
</button>
|
||||
</form>
|
||||
<div class="auth-footer">
|
||||
<button class="btn-text" id="btn-back-to-password">← Back to sign in</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/crypto.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/auth.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,55 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Create Account — PassKeeper{% endblock %}
|
||||
{% block body_class %}auth-page{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<div class="auth-container">
|
||||
<div class="auth-card">
|
||||
<div class="auth-logo">
|
||||
<span class="logo-icon">🔒</span>
|
||||
<span class="logo-text">PassKeeper</span>
|
||||
</div>
|
||||
|
||||
<h1 class="auth-title">Create account</h1>
|
||||
|
||||
<div class="notice-info">
|
||||
<strong>Important:</strong> Your master password encrypts all your data.
|
||||
It is <em>never sent to our servers</em>. If you forget it, your vault cannot be recovered.
|
||||
</div>
|
||||
|
||||
<form id="register-form" novalidate>
|
||||
<div class="form-group">
|
||||
<label for="email">Email address</label>
|
||||
<input type="email" id="email" name="email" required
|
||||
autocomplete="email" placeholder="you@example.com">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Master password <span class="hint">(min. 12 characters)</span></label>
|
||||
<div class="input-with-toggle">
|
||||
<input type="password" id="password" name="password" required
|
||||
autocomplete="new-password" minlength="12" placeholder="Create a strong master password">
|
||||
<button type="button" class="btn-show-pass" id="toggle-reg-pass" aria-label="Toggle password visibility">👁</button>
|
||||
</div>
|
||||
<div class="password-strength" id="strength-bar"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="confirm_password">Confirm master password</label>
|
||||
<input type="password" id="confirm_password" name="confirm_password" required
|
||||
autocomplete="new-password" placeholder="Repeat master password">
|
||||
</div>
|
||||
<button type="submit" class="btn-primary btn-full" data-loading-text="Creating account…">
|
||||
Create account
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p class="auth-footer">
|
||||
Already have an account? <a href="/login">Sign in</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/crypto.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/auth.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,20 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self';">
|
||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
||||
<title>{% block title %}PassKeeper{% endblock %}</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/app.css') }}">
|
||||
{% block head_extra %}{% endblock %}
|
||||
</head>
|
||||
<body class="{% block body_class %}{% endblock %}">
|
||||
{% block body %}{% endblock %}
|
||||
|
||||
<div id="toast" class="toast" aria-live="polite"></div>
|
||||
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,419 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}My Vault — PassKeeper{% endblock %}
|
||||
{% block body_class %}vault-page{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<div class="app-layout">
|
||||
|
||||
<!-- ── Sidebar ─────────────────────────────────────────────────── -->
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-header">
|
||||
<span class="logo-icon">🔒</span>
|
||||
<span class="logo-text">PassKeeper</span>
|
||||
</div>
|
||||
|
||||
<nav class="sidebar-nav">
|
||||
<ul>
|
||||
<li class="sidebar-item active" id="sidebar-all" data-view="vault">
|
||||
<span class="sidebar-icon">🏠</span> <span class="sidebar-label">All Items</span>
|
||||
</li>
|
||||
<li class="sidebar-section-header">Item Types</li>
|
||||
<li class="sidebar-item" data-type-filter="password">
|
||||
<span class="sidebar-icon">🔑</span> <span class="sidebar-label">Passwords</span>
|
||||
</li>
|
||||
<li class="sidebar-item" data-type-filter="note">
|
||||
<span class="sidebar-icon">📝</span> <span class="sidebar-label">Secure Notes</span>
|
||||
</li>
|
||||
<li class="sidebar-item" data-type-filter="card">
|
||||
<span class="sidebar-icon">💳</span> <span class="sidebar-label">Payment Cards</span>
|
||||
</li>
|
||||
<li class="sidebar-item" data-type-filter="bank">
|
||||
<span class="sidebar-icon">🏦</span> <span class="sidebar-label">Bank Accounts</span>
|
||||
</li>
|
||||
<li class="sidebar-item" data-type-filter="address">
|
||||
<span class="sidebar-icon">🏠</span> <span class="sidebar-label">Addresses</span>
|
||||
</li>
|
||||
<li class="sidebar-item" data-type-filter="ssn">
|
||||
<span class="sidebar-icon">🪪</span> <span class="sidebar-label">Identities</span>
|
||||
</li>
|
||||
<li class="sidebar-section-header">Tools</li>
|
||||
<li class="sidebar-item" id="sidebar-security" data-view="security">
|
||||
<span class="sidebar-icon">🛡️</span> <span class="sidebar-label">Security</span>
|
||||
</li>
|
||||
<li class="sidebar-item" id="sidebar-sharing" data-view="sharing">
|
||||
<span class="sidebar-icon">🔗</span> <span class="sidebar-label">Sharing</span>
|
||||
</li>
|
||||
<li class="sidebar-item" id="sidebar-emergency" data-view="emergency">
|
||||
<span class="sidebar-icon">🚨</span> <span class="sidebar-label">Emergency Access</span>
|
||||
</li>
|
||||
<li class="sidebar-section-header">
|
||||
Folders
|
||||
<button class="btn-new-folder" id="btn-new-folder" title="New folder">+</button>
|
||||
</li>
|
||||
<li id="new-folder-row" class="new-folder-row hidden">
|
||||
<form id="new-folder-form">
|
||||
<input type="text" id="new-folder-input" placeholder="Folder name" maxlength="128">
|
||||
<button type="submit" class="btn-icon" title="Save">✓</button>
|
||||
<button type="button" class="btn-icon" id="btn-cancel-folder" title="Cancel">✕</button>
|
||||
</form>
|
||||
</li>
|
||||
<ul id="sidebar-folders"></ul>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-footer">
|
||||
<button class="sidebar-item btn-text" id="btn-settings">
|
||||
<span class="sidebar-icon">⚙️</span> <span class="sidebar-label">Settings</span>
|
||||
</button>
|
||||
<button class="sidebar-item btn-text" id="btn-logout">
|
||||
<span class="sidebar-icon">🚪</span> <span class="sidebar-label">Sign out</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- ── Main ───────────────────────────────────────────────────── -->
|
||||
<main class="vault-main">
|
||||
|
||||
<!-- Vault view -->
|
||||
<div id="view-vault">
|
||||
<header class="vault-header">
|
||||
<h2 class="vault-title" id="vault-title">All Items</h2>
|
||||
<div class="vault-toolbar">
|
||||
<div class="search-wrapper">
|
||||
<span class="search-icon">🔍</span>
|
||||
<input type="search" id="search-input" placeholder="Search vault…" autocomplete="off">
|
||||
</div>
|
||||
<div class="sort-wrapper">
|
||||
<select id="sort-select" title="Sort by">
|
||||
<option value="name-asc">Name A–Z</option>
|
||||
<option value="name-desc">Name Z–A</option>
|
||||
<option value="date-desc">Newest first</option>
|
||||
<option value="date-asc">Oldest first</option>
|
||||
<option value="folder">By folder</option>
|
||||
</select>
|
||||
</div>
|
||||
<button class="btn-fab" id="btn-add-item" title="Add item">+</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="vault-spinner" class="spinner-overlay hidden"><div class="spinner"></div></div>
|
||||
<ul id="vault-list" class="vault-list"></ul>
|
||||
</div>
|
||||
|
||||
<!-- Security dashboard view -->
|
||||
<div id="view-security" class="hidden">
|
||||
<header class="vault-header"><h2 class="vault-title">Security Dashboard</h2></header>
|
||||
<div class="security-dashboard">
|
||||
<div class="security-summary" id="security-summary"></div>
|
||||
<div class="security-sections" id="security-sections"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sharing view -->
|
||||
<div id="view-sharing" class="hidden">
|
||||
<header class="vault-header">
|
||||
<h2 class="vault-title">Sharing</h2>
|
||||
<div class="vault-toolbar">
|
||||
<button class="btn-primary btn-sm" id="btn-share-item">+ Share an item</button>
|
||||
</div>
|
||||
</header>
|
||||
<div class="panel-body">
|
||||
<div id="sharing-keys-notice" class="notice-info hidden">
|
||||
You need to set up sharing keys before you can share items.
|
||||
<button class="btn-primary btn-sm" id="btn-setup-keys-from-sharing">Set up keys</button>
|
||||
</div>
|
||||
<div class="panel-tabs">
|
||||
<button class="tab-btn active" data-tab="shared-out">Shared by me</button>
|
||||
<button class="tab-btn" data-tab="shared-in">Shared with me</button>
|
||||
</div>
|
||||
<div id="tab-shared-out" class="tab-pane">
|
||||
<ul id="shared-out-list" class="share-list"></ul>
|
||||
</div>
|
||||
<div id="tab-shared-in" class="tab-pane hidden">
|
||||
<ul id="shared-in-list" class="share-list"></ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Emergency Access view -->
|
||||
<div id="view-emergency" class="hidden">
|
||||
<header class="vault-header">
|
||||
<h2 class="vault-title">Emergency Access</h2>
|
||||
<div class="vault-toolbar">
|
||||
<button class="btn-primary btn-sm" id="btn-add-emergency">+ Add trusted contact</button>
|
||||
</div>
|
||||
</header>
|
||||
<div class="panel-body">
|
||||
<div class="panel-tabs">
|
||||
<button class="tab-btn active" data-tab="em-grants">My trusted contacts</button>
|
||||
<button class="tab-btn" data-tab="em-access">I'm a trusted contact</button>
|
||||
</div>
|
||||
<div id="tab-em-grants" class="tab-pane">
|
||||
<ul id="em-grants-list" class="share-list"></ul>
|
||||
</div>
|
||||
<div id="tab-em-access" class="tab-pane hidden">
|
||||
<ul id="em-access-list" class="share-list"></ul>
|
||||
<div id="em-vault-panel" class="em-vault-panel hidden">
|
||||
<div class="em-vault-header">
|
||||
<h4>Emergency Vault — Decrypted Items</h4>
|
||||
<button class="btn-secondary btn-sm" id="btn-em-vault-back">← Back</button>
|
||||
</div>
|
||||
<ul id="em-vault-list" class="em-vault-list"></ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- ── Unlock overlay ──────────────────────────────────────────────── -->
|
||||
<div id="unlock-overlay" class="modal-overlay" role="dialog" aria-modal="true" aria-labelledby="unlock-title">
|
||||
<div class="modal modal-unlock">
|
||||
<div class="auth-logo unlock-logo"><span class="logo-icon">🔒</span><span class="logo-text">PassKeeper</span></div>
|
||||
<h3 id="unlock-title" class="unlock-title">Unlock your vault</h3>
|
||||
<p class="unlock-subtitle">Re-enter your master password to continue.</p>
|
||||
<p id="unlock-error" class="form-error hidden">Incorrect master password.</p>
|
||||
<form id="unlock-form" novalidate>
|
||||
<div class="form-group">
|
||||
<label for="unlock-password">Master password</label>
|
||||
<input type="password" id="unlock-password" autocomplete="current-password" placeholder="Enter master password">
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<a href="/login" class="btn-secondary btn-link">Sign out</a>
|
||||
<button type="submit" class="btn-primary">Unlock</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Add / Edit Item Modal ─────────────────────────────────────────── -->
|
||||
<div id="item-modal" class="modal-overlay" role="dialog" aria-modal="true" aria-labelledby="modal-title">
|
||||
<div class="modal modal-item">
|
||||
<div class="modal-header">
|
||||
<h3 id="modal-title">Add Item</h3>
|
||||
<button class="btn-icon btn-close" id="btn-close-modal" aria-label="Close">✕</button>
|
||||
</div>
|
||||
<form id="item-form" novalidate>
|
||||
<div class="form-group" id="type-selector-group">
|
||||
<label for="field-type">Item Type</label>
|
||||
<select id="field-type" name="item_type">
|
||||
<option value="password">🔑 Password</option>
|
||||
<option value="note">📝 Secure Note</option>
|
||||
<option value="card">💳 Payment Card</option>
|
||||
<option value="bank">🏦 Bank Account</option>
|
||||
<option value="address">🏠 Address</option>
|
||||
<option value="ssn">🪪 Identity (SSN)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="field-name">Name <span class="required">*</span></label>
|
||||
<input type="text" id="field-name" name="name" required placeholder="e.g. Gmail">
|
||||
</div>
|
||||
<div class="type-fields" data-for-types="password">
|
||||
<div class="form-group"><label for="field-url">Website URL</label><input type="url" id="field-url" placeholder="https://example.com"></div>
|
||||
<div class="form-group"><label for="field-username">Username / Email</label><input type="text" id="field-username" autocomplete="off" placeholder="username or email"></div>
|
||||
<div class="form-group">
|
||||
<label for="field-password">Password</label>
|
||||
<div class="input-with-toggle">
|
||||
<input type="password" id="field-password" autocomplete="new-password" placeholder="Enter password">
|
||||
<button type="button" class="btn-show-pass" id="btn-toggle-pass" aria-label="Toggle">👁</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="type-fields hidden" data-for-types="note">
|
||||
<div class="form-group"><label for="field-note-body">Note</label><textarea id="field-note-body" rows="6" placeholder="Enter your secure note…"></textarea></div>
|
||||
</div>
|
||||
<div class="type-fields hidden" data-for-types="card">
|
||||
<div class="form-group"><label for="field-cardholder">Cardholder Name</label><input type="text" id="field-cardholder" placeholder="Name on card"></div>
|
||||
<div class="form-group"><label for="field-card-number">Card Number</label><input type="text" id="field-card-number" autocomplete="off" placeholder="•••• •••• •••• ••••" maxlength="19"></div>
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label for="field-expiry-month">Expiry Month</label>
|
||||
<select id="field-expiry-month"><option value="">MM</option>
|
||||
<option value="01">01</option><option value="02">02</option><option value="03">03</option><option value="04">04</option>
|
||||
<option value="05">05</option><option value="06">06</option><option value="07">07</option><option value="08">08</option>
|
||||
<option value="09">09</option><option value="10">10</option><option value="11">11</option><option value="12">12</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group"><label for="field-expiry-year">Year</label><input type="text" id="field-expiry-year" placeholder="YYYY" maxlength="4"></div>
|
||||
<div class="form-group"><label for="field-cvv">CVV</label><input type="text" id="field-cvv" autocomplete="off" placeholder="•••" maxlength="4"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="type-fields hidden" data-for-types="bank">
|
||||
<div class="form-group"><label for="field-bank-name">Bank Name</label><input type="text" id="field-bank-name" placeholder="e.g. Chase"></div>
|
||||
<div class="form-group"><label for="field-account-type">Account Type</label>
|
||||
<select id="field-account-type"><option value="">— Select —</option><option value="checking">Checking</option><option value="savings">Savings</option><option value="money_market">Money Market</option><option value="other">Other</option></select>
|
||||
</div>
|
||||
<div class="form-group"><label for="field-routing">Routing Number</label><input type="text" id="field-routing" autocomplete="off" placeholder="9-digit routing number" maxlength="9"></div>
|
||||
<div class="form-group"><label for="field-account-number">Account Number</label><input type="text" id="field-account-number" autocomplete="off" placeholder="Account number"></div>
|
||||
</div>
|
||||
<div class="type-fields hidden" data-for-types="address">
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label for="field-first-name">First Name</label><input type="text" id="field-first-name" placeholder="First name"></div>
|
||||
<div class="form-group"><label for="field-last-name">Last Name</label><input type="text" id="field-last-name" placeholder="Last name"></div>
|
||||
</div>
|
||||
<div class="form-group"><label for="field-company">Company</label><input type="text" id="field-company" placeholder="Company (optional)"></div>
|
||||
<div class="form-group"><label for="field-address-line">Street Address</label><input type="text" id="field-address-line" placeholder="123 Main St"></div>
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label for="field-city">City</label><input type="text" id="field-city" placeholder="City"></div>
|
||||
<div class="form-group"><label for="field-state">State</label><input type="text" id="field-state" placeholder="State"></div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label for="field-zip">ZIP</label><input type="text" id="field-zip" placeholder="ZIP"></div>
|
||||
<div class="form-group"><label for="field-country">Country</label><input type="text" id="field-country" placeholder="Country"></div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group"><label for="field-phone">Phone</label><input type="tel" id="field-phone" placeholder="+1 555-000-0000"></div>
|
||||
<div class="form-group"><label for="field-email">Email</label><input type="email" id="field-email" placeholder="email@example.com"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="type-fields hidden" data-for-types="ssn">
|
||||
<div class="form-group"><label for="field-ssn-number">Social Security Number</label>
|
||||
<div class="input-with-toggle">
|
||||
<input type="password" id="field-ssn-number" autocomplete="off" placeholder="•••-••-••••" maxlength="11">
|
||||
<button type="button" class="btn-show-pass" id="btn-toggle-ssn" aria-label="Toggle">👁</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="field-folder">Folder</label>
|
||||
<select id="field-folder"><option value="">— No folder —</option></select>
|
||||
</div>
|
||||
<div class="type-fields" data-for-types="password card bank address ssn">
|
||||
<div class="form-group"><label for="field-notes">Notes</label><textarea id="field-notes" rows="3" placeholder="Optional notes…"></textarea></div>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn-secondary" id="btn-cancel-modal">Cancel</button>
|
||||
<button type="submit" class="btn-primary">Save</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Account Settings Modal ────────────────────────────────────────── -->
|
||||
<div id="settings-modal" class="modal-overlay" role="dialog" aria-modal="true">
|
||||
<div class="modal modal-settings">
|
||||
<div class="modal-header">
|
||||
<h3>Account Settings</h3>
|
||||
<button class="btn-icon btn-close" id="btn-close-settings" aria-label="Close">✕</button>
|
||||
</div>
|
||||
|
||||
<!-- MFA Section -->
|
||||
<div class="settings-section">
|
||||
<h4 class="settings-section-title">🔐 Two-Factor Authentication</h4>
|
||||
<div id="mfa-status-area">
|
||||
<p id="mfa-status-text" class="settings-desc"></p>
|
||||
<div id="mfa-setup-area" class="hidden">
|
||||
<img id="mfa-qr-img" src="" alt="QR Code" class="mfa-qr">
|
||||
<p class="settings-desc">Scan with Google Authenticator or Authy, then enter the 6-digit code below.</p>
|
||||
<p class="settings-desc mfa-secret-text">Manual key: <code id="mfa-secret-display"></code></p>
|
||||
<div class="form-group">
|
||||
<label for="mfa-verify-code">Verification code</label>
|
||||
<input type="text" id="mfa-verify-code" inputmode="numeric" maxlength="6" placeholder="000000">
|
||||
</div>
|
||||
<button class="btn-primary" id="btn-mfa-confirm">Enable MFA</button>
|
||||
<button class="btn-secondary" id="btn-mfa-cancel-setup">Cancel</button>
|
||||
</div>
|
||||
<div id="mfa-disable-area" class="hidden">
|
||||
<div class="form-group">
|
||||
<label for="mfa-disable-code">Enter your current code to disable MFA</label>
|
||||
<input type="text" id="mfa-disable-code" inputmode="numeric" maxlength="6" placeholder="000000">
|
||||
</div>
|
||||
<button class="btn-primary" id="btn-mfa-disable-confirm">Disable MFA</button>
|
||||
<button class="btn-secondary" id="btn-mfa-disable-cancel">Cancel</button>
|
||||
</div>
|
||||
<div id="mfa-actions"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sharing Keys Section -->
|
||||
<div class="settings-section">
|
||||
<h4 class="settings-section-title">🔗 Sharing & Emergency Access Keys</h4>
|
||||
<p id="sharing-keys-status" class="settings-desc"></p>
|
||||
<div id="sharing-keys-actions"></div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Share Item Modal ───────────────────────────────────────────────── -->
|
||||
<div id="share-modal" class="modal-overlay" role="dialog" aria-modal="true">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3>Share an Item</h3>
|
||||
<button class="btn-icon btn-close" id="btn-close-share-modal" aria-label="Close">✕</button>
|
||||
</div>
|
||||
<form id="share-form" novalidate>
|
||||
<p id="share-error" class="form-error hidden"></p>
|
||||
<div class="form-group">
|
||||
<label for="share-item-select">Item to share</label>
|
||||
<select id="share-item-select"></select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="share-recipient-email">Recipient's email</label>
|
||||
<input type="email" id="share-recipient-email" placeholder="recipient@example.com">
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn-secondary" id="btn-cancel-share">Cancel</button>
|
||||
<button type="submit" class="btn-primary">Share</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Emergency Access Setup Modal ──────────────────────────────────── -->
|
||||
<div id="emergency-modal" class="modal-overlay" role="dialog" aria-modal="true">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3>Add Emergency Contact</h3>
|
||||
<button class="btn-icon btn-close" id="btn-close-emergency-modal" aria-label="Close">✕</button>
|
||||
</div>
|
||||
<form id="emergency-form" novalidate>
|
||||
<p id="emergency-error" class="form-error hidden"></p>
|
||||
<p class="settings-desc">
|
||||
Your trusted contact will be able to request access to your vault after a waiting period
|
||||
if you are unable to access your account.
|
||||
</p>
|
||||
<div class="form-group">
|
||||
<label for="emergency-email">Trusted contact's email</label>
|
||||
<input type="email" id="emergency-email" placeholder="contact@example.com">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="emergency-wait-days">Wait period (days)</label>
|
||||
<select id="emergency-wait-days">
|
||||
<option value="1">1 day</option>
|
||||
<option value="3">3 days</option>
|
||||
<option value="7" selected>7 days</option>
|
||||
<option value="14">14 days</option>
|
||||
<option value="30">30 days</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn-secondary" id="btn-cancel-emergency">Cancel</button>
|
||||
<button type="submit" class="btn-primary">Send Invitation</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Item Detail Modal (read-only: shared items) ────────────────────── -->
|
||||
<div id="detail-modal" class="modal-overlay" role="dialog" aria-modal="true" aria-labelledby="detail-modal-title">
|
||||
<div class="modal modal-detail">
|
||||
<div class="modal-header">
|
||||
<h3 id="detail-modal-title">Item Details</h3>
|
||||
<button class="btn-icon btn-close" id="btn-close-detail-modal" aria-label="Close">✕</button>
|
||||
</div>
|
||||
<div id="detail-modal-body" class="detail-body"></div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn-secondary" id="btn-detail-done">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/crypto.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/auth.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/sharing.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/vault.js') }}"></script>
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user