EvenHub app stores login token instead of password

This commit is contained in:
James Babcock committed 2026-08-30 00:35:55 -07:00
1 parent cc4b69fb80
commit 6c46f2f7cc
8 files changed
+302 -49

No files matched your search

+144 -12
View File
@@ -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<typeof ConfigSettingString>[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<typeof ConfigSettingBoolean>[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, "");
}
+22 -22
View File
@@ -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<string> | null = null;
async listApps(page = 1, category = ""): Promise<EvenHubStorePage> {
@@ -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<void> {
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<string, string | number>; body?: Record<string, unknown> } = {},
): Promise<unknown> {
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<string> {
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<string> {
private async login(email: string, password: string, remember: boolean): Promise<string> {
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;
+1 -1
View File
@@ -73,7 +73,7 @@ const evenhubApp: AppDefinition = {
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
store.closeCredentialEditor(options.actions);
store.onWindowClosed(options.actions);
options.onClosed();
},
});
+50 -11
View File
@@ -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<LayerActions, "endTextSettingEdit">): void {
this.closed = true;
this.closeCredentialEditor(actions);
clearTransientEvenHubSession();
}
private async reload(ctx: LayerContext): Promise<void> {
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<void> {
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();
}
}
}