Remember SQL connections in the browser, never the password

This commit is contained in:
Roberto Treviño Cervantes
2026-11-12 01:13:34 -06:00
parent f4d2a3e85f
commit 0ee53fd286
5 changed files with 217 additions and 0 deletions
@@ -85,6 +85,31 @@
</mat-form-field>
</form>
} @else {
@if (savedConnections().length) {
<div class="saved-connections">
<span class="saved-connections__label">Conexiones guardadas</span>
<div class="saved-connections__list">
@for (saved of savedConnections(); track saved.id) {
<div class="saved-connection">
<button type="button" class="saved-connection__pick" matRipple (click)="applySaved(saved)">
<mat-icon aria-hidden="true">storage</mat-icon>
<span>{{ saved.label }}</span>
</button>
<button
mat-icon-button
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Olvidar esta conexión guardada"
matTooltip="Olvidar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
</div>
}
</div>
</div>
}
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
<mat-form-field appearance="outline" class="db-form__host">
<mat-label>Servidor</mat-label>
@@ -108,6 +133,9 @@
<input matInput type="password" formControlName="password" autocomplete="new-password" />
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Recordar servidor, usuario y base de datos (nunca la contraseña)
</mat-checkbox>
}
@if (testing()) {
@@ -80,6 +80,62 @@
color: var(--mat-sys-on-surface-variant);
}
.saved-connections {
margin-bottom: var(--space-4);
}
.saved-connections__label {
color: var(--mat-sys-on-surface-variant);
display: block;
font: var(--mat-sys-label-small);
margin-bottom: var(--space-1);
}
.saved-connections__list {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.saved-connection {
align-items: center;
background: var(--mat-sys-surface-variant);
border-radius: var(--mat-sys-corner-full);
display: flex;
gap: var(--space-1);
padding-right: var(--space-1);
}
.saved-connection__pick {
align-items: center;
background: none;
border: 0;
color: var(--mat-sys-on-surface-variant);
cursor: pointer;
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-1);
padding: var(--space-1) 0 var(--space-1) var(--space-3);
mat-icon {
font-size: 18px;
height: 18px;
width: 18px;
}
}
.saved-connection__forget {
--mdc-icon-button-state-layer-size: 28px;
height: 28px;
width: 28px;
mat-icon {
font-size: 16px;
height: 16px;
width: 16px;
}
}
.db-form {
display: grid;
gap: 0 var(--space-4);
@@ -1,6 +1,7 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
@@ -17,6 +18,7 @@ import { SourceGateway } from '../../api/source-gateway';
import { connectionsFor } from '../../domain/connection-registry';
import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog';
import { DataConnection } from '../../domain/data-source';
import { SavedSqlConnection, listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from '../../domain/saved-sql-connections';
import { SqlConnection } from '../../domain/sql-source';
import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url';
import { FileDropzone } from '../file-dropzone/file-dropzone';
@@ -33,6 +35,7 @@ type View = 'catalog' | 'files' | 'database';
imports: [
FileDropzone,
MatButtonModule,
MatCheckboxModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -95,6 +98,7 @@ export class ConnectorGalleryDialog {
readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] });
readonly testing = signal(false);
readonly testResult = signal<{ ok: boolean; message: string } | null>(null);
readonly remember = signal(false);
readonly engine = computed(() => this.entry()?.engine ?? null);
readonly serverEngine = computed(() => {
@@ -102,10 +106,29 @@ export class ConnectorGalleryDialog {
return engine && engine !== 'url' ? engine : null;
});
private readonly savedConnectionsAll = signal(listSavedSqlConnections());
/** Only the ones for the engine currently picked, so a saved SQL Server entry never fills a MySQL form. */
readonly savedConnections = computed(() => {
const engineId = this.serverEngine()?.id;
return engineId ? this.savedConnectionsAll().filter((saved) => saved.engine === engineId) : [];
});
applySaved(saved: SavedSqlConnection): void {
this.serverForm.patchValue({ host: saved.host, port: saved.port, database: saved.database, user: saved.user });
this.testResult.set(null);
}
forgetSaved(saved: SavedSqlConnection, event: Event): void {
event.stopPropagation();
removeSqlConnection(saved.id);
this.savedConnectionsAll.set(listSavedSqlConnections());
}
pick(entry: GalleryEntry): void {
if (!entry.available) return;
this.entry.set(entry);
this.testResult.set(null);
this.remember.set(false);
this.view.set(entry.engine ? 'database' : 'files');
}
@@ -143,6 +166,10 @@ export class ConnectorGalleryDialog {
connectDatabase(): void {
const ref = this.connectionRef();
if (!ref) return;
if (this.remember() && 'server' in ref) {
const { password: _password, ...shape } = ref.server;
saveSqlConnection({ label: this.connectionLabel(), ...shape });
}
this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]);
}
@@ -0,0 +1,47 @@
import { listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from './saved-sql-connections';
describe('saved SQL connections', () => {
beforeEach(() => localStorage.clear());
it('never stores a password field', () => {
const saved = saveSqlConnection({ label: 'HIS · lector@his.local', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
expect(Object.keys(saved)).not.toContain('password');
expect(JSON.parse(localStorage.getItem('isssteleon.connect.savedSqlConnections')!)[0]).not.toHaveProperty('password');
});
it('upserts by connection shape instead of growing duplicates', () => {
const entry = { label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' };
saveSqlConnection(entry);
saveSqlConnection({ ...entry, label: 'HIS (renamed)' });
const all = listSavedSqlConnections();
expect(all.length).toBe(1);
expect(all[0].label).toBe('HIS (renamed)');
});
it('keeps connections to different servers separate', () => {
saveSqlConnection({ label: 'A', engine: 'mssql', host: 'a.local', port: 1433, database: 'HIS', user: 'lector' });
saveSqlConnection({ label: 'B', engine: 'mysql', host: 'b.local', port: 3306, database: 'HIS', user: 'lector' });
expect(listSavedSqlConnections().length).toBe(2);
});
it('removes a saved connection by id', () => {
const saved = saveSqlConnection({ label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
removeSqlConnection(saved.id);
expect(listSavedSqlConnections()).toEqual([]);
});
it('caps the list so it cannot grow without bound', () => {
for (let i = 0; i < 25; i++) {
saveSqlConnection({ label: `db${i}`, engine: 'mssql', host: `host${i}`, port: 1433, database: 'HIS', user: 'lector' });
}
expect(listSavedSqlConnections().length).toBeLessThanOrEqual(20);
});
it('degrades to an empty list rather than throwing when storage is unreadable', () => {
const spy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked');
});
expect(listSavedSqlConnections()).toEqual([]);
spy.mockRestore();
});
});
@@ -0,0 +1,59 @@
const STORAGE_KEY = 'isssteleon.connect.savedSqlConnections';
const MAX_SAVED = 20;
/**
* A database connection's shape, remembered across visits so the form
* doesn't need retyping. Never the password: credentials travel with every
* request and are never stored (see `sql-source.ts`), so reconnecting
* through a saved entry still asks for it.
*/
export interface SavedSqlConnection {
id: string;
label: string;
engine: string;
host: string;
port: number | null;
database: string;
user: string;
}
export type SavedSqlConnectionInput = Omit<SavedSqlConnection, 'id'>;
function connectionId(entry: SavedSqlConnectionInput): string {
return [entry.engine, entry.host, entry.port ?? '', entry.database, entry.user].join('|');
}
function readAll(): SavedSqlConnection[] {
try {
const raw = localStorage.getItem(STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function writeAll(entries: SavedSqlConnection[]): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
} catch {
// Private browsing, a cleared/blocked store, or a full quota: the form
// just won't remember anything this time, nothing to surface to the user.
}
}
export function listSavedSqlConnections(): SavedSqlConnection[] {
return readAll();
}
/** Upserts by connection shape (engine/host/port/database/user), newest first. */
export function saveSqlConnection(entry: SavedSqlConnectionInput): SavedSqlConnection {
const saved: SavedSqlConnection = { ...entry, id: connectionId(entry) };
const rest = readAll().filter((existing) => existing.id !== saved.id);
writeAll([saved, ...rest].slice(0, MAX_SAVED));
return saved;
}
export function removeSqlConnection(id: string): void {
writeAll(readAll().filter((existing) => existing.id !== id));
}