diff --git a/app/apps/evenhub/credentials.ts b/app/apps/evenhub/credentials.ts index 2273c750..491328fc 100644 --- a/app/apps/evenhub/credentials.ts +++ b/app/apps/evenhub/credentials.ts @@ -1,24 +1,86 @@ -import { ConfigSettingString } from "../../ui/dashboard-settings"; +import { + ConfigSettingBoolean, + ConfigSettingString, +} from "../../ui/dashboard-settings"; +import { getStringSetting, setStringSetting } from "../../native/settings-store"; /** - * EvenHub owns its account configuration. The storage keys intentionally - * match the former Settings-app entries so existing users stay signed in. + * Persistent EvenHub session data. Passwords are deliberately excluded: the + * password entered in the login form lives only in memory until the request + * completes, while a successful login may persist the returned token. */ export const evenHubEmailSetting = new ConfigSettingString({ - id: "evenhub-email", + id: "evenhub-saved-email", label: "Email", storageKey: "integrations.evenhub.email", defaultValue: "", + normalize: normalizeEmail, +}); + +export const evenHubTokenSetting = new ConfigSettingString({ + id: "evenhub-token", + label: "Login token", + storageKey: "integrations.evenhub.token", + defaultValue: "", + inputKind: "password", + normalize: normalizeToken, + formatValue: (value) => (value ? "(signed in)" : "(signed out)"), +}); + +class TransientStringSetting extends ConfigSettingString { + private value: string; + private readonly normalizeValue: (value: string | null | undefined) => string; + + constructor(options: ConstructorParameters[0]) { + super(options); + this.normalizeValue = options.normalize ?? ((value) => value ?? ""); + this.value = this.normalizeValue(options.defaultValue); + } + + override get(): string { + return this.value; + } + + override set(value: string): string { + this.value = this.normalizeValue(value); + return this.value; + } +} + +class TransientBooleanSetting extends ConfigSettingBoolean { + private value: boolean; + + constructor(options: ConstructorParameters[0]) { + super(options); + this.value = options.defaultValue; + } + + override get(): boolean { + return this.value; + } + + override set(value: boolean): boolean { + this.value = value; + return value; + } +} + +/** Phone login-form values. These overrides never touch the settings store. */ +export const evenHubLoginEmailSetting = new TransientStringSetting({ + id: "evenhub-login-email", + label: "Email", + storageKey: "transient.evenhub.email", + defaultValue: "", editorTitle: "Email", glassesEditTitle: "Edit Even email", inputKind: "email", - normalize: (value) => (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(), + normalize: normalizeEmail, }); -export const evenHubPasswordSetting = new ConfigSettingString({ - id: "evenhub-password", +export const evenHubLoginPasswordSetting = new TransientStringSetting({ + id: "evenhub-login-password", label: "Password", - storageKey: "integrations.evenhub.password", + storageKey: "transient.evenhub.password", defaultValue: "", editorTitle: "Password", glassesEditTitle: "Edit Even password", @@ -27,10 +89,80 @@ export const evenHubPasswordSetting = new ConfigSettingString({ formatValue: (value) => (value ? "(set)" : "(not set)"), }); -export function hasEvenHubCredentials(): boolean { - return Boolean(evenHubEmailSetting.get().trim() && evenHubPasswordSetting.get()); +export const evenHubRememberMeSetting = new TransientBooleanSetting({ + id: "evenhub-remember-me", + label: "Remember me", + storageKey: "transient.evenhub.rememberMe", + defaultValue: true, +}); + +let transientToken = ""; + +export function getEvenHubToken(): string { + return transientToken || evenHubTokenSetting.get(); } -export function clearEvenHubPassword(): void { - evenHubPasswordSetting.set(""); +export function hasEvenHubCredentials(): boolean { + return Boolean(getEvenHubToken()); +} + +export function saveEvenHubSession(email: string, token: string, remember: boolean): void { + const normalizedEmail = normalizeEmail(email); + const normalizedToken = normalizeToken(token); + if (remember) { + evenHubEmailSetting.set(normalizedEmail); + evenHubTokenSetting.set(normalizedToken); + transientToken = ""; + } else { + evenHubEmailSetting.set(""); + evenHubTokenSetting.set(""); + transientToken = normalizedToken; + } +} + +/** Clear a rejected token but retain a remembered email for the next login. */ +export function invalidateEvenHubToken(): void { + transientToken = ""; + evenHubTokenSetting.set(""); +} + +export function clearEvenHubSession(): void { + transientToken = ""; + evenHubEmailSetting.set(""); + evenHubTokenSetting.set(""); + clearEvenHubLoginForm(); +} + +export function resetEvenHubLoginForm(): void { + evenHubLoginEmailSetting.set(evenHubEmailSetting.get()); + evenHubLoginPasswordSetting.set(""); + evenHubRememberMeSetting.set(true); +} + +export function clearEvenHubLoginForm(): void { + evenHubLoginEmailSetting.set(""); + evenHubLoginPasswordSetting.set(""); + evenHubRememberMeSetting.set(true); +} + +/** Discard a window-scoped session; remembered sessions are left intact. */ +export function clearTransientEvenHubSession(): void { + if (transientToken) transientToken = ""; + clearEvenHubLoginForm(); +} + +function normalizeEmail(value: string | null | undefined): string { + return (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(); +} + +function normalizeToken(value: string | null | undefined): string { + return (value ?? "").replace(/[\x00-\x20\x7f]+/g, "").trim(); +} + +// One-time security migration from builds that persisted the account password. +// Existing users must sign in once more so the password can be exchanged for a +// token under the new storage model. +const LEGACY_PASSWORD_KEY = "integrations.evenhub.password"; +if (getStringSetting(LEGACY_PASSWORD_KEY, "")) { + setStringSetting(LEGACY_PASSWORD_KEY, ""); } diff --git a/app/apps/evenhub/even-api.ts b/app/apps/evenhub/even-api.ts index 1a099207..ea8a5ba6 100644 --- a/app/apps/evenhub/even-api.ts +++ b/app/apps/evenhub/even-api.ts @@ -6,7 +6,12 @@ * the same signed-header scheme used by the firmware API. */ import { Application } from "@nativescript/core"; -import { evenHubEmailSetting, evenHubPasswordSetting, hasEvenHubCredentials } from "./credentials"; +import { + getEvenHubToken, + hasEvenHubCredentials, + invalidateEvenHubToken, + saveEvenHubSession, +} from "./credentials"; import { fetchWithUserAgent } from "../../util/http"; declare const android: any; @@ -72,7 +77,6 @@ export class EvenHubAuthenticationError extends Error { } export class EvenHubApiClient { - private token = ""; private loginPromise: Promise | null = null; async listApps(page = 1, category = ""): Promise { @@ -147,9 +151,13 @@ export class EvenHubApiClient { return { bytes, extension: extension === "jpeg" ? "jpg" : extension }; } - clearSession(): void { - this.token = ""; - this.loginPromise = null; + async signIn(email: string, password: string, remember: boolean): Promise { + if (!this.loginPromise) { + this.loginPromise = this.login(email, password, remember).finally(() => { + this.loginPromise = null; + }); + } + await this.loginPromise; } private async authenticatedRequest( @@ -158,38 +166,30 @@ export class EvenHubApiClient { options: { query?: Record; body?: Record } = {}, ): Promise { let token = await this.ensureLogin(); - let response = await this.request(method, path, { ...options, token, commonVersion: 3 }); + const response = await this.request(method, path, { ...options, token, commonVersion: 3 }); if (response.httpStatus === 401) { - this.clearSession(); - token = await this.ensureLogin(); - response = await this.request(method, path, { ...options, token, commonVersion: 3 }); + invalidateEvenHubToken(); } return unwrap(response.envelope, response.httpStatus, path); } private ensureLogin(): Promise { - if (this.token) return Promise.resolve(this.token); - if (!isEvenHubStoreConfigured()) { - return Promise.reject(new EvenHubAuthenticationError("Enter your Even account email and password.")); - } - if (!this.loginPromise) { - this.loginPromise = this.login().finally(() => { - this.loginPromise = null; - }); - } - return this.loginPromise; + const token = getEvenHubToken(); + return token + ? Promise.resolve(token) + : Promise.reject(new EvenHubAuthenticationError("Enter your Even account email and password.")); } - private async login(): Promise { + private async login(email: string, password: string, remember: boolean): Promise { try { const response = await this.request("POST", "/v2/g/login", { commonVersion: 1, - body: { email: evenHubEmailSetting.get().trim(), passwd: evenHubPasswordSetting.get() }, + body: { email: email.trim(), passwd: password }, }); const data = asRecord(unwrap(response.envelope, response.httpStatus, "/v2/g/login")); const token = typeof data.token === "string" ? data.token : ""; if (!token) throw new Error("Even login succeeded without returning a session token."); - this.token = token; + saveEvenHubSession(email, token, remember); return token; } catch (error) { if (error instanceof EvenHubAuthenticationError) throw error; diff --git a/app/apps/evenhub/index.ts b/app/apps/evenhub/index.ts index 073294d0..d938c123 100644 --- a/app/apps/evenhub/index.ts +++ b/app/apps/evenhub/index.ts @@ -73,7 +73,7 @@ const evenhubApp: AppDefinition = { setSurfaceVisible: options.setSurfaceVisible, removeSurface: options.removeSurface, onClosed: () => { - store.closeCredentialEditor(options.actions); + store.onWindowClosed(options.actions); options.onClosed(); }, }); diff --git a/app/apps/evenhub/store-layer.ts b/app/apps/evenhub/store-layer.ts index 5196d041..103a0a83 100644 --- a/app/apps/evenhub/store-layer.ts +++ b/app/apps/evenhub/store-layer.ts @@ -18,9 +18,13 @@ import { type EvenHubStoreApp, } from "./even-api"; import { - clearEvenHubPassword, - evenHubEmailSetting, - evenHubPasswordSetting, + clearEvenHubLoginForm, + clearEvenHubSession, + clearTransientEvenHubSession, + evenHubLoginEmailSetting, + evenHubLoginPasswordSetting, + evenHubRememberMeSetting, + resetEvenHubLoginForm, } from "./credentials"; import { EvenHubStoreDetailLayer } from "./store-detail-layer"; import { lineStep } from "../../ui/metrics"; @@ -49,8 +53,11 @@ export class EvenHubStoreLayer implements Layer { private showingLogin = !isEvenHubStoreConfigured(); private status = this.showingLogin ? "Sign in to browse public apps." : ""; private credentialEditorOpen = false; + private closed = false; - constructor(private readonly options: EvenHubStoreLayerOptions) {} + constructor(private readonly options: EvenHubStoreLayerOptions) { + if (this.showingLogin) resetEvenHubLoginForm(); + } paint(ctx: LayerContext): GrayImage { if (!this.started) { @@ -169,8 +176,7 @@ export class EvenHubStoreLayer implements Layer { label: "Log Out", onSelect: (ctx) => { ctx.stack.pop(); - clearEvenHubPassword(); - evenHubApi.clearSession(); + clearEvenHubSession(); this.enterLogin(ctx, "Signed out."); }, }, @@ -183,9 +189,14 @@ export class EvenHubStoreLayer implements Layer { void actions.endTextSettingEdit(); } + onWindowClosed(actions: Pick): void { + this.closed = true; + this.closeCredentialEditor(actions); + clearTransientEvenHubSession(); + } + private async reload(ctx: LayerContext): Promise { if (this.loading) return; - evenHubApi.clearSession(); this.apps = []; this.total = 0; this.nextPage = 1; @@ -227,11 +238,13 @@ export class EvenHubStoreLayer implements Layer { } private enterLogin(ctx: LayerContext, status = "Sign in to browse public apps."): void { + const wasShowingLogin = this.showingLogin; this.showingLogin = true; this.loading = false; this.apps = []; this.total = 0; this.status = status; + if (!wasShowingLogin) resetEvenHubLoginForm(); this.openCredentialEditor(ctx); ctx.actions.requestRender(); } @@ -240,22 +253,48 @@ export class EvenHubStoreLayer implements Layer { if (this.credentialEditorOpen) return; this.credentialEditorOpen = true; void ctx.actions.startTextSettingsEdit( - [evenHubEmailSetting, evenHubPasswordSetting], + [evenHubLoginEmailSetting, evenHubLoginPasswordSetting], "Sign in to EvenHub", () => { this.credentialEditorOpen = false; void this.submitCredentials(ctx); }, + { setting: evenHubRememberMeSetting, label: "Remember me" }, ); } private async submitCredentials(ctx: LayerContext): Promise { - if (!isEvenHubStoreConfigured()) { + const email = evenHubLoginEmailSetting.get(); + const password = evenHubLoginPasswordSetting.get(); + if (!email.trim() || !password) { this.enterLogin(ctx, "Email and password are required."); return; } - this.showingLogin = false; - await this.reload(ctx); + this.loading = true; + this.status = "Signing in..."; + ctx.actions.requestRender(); + try { + await evenHubApi.signIn(email, password, evenHubRememberMeSetting.get()); + if (this.closed) { + clearTransientEvenHubSession(); + return; + } + this.showingLogin = false; + clearEvenHubLoginForm(); + this.loading = false; + await this.reload(ctx); + } catch (error) { + if (this.closed) return; + const message = cleanError(error); + this.options.appendLog(`evenhub store login failed: ${message}`); + this.status = `Login failed: ${message}`; + evenHubLoginPasswordSetting.set(""); + this.openCredentialEditor(ctx); + } finally { + evenHubLoginPasswordSetting.set(""); + this.loading = false; + if (!this.closed) ctx.actions.requestRender(); + } } } diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 26735a88..272bb3f9 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -34,7 +34,7 @@ import { type AppContext, type AppDefinition, type AppLaunchParams, type TextEdi import { type InProcessAppOptions, type InProcessWindow } from "../ui/shell/in-process-window"; import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-apps-persistence"; import { appViewportRect, type WindowHeightMode } from "../ui/shell/geometry"; -import { type LayerActions } from "../ui/layers"; +import { type LayerActions, type TextSettingsEditToggle } from "../ui/layers"; import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings"; import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization"; import { @@ -66,6 +66,9 @@ export type DashboardSnapshot = { secondaryTextSettingTitle: string; secondaryTextSettingValue: string; secondaryTextSettingInputKind: "text" | "email" | "password"; + activeTextEditorToggleLabel: string; + activeTextEditorToggleValue: boolean; + activeTextEditorToggleVisible: boolean; evenAppConflictMessage: string; evenAppConflictWarningVisible: boolean; firmwareWarningMessage: string; @@ -152,6 +155,7 @@ class DashboardController { private activeTextSettings: ConfigSettingString[] = []; private activeTextEditorTitle = ""; private activeTextEditorOnFinish: (() => void) | null = null; + private activeTextEditorToggle: TextSettingsEditToggle | null = null; private evenNotificationActive = false; private evenAppConflictMessage = ""; private firmwareWarningMessage = ""; @@ -232,7 +236,8 @@ class DashboardController { settings: readonly ConfigSettingString[], title: string, onFinish?: () => void, - ) => this.startTextSettingsEdit(settings, title, onFinish), + toggle?: TextSettingsEditToggle, + ) => this.startTextSettingsEdit(settings, title, onFinish, toggle), endTextSettingEdit: () => this.endTextSettingEdit(), startVoiceCapture: () => this.startVoiceCapture(), stopVoiceCapture: () => this.stopVoiceCapture(), @@ -733,6 +738,9 @@ class DashboardController { secondaryTextSettingTitle: secondaryTextSetting?.editorTitle ?? "", secondaryTextSettingValue: secondaryTextSetting?.get() ?? "", secondaryTextSettingInputKind: secondaryTextSetting?.inputKind ?? "text", + activeTextEditorToggleLabel: this.activeTextEditorToggle?.label ?? "", + activeTextEditorToggleValue: this.activeTextEditorToggle?.setting.get() ?? false, + activeTextEditorToggleVisible: this.activeTextEditorToggle !== null, evenAppConflictMessage: this.evenAppConflictMessage, evenAppConflictWarningVisible: this.evenAppConflictMessage.length > 0, firmwareWarningMessage: this.firmwareWarningMessage, @@ -827,6 +835,12 @@ class DashboardController { this.previewOrRenderAfterTextSettingChange(); } + setActiveTextEditorToggleValue(value: boolean): void { + if (!this.activeTextEditorToggle || this.activeTextEditorToggle.setting.get() === value) return; + this.activeTextEditorToggle.setting.set(value); + this.emit(); + } + async connect(): Promise { if (this.phase !== "disconnected") return; // Connecting is the explicit way out of the manual-disconnected state. @@ -1291,10 +1305,12 @@ class DashboardController { settings: readonly ConfigSettingString[], title: string, onFinish?: () => void, + toggle?: TextSettingsEditToggle, ): void { this.activeTextSettings = Array.from(settings.slice(0, 2)); this.activeTextEditorTitle = title; this.activeTextEditorOnFinish = onFinish ?? null; + this.activeTextEditorToggle = toggle ?? null; this.emit(); } @@ -1352,6 +1368,7 @@ class DashboardController { this.activeTextSettings = []; this.activeTextEditorTitle = ""; this.activeTextEditorOnFinish = null; + this.activeTextEditorToggle = null; this.emit(); if (finishedSettings.includes(nightscoutSiteUrlSetting) || finishedSettings.includes(nightscoutApiTokenSetting)) { void this.refreshNightscoutAfterSettingsChange(); diff --git a/app/phone-ui/main-page.xml b/app/phone-ui/main-page.xml index 98f51b4a..6f270dd9 100644 --- a/app/phone-ui/main-page.xml +++ b/app/phone-ui/main-page.xml @@ -130,6 +130,16 @@ secure="{{ secondaryTextSettingSecure }}" returnKeyType="done" /> + + diff --git a/app/phone-ui/main-view-model.ts b/app/phone-ui/main-view-model.ts index 049c7421..b6716c92 100644 --- a/app/phone-ui/main-view-model.ts +++ b/app/phone-ui/main-view-model.ts @@ -23,6 +23,9 @@ export class MainViewModel extends Observable { private _secondaryTextSettingTitle = ""; private _secondaryTextSettingValue = ""; private _secondaryTextSettingInputKind: "text" | "email" | "password" = "text"; + private _activeTextEditorToggleLabel = ""; + private _activeTextEditorToggleValue = false; + private _activeTextEditorToggleVisible = false; private _evenAppConflictMessage = ""; private _evenAppConflictWarningVisible = false; private _firmwareWarningMessage = ""; @@ -49,6 +52,9 @@ export class MainViewModel extends Observable { this.secondaryTextSettingTitle = snapshot.secondaryTextSettingTitle; this.secondaryTextSettingValue = snapshot.secondaryTextSettingValue; this.secondaryTextSettingInputKind = snapshot.secondaryTextSettingInputKind; + this.activeTextEditorToggleLabel = snapshot.activeTextEditorToggleLabel; + this.activeTextEditorToggleValue = snapshot.activeTextEditorToggleValue; + this.activeTextEditorToggleVisible = snapshot.activeTextEditorToggleVisible; this.evenAppConflictMessage = snapshot.evenAppConflictMessage; this.evenAppConflictWarningVisible = snapshot.evenAppConflictWarningVisible; this.firmwareWarningMessage = snapshot.firmwareWarningMessage; @@ -315,6 +321,43 @@ export class MainViewModel extends Observable { return this.hasSecondaryTextSetting ? "next" : "done"; } + get activeTextEditorToggleLabel(): string { + return this._activeTextEditorToggleLabel; + } + + set activeTextEditorToggleLabel(value: string) { + if (this._activeTextEditorToggleLabel !== value) { + this._activeTextEditorToggleLabel = value; + this.notifyPropertyChange("activeTextEditorToggleLabel", value); + } + } + + get activeTextEditorToggleValue(): boolean { + return this._activeTextEditorToggleValue; + } + + set activeTextEditorToggleValue(value: boolean) { + if (this._activeTextEditorToggleValue !== value) { + this._activeTextEditorToggleValue = value; + this.notifyPropertyChange("activeTextEditorToggleValue", value); + } + } + + get activeTextEditorToggleVisible(): boolean { + return this._activeTextEditorToggleVisible; + } + + set activeTextEditorToggleVisible(value: boolean) { + if (this._activeTextEditorToggleVisible !== value) { + this._activeTextEditorToggleVisible = value; + this.notifyPropertyChange("activeTextEditorToggleVisibility", this.activeTextEditorToggleVisibility); + } + } + + get activeTextEditorToggleVisibility(): "visible" | "collapse" { + return this._activeTextEditorToggleVisible ? "visible" : "collapse"; + } + get isTextSettingEditorActive(): boolean { return this._activeTextSettingId !== null; } @@ -573,6 +616,12 @@ export class MainViewModel extends Observable { dashboardController.finishActiveTextSettingEdit(); } + onTextSettingToggleChange(args: { value?: boolean; object?: { checked?: boolean } }): void { + dashboardController.setActiveTextEditorToggleValue( + args.object?.checked ?? args.value ?? false, + ); + } + onOpenEvenAppSettingsTap(): void { dashboardController.openEvenAppSettings(); } diff --git a/app/ui/layers.ts b/app/ui/layers.ts index 7dc658a1..981d6ce6 100644 --- a/app/ui/layers.ts +++ b/app/ui/layers.ts @@ -1,7 +1,12 @@ import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image"; import { type Plane } from "../graphics/plane"; import { spanCurrent } from "../native/frame-timings"; -import { type ConfigSettingString } from "./dashboard-settings"; +import { type ConfigSettingBoolean, type ConfigSettingString } from "./dashboard-settings"; + +export type TextSettingsEditToggle = { + setting: ConfigSettingBoolean; + label: string; +}; export type DashboardInputEvent = | { type: "click"; source: "ring" | "left-arm" | "right-arm" } @@ -34,6 +39,7 @@ export type LayerActions = { settings: readonly ConfigSettingString[], title: string, onFinish?: () => void, + toggle?: TextSettingsEditToggle, ) => Promise | void; endTextSettingEdit: () => Promise | void; /**