AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: add login device metadata
tianma-ifdf99373a522e
diff --git a/apps/api/src/auth-session-devices.ts b/apps/api/src/auth-session-devices.tsindex 5dd6b845..75d465d4 100644--- a/apps/api/src/auth-session-devices.ts+++ b/apps/api/src/auth-session-devices.ts@@ -4,6 +4,10 @@ export type LoginDeviceSessionRow = {id: string;device_id: string | null;user_agent: string | null;+ device_label: string | null;+ ip_address: string | null;+ ip_country: string | null;+ ip_region: string | null;expires_at: string;created_at: string;last_seen_at: string | null;@@ -42,6 +46,10 @@ export const groupLoginDeviceSessions = (return [...grouped.values()].map(({ representative, createdAt, lastSeenAt }) => ({id: representative.id,userAgent: representative.user_agent,+ label: representative.device_label,+ ipAddress: representative.ip_address,+ ipCountry: representative.ip_country,+ ipRegion: representative.ip_region,isCurrent: representative.id === currentSessionId,createdAt,lastSeenAt,diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 0beec336..faa59910 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -8,6 +8,7 @@ import {ChangePasswordSchema,DeleteMemosSchema,LoginSchema,+ LoginDeviceSessionUpdateSchema,markdownToDoc,isSuspiciousMemoOverwrite,isMemoEditBindingValid,@@ -508,7 +509,7 @@ app.get("/api/v1/auth/sessions", async (c) => {const now = isoNow();const rows = await c.env.storage.db.prepare(- `SELECT id, device_id, user_agent, expires_at, created_at, last_seen_at+ `SELECT id, device_id, user_agent, device_label, ip_address, ip_country, ip_region, expires_at, created_at, last_seen_atFROM sessionsWHERE user_id = ?AND revoked_at IS NULL@@ -524,6 +525,40 @@ app.get("/api/v1/auth/sessions", async (c) => {});});+app.patch("/api/v1/auth/sessions/:sessionId", zValidator("json", LoginDeviceSessionUpdateSchema), async (c) => {+ const auth = await authenticateRequest(c, true);++ if (!auth || auth.kind !== "user" || !auth.actorId || !auth.sessionId) {+ return unauthorized(c, "An interactive user session is required.");+ }++ const sessionId = c.req.param("sessionId");+ const input = c.req.valid("json");+ const now = isoNow();+ const session = await c.env.storage.db.prepare(+ `SELECT id, device_id FROM sessions+ WHERE id = ? AND user_id = ? AND revoked_at IS NULL AND expires_at > ?`+ ).bind(sessionId, auth.actorId, now).first<{ id: string; device_id: string | null }>();++ if (!session) return notFound(c, "Login session not found.");++ const statement = session.device_id+ ? c.env.storage.db.prepare(+ `UPDATE sessions SET device_label = ?+ WHERE user_id = ? AND device_id = ? AND revoked_at IS NULL`+ ).bind(input.label || null, auth.actorId, session.device_id)+ : c.env.storage.db.prepare(`UPDATE sessions SET device_label = ? WHERE id = ?`).bind(input.label || null, session.id);++ await c.env.storage.db.batch([+ statement,+ auditStatement(c.env.storage.db, "user", auth.actorId, "auth.session_label_update", "session", session.id, {+ label: input.label || null,+ }),+ ]);++ return c.json({ ok: true });+});+app.delete("/api/v1/auth/sessions", async (c) => {const auth = await authenticateRequest(c, true);@@ -3960,6 +3995,9 @@ const createSession = async (c: AppContext, user: UserRow, requestedDeviceId?: sconst deviceId = resolveSessionDeviceId(requestedDeviceId, userAgent, id);const ip = c.req.header("CF-Connecting-IP");const ipHash = ip ? await sha256(ip) : null;+ const cf = c.req.raw.cf as { country?: string; region?: string } | undefined;+ const ipCountry = c.req.header("CF-IPCountry") ?? cf?.country ?? null;+ const ipRegion = cf?.region ?? null;await c.env.storage.db.batch([c.env.storage.db.prepare(@@ -3968,9 +4006,9 @@ const createSession = async (c: AppContext, user: UserRow, requestedDeviceId?: s).bind(now, user.id, deviceId),c.env.storage.db.prepare(`INSERT INTO sessions (- id, user_id, token_hash, device_id, user_agent, ip_hash, expires_at, created_at, last_seen_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`- ).bind(id, user.id, await sha256(token), deviceId, userAgent, ipHash, expiresAt, now, now),+ id, user_id, token_hash, device_id, user_agent, ip_hash, device_label, ip_address, ip_country, ip_region, expires_at, created_at, last_seen_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`+ ).bind(id, user.id, await sha256(token), deviceId, userAgent, ipHash, null, ip ?? null, ipCountry, ipRegion, expiresAt, now, now),]);return { id, token, maxAge };diff --git a/apps/web/src/components/settings/LoginDevicesCard.tsx b/apps/web/src/components/settings/LoginDevicesCard.tsxindex 3096bb68..697ae61b 100644--- a/apps/web/src/components/settings/LoginDevicesCard.tsx+++ b/apps/web/src/components/settings/LoginDevicesCard.tsx@@ -1,9 +1,10 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { Laptop, MonitorSmartphone, Smartphone, Tablet } from "lucide-react";+import { Check, Laptop, MonitorSmartphone, Pencil, Smartphone, Tablet, X } from "lucide-react";import { useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import { Input } from "@/components/ui/input";import { api } from "@/lib/api";import { LoginSessionRevokeDialog, type LoginSessionRevokeTarget } from "./LoginSessionRevokeDialog";@@ -69,6 +70,8 @@ export const LoginDevicesCard = ({ authRequired }: LoginDevicesCardProps) => {const { t, i18n } = useTranslation();const queryClient = useQueryClient();const [revokeTarget, setRevokeTarget] = useState<LoginSessionRevokeTarget | null>(null);+ const [editingSessionId, setEditingSessionId] = useState<string | null>(null);+ const [labelDraft, setLabelDraft] = useState("");const locale = i18n.resolvedLanguage ?? i18n.language;const sessionsQuery = useQuery({queryKey: ["auth", "sessions"],@@ -85,6 +88,14 @@ export const LoginDevicesCard = ({ authRequired }: LoginDevicesCardProps) => {await queryClient.invalidateQueries({ queryKey: ["auth", "sessions"] });},});+ const labelMutation = useMutation({+ mutationFn: ({ sessionId, label }: { sessionId: string; label: string | null }) =>+ api.updateLoginDeviceSession(sessionId, { label }),+ onSuccess: async () => {+ setEditingSessionId(null);+ await queryClient.invalidateQueries({ queryKey: ["auth", "sessions"] });+ },+ });if (!authRequired) return null;@@ -117,6 +128,8 @@ export const LoginDevicesCard = ({ authRequired }: LoginDevicesCardProps) => {const { deviceKind, os, browser } = describeUserAgent(session.userAgent);const DeviceIcon = getDeviceIcon(deviceKind);const details = [os, browser || t("loginDevices.unknownBrowser")].filter(Boolean).join(" · ");+ const location = [session.ipAddress, session.ipCountry, session.ipRegion].filter(Boolean).join(" · ");+ const isEditing = editingSessionId === session.id;return (<li key={session.id} className="flex gap-3 py-3 first:pt-0 last:pb-0">@@ -125,7 +138,22 @@ export const LoginDevicesCard = ({ authRequired }: LoginDevicesCardProps) => {</span><div className="min-w-0 flex-1"><div className="flex flex-wrap items-center gap-2">- <p className="text-sm font-semibold text-slate-800">{t(`loginDevices.${deviceKind}`)}</p>+ {isEditing ? (+ <Input+ autoFocus+ maxLength={80}+ className="h-8 w-48"+ value={labelDraft}+ placeholder={t("loginDevices.labelPlaceholder")}+ onChange={(event) => setLabelDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") labelMutation.mutate({ sessionId: session.id, label: labelDraft.trim() || null });+ if (event.key === "Escape") setEditingSessionId(null);+ }}+ />+ ) : (+ <p className="text-sm font-semibold text-slate-800">{session.label || t(`loginDevices.${deviceKind}`)}</p>+ )}{session.isCurrent ? (<span className="rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-semibold text-emerald-700">{t("loginDevices.current")}@@ -133,12 +161,35 @@ export const LoginDevicesCard = ({ authRequired }: LoginDevicesCardProps) => {) : null}</div><p className="mt-0.5 truncate text-xs text-slate-500" title={session.userAgent ?? undefined}>{details}</p>+ {location ? <p className="mt-0.5 truncate text-xs text-slate-500">{t("loginDevices.location", { location })}</p> : null}<p className="mt-1 text-xs text-slate-500">{t("loginDevices.lastSeen", { time: formatSessionTime(session.lastSeenAt, locale) })}<span aria-hidden="true"> · </span>{t("loginDevices.signedIn", { time: formatSessionTime(session.createdAt, locale) })}</p></div>+ <div className="flex shrink-0 items-start gap-1">+ {isEditing ? (+ <>+ <Button+ size="icon"+ variant="outline"+ aria-label={t("loginDevices.saveLabel")}+ disabled={labelMutation.isPending}+ onClick={() => labelMutation.mutate({ sessionId: session.id, label: labelDraft.trim() || null })}+ ><Check className="h-4 w-4" /></Button>+ <Button size="icon" variant="ghost" aria-label={t("loginDevices.cancelLabel")} onClick={() => setEditingSessionId(null)}>+ <X className="h-4 w-4" />+ </Button>+ </>+ ) : (+ <Button+ size="icon"+ variant="ghost"+ aria-label={t("loginDevices.editLabel")}+ onClick={() => { setEditingSessionId(session.id); setLabelDraft(session.label ?? ""); }}+ ><Pencil className="h-4 w-4" /></Button>+ )}{!session.isCurrent ? (<Buttonsize="sm"@@ -149,6 +200,7 @@ export const LoginDevicesCard = ({ authRequired }: LoginDevicesCardProps) => {{t("loginDevices.revokeDevice")}</Button>) : null}+ </div></li>);})}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 5f898149..0ef4b472 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -154,6 +154,12 @@ export const api = {revokeLoginDeviceSession: (sessionId: string) =>request<{ ok: true }>(`/api/v1/auth/sessions/${sessionId}`, { method: "DELETE" }),+ updateLoginDeviceSession: (sessionId: string, payload: { label: string | null }) =>+ request<{ ok: true }>(`/api/v1/auth/sessions/${sessionId}`, {+ method: "PATCH",+ body: JSON.stringify(payload),+ }),+revokeOtherLoginDeviceSessions: () =>request<{ ok: true }>("/api/v1/auth/sessions", { method: "DELETE" }),diff --git a/docs/openapi.json b/docs/openapi.jsonindex 31b78d8f..7e2015e2 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -129,6 +129,37 @@"$ref": "#/components/responses/Error"}}+ },+ "patch": {+ "summary": "Update a login device label",+ "parameters": [+ {+ "name": "sessionId",+ "in": "path",+ "required": true,+ "schema": { "type": "string" }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": { "label": { "type": ["string", "null"], "maxLength": 80 } },+ "required": ["label"]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Device label updated",+ "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Ok" } } }+ },+ "401": { "$ref": "#/components/responses/Error" },+ "404": { "$ref": "#/components/responses/Error" }+ }}},"/api/v1/auth/sessions/{sessionId}": {@@ -1396,12 +1427,16 @@"properties": {"id": { "type": "string" },"userAgent": { "type": ["string", "null"] },+ "label": { "type": ["string", "null"] },+ "ipAddress": { "type": ["string", "null"] },+ "ipCountry": { "type": ["string", "null"] },+ "ipRegion": { "type": ["string", "null"] },"isCurrent": { "type": "boolean" },"createdAt": { "type": "string", "format": "date-time" },"lastSeenAt": { "type": "string", "format": "date-time" },"expiresAt": { "type": "string", "format": "date-time" }},- "required": ["id", "userAgent", "isCurrent", "createdAt", "lastSeenAt", "expiresAt"]+ "required": ["id", "userAgent", "label", "ipAddress", "ipCountry", "ipRegion", "isCurrent", "createdAt", "lastSeenAt", "expiresAt"]},"AuthUser": {"type": "object",diff --git a/migrations/0019_auth_session_metadata.sql b/migrations/0019_auth_session_metadata.sqlnew file mode 100644index 00000000..2af1b1e1--- /dev/null+++ b/migrations/0019_auth_session_metadata.sql@@ -0,0 +1,4 @@+ALTER TABLE sessions ADD COLUMN device_label TEXT;+ALTER TABLE sessions ADD COLUMN ip_address TEXT;+ALTER TABLE sessions ADD COLUMN ip_country TEXT;+ALTER TABLE sessions ADD COLUMN ip_region TEXT;diff --git a/package.json b/package.jsonindex b92cec24..e4fa3cb0 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "edgeever",- "version": "1.6.6",+ "version": "1.6.7","private": true,"type": "module","workspaces": [diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex e292c338..9378b1a6 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -686,6 +686,11 @@ export const enUS = {desktop: "Computer",unknownDevice: "Unknown device",unknownBrowser: "Unknown browser",+ labelPlaceholder: "For example: Office computer",+ editLabel: "Edit device label",+ saveLabel: "Save device label",+ cancelLabel: "Cancel device label editing",+ location: "Location: {{location}}",lastSeen: "Last active: {{time}}",signedIn: "Signed in: {{time}}",revokeDevice: "Sign out device",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 29ea13e8..258fa294 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -686,6 +686,11 @@ export const zhCN = {desktop: "电脑",unknownDevice: "未知设备",unknownBrowser: "未知浏览器",+ labelPlaceholder: "例如:办公室电脑",+ editLabel: "编辑设备备注",+ saveLabel: "保存设备备注",+ cancelLabel: "取消编辑设备备注",+ location: "位置:{{location}}",lastSeen: "上次访问:{{time}}",signedIn: "登录时间:{{time}}",revokeDevice: "退出此设备",diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.tsindex d01c3e84..989abf7d 100644--- a/packages/shared/src/schemas.ts+++ b/packages/shared/src/schemas.ts@@ -80,6 +80,10 @@ export const LoginSchema = z.object({deviceId: z.string().trim().min(16).max(160).optional(),});+export const LoginDeviceSessionUpdateSchema = z.object({+ label: z.string().trim().max(80).nullable(),+});+export const ChangePasswordSchema = z.object({currentPassword: z.string().min(1).max(512),@@ -125,6 +129,7 @@ export type MoveMemosInput = z.infer<typeof MoveMemosSchema>;export type DeleteMemosInput = z.infer<typeof DeleteMemosSchema>;export type MergeMemosInput = z.infer<typeof MergeMemosSchema>;export type LoginInput = z.infer<typeof LoginSchema>;+export type LoginDeviceSessionUpdateInput = z.infer<typeof LoginDeviceSessionUpdateSchema>;export type ChangePasswordInput = z.infer<typeof ChangePasswordSchema>;export type UserCreateInput = z.infer<typeof UserCreateSchema>;export type UserUpdateInput = z.infer<typeof UserUpdateSchema>;diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex e7cdbd8f..fd4abdab 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -149,6 +149,10 @@ export type AuthSession = {export type LoginDeviceSession = {id: string;userAgent: string | null;+ label: string | null;+ ipAddress: string | null;+ ipCountry: string | null;+ ipRegion: string | null;isCurrent: boolean;createdAt: string;lastSeenAt: string;diff --git a/tests/auth-session-devices.test.ts b/tests/auth-session-devices.test.tsindex f7b35088..d2b6f36c 100644--- a/tests/auth-session-devices.test.ts+++ b/tests/auth-session-devices.test.ts@@ -26,6 +26,10 @@ describe("login device sessions", () => {id: "sess_latest",device_id: "mobile-installation-1",user_agent: "EdgeEver/1.4.0",+ device_label: "手机",+ ip_address: "203.0.113.10",+ ip_country: "CN",+ ip_region: "Guangdong",created_at: "2026-07-20T00:00:00.000Z",last_seen_at: "2026-07-22T04:00:00.000Z",expires_at: "2027-07-20T00:00:00.000Z",@@ -34,6 +38,10 @@ describe("login device sessions", () => {id: "sess_current",device_id: "mobile-installation-1",user_agent: "EdgeEver/1.4.0",+ device_label: "手机",+ ip_address: "203.0.113.11",+ ip_country: "CN",+ ip_region: "Guangdong",created_at: "2026-07-18T00:00:00.000Z",last_seen_at: "2026-07-21T04:00:00.000Z",expires_at: "2027-07-18T00:00:00.000Z",@@ -44,6 +52,10 @@ describe("login device sessions", () => {{id: "sess_current",userAgent: "EdgeEver/1.4.0",+ label: "手机",+ ipAddress: "203.0.113.11",+ ipCountry: "CN",+ ipRegion: "Guangdong",isCurrent: true,createdAt: "2026-07-18T00:00:00.000Z",lastSeenAt: "2026-07-22T04:00:00.000Z",