mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(device-pairing): pair phones and browsers with a QR code
Settings -> Account gets "Connect a device", a paired-devices list, and a remote access headers editor, so the mobile app and other browsers can sign in without typing a password and pass a reverse proxy such as Cloudflare Access. - one-time pairing codes (3 min TTL) minted by a Better Auth plugin and redeemed into a new session that records the device name - POST /api/device-pairing/links builds the ocm://link app link with the stored headers as h= parameters and a browser /pair link; plain-HTTP and loopback origins are blocked or warned about - remote access headers are stored encrypted, returned by name only, and validated (8 headers, 512-char values, 1800 encoded characters, reserved transport names blocked); a Cloudflare Access service token preset fills CF-Access-Client-Id and CF-Access-Client-Secret - login offers "Sign in with QR code" and /pair redeems a scanned code, returning to the login redirect target - revoking a device deletes its session, closes its live connections and removes its push subscriptions; the current session cannot be revoked
This commit is contained in:
1 parent
5b0e629182
commit
f8e4cfe136
79 files changed
+5398
-110
No files matched your search
@@ -176,6 +176,17 @@ export const getTrustedOrigins = (): string[] =>
|
||||
.map((origin) => origin.trim())
|
||||
.filter((origin) => origin.length > 0)
|
||||
|
||||
/** Reports whether a request Origin is one of the configured trusted origins. */
|
||||
export const isTrustedOrigin = (
|
||||
origin: string | undefined,
|
||||
options: { requireOrigin?: boolean } = {},
|
||||
trustedOrigins: readonly string[] = getTrustedOrigins(),
|
||||
): boolean => {
|
||||
if (!origin) return !(options.requireOrigin ?? false)
|
||||
if (origin === 'null') return false
|
||||
return trustedOrigins.includes(origin)
|
||||
}
|
||||
|
||||
export const getApiUrl = (port: number = ENV.SERVER.PORT): string => {
|
||||
const host = ENV.SERVER.HOST
|
||||
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { z } from "zod";
|
||||
import { trimUrlTrailingSlashes } from "../utils/url";
|
||||
|
||||
export const REMOTE_ACCESS_HEADER_MAX_COUNT = 8;
|
||||
export const REMOTE_ACCESS_HEADER_VALUE_MAX_LENGTH = 512;
|
||||
export const REMOTE_ACCESS_HEADER_NAME_MAX_LENGTH = 128;
|
||||
export const REMOTE_ACCESS_HEADERS_MAX_ENCODED_LENGTH = 1800;
|
||||
export const CLOUDFLARE_ACCESS_HEADER_NAMES = ["CF-Access-Client-Id", "CF-Access-Client-Secret"] as const;
|
||||
export const DEVICE_PAIRING_PATH = "/pair";
|
||||
export const DEVICE_PAIRING_CODE_TTL_SECONDS = 180;
|
||||
|
||||
export const DEVICE_PAIRING_ERROR_CODES = {
|
||||
PAIRING_CODE_INVALID: "PAIRING_CODE_INVALID",
|
||||
DEVICE_NOT_FOUND: "DEVICE_NOT_FOUND",
|
||||
CANNOT_REVOKE_CURRENT_SESSION: "CANNOT_REVOKE_CURRENT_SESSION",
|
||||
} as const;
|
||||
|
||||
export const PAIRING_CODE_INVALID_MESSAGE =
|
||||
"This pairing code has expired or was already used. Show a new QR code and scan again.";
|
||||
|
||||
const HTTP_HEADER_NAME_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
||||
const BLOCKED_REMOTE_ACCESS_HEADER_NAMES = new Set([
|
||||
"cookie",
|
||||
"set-cookie",
|
||||
"host",
|
||||
"origin",
|
||||
"content-length",
|
||||
"content-type",
|
||||
"connection",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
"te",
|
||||
"keep-alive",
|
||||
"x-forwarded-for",
|
||||
"x-forwarded-host",
|
||||
"x-forwarded-proto",
|
||||
"forwarded",
|
||||
"x-real-ip",
|
||||
"cf-connecting-ip",
|
||||
]);
|
||||
|
||||
/** Reports whether a header name is reserved by the transport or uses the proxy- prefix. */
|
||||
export function isBlockedRemoteAccessHeaderName(name: string): boolean {
|
||||
const normalized = name.trim().toLowerCase();
|
||||
return BLOCKED_REMOTE_ACCESS_HEADER_NAMES.has(normalized) || normalized.startsWith("proxy-");
|
||||
}
|
||||
|
||||
export const RemoteAccessHeaderNameSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(REMOTE_ACCESS_HEADER_NAME_MAX_LENGTH)
|
||||
.regex(HTTP_HEADER_NAME_TOKEN, "Header names must be valid HTTP tokens")
|
||||
.refine((name) => !isBlockedRemoteAccessHeaderName(name), "This header name is reserved");
|
||||
|
||||
const remoteAccessHeaderValueRules = z
|
||||
.string()
|
||||
.refine((value) => !/[\r\n\0]/.test(value), "Header values must not contain line breaks")
|
||||
.trim()
|
||||
.max(REMOTE_ACCESS_HEADER_VALUE_MAX_LENGTH);
|
||||
|
||||
export const RemoteAccessHeaderValueSchema = remoteAccessHeaderValueRules.min(1);
|
||||
|
||||
export const RemoteAccessHeaderDraftValueSchema = remoteAccessHeaderValueRules;
|
||||
|
||||
export const RemoteAccessHeaderSchema = z.object({
|
||||
name: RemoteAccessHeaderNameSchema,
|
||||
value: RemoteAccessHeaderValueSchema,
|
||||
});
|
||||
|
||||
export const RemoteAccessHeaderListSchema = z
|
||||
.array(RemoteAccessHeaderSchema)
|
||||
.max(REMOTE_ACCESS_HEADER_MAX_COUNT)
|
||||
.refine(
|
||||
(headers) => new Set(headers.map((header) => header.name.toLowerCase())).size === headers.length,
|
||||
"Header names must be unique",
|
||||
)
|
||||
.refine(
|
||||
(headers) => encodedRemoteAccessHeadersLength(headers) <= REMOTE_ACCESS_HEADERS_MAX_ENCODED_LENGTH,
|
||||
`Remote access headers are too long to fit in a QR code (limit ${REMOTE_ACCESS_HEADERS_MAX_ENCODED_LENGTH} encoded characters)`,
|
||||
);
|
||||
|
||||
/** Serializes a remote-access header into the `Name:Value` form carried by the link `h` parameter. */
|
||||
export function formatRemoteAccessHeaderParam(header: RemoteAccessHeader): string {
|
||||
return `${header.name}:${header.value}`;
|
||||
}
|
||||
|
||||
function encodedRemoteAccessHeadersLength(headers: RemoteAccessHeader[]): number {
|
||||
const params = new URLSearchParams();
|
||||
for (const header of headers) params.append("h", formatRemoteAccessHeaderParam(header));
|
||||
return params.toString().length;
|
||||
}
|
||||
|
||||
export const RemoteAccessHeaderSummarySchema = z.object({
|
||||
name: z.string(),
|
||||
hasValue: z.boolean(),
|
||||
});
|
||||
|
||||
export const RemoteAccessHeadersResponseSchema = z.object({
|
||||
headers: z.array(RemoteAccessHeaderSummarySchema),
|
||||
unreadable: z.boolean(),
|
||||
});
|
||||
|
||||
export const ReplaceRemoteAccessHeadersRequestSchema = z.object({
|
||||
headers: z
|
||||
.array(
|
||||
z.object({
|
||||
name: RemoteAccessHeaderNameSchema,
|
||||
value: RemoteAccessHeaderDraftValueSchema.optional(),
|
||||
}),
|
||||
)
|
||||
.max(REMOTE_ACCESS_HEADER_MAX_COUNT),
|
||||
});
|
||||
|
||||
export const DevicePairingCodeSchema = z.string().min(16).max(256);
|
||||
export const DeviceNameSchema = z.string().trim().min(1).max(80);
|
||||
|
||||
export const RedeemDevicePairingCodeRequestSchema = z.object({
|
||||
code: DevicePairingCodeSchema,
|
||||
deviceName: DeviceNameSchema.optional(),
|
||||
});
|
||||
|
||||
export const RedeemDevicePairingCodeResponseSchema = z.object({
|
||||
user: z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
email: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const AppLinkBlockedReasonSchema = z.enum(["insecure-origin", "loopback"]);
|
||||
export const DevicePairingLinkWarningSchema = z.enum(["plain-http", "loopback", "headers-unreadable"]);
|
||||
|
||||
export const CreateDevicePairingLinksRequestSchema = z.object({
|
||||
name: z.string().trim().min(1).max(100).optional(),
|
||||
});
|
||||
|
||||
export const DevicePairingLinksResponseSchema = z.object({
|
||||
appLink: z.string().nullable(),
|
||||
appLinkBlockedReason: AppLinkBlockedReasonSchema.nullable(),
|
||||
browserLink: z.string(),
|
||||
expiresAt: z.string(),
|
||||
headerNames: z.array(z.string()),
|
||||
warnings: z.array(DevicePairingLinkWarningSchema),
|
||||
});
|
||||
|
||||
export const PairedDeviceSchema = z.object({
|
||||
id: z.string(),
|
||||
deviceName: z.string().nullable(),
|
||||
userAgent: z.string().nullable(),
|
||||
ipAddress: z.string().nullable(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
isCurrent: z.boolean(),
|
||||
});
|
||||
|
||||
export const PairedDevicesResponseSchema = z.object({
|
||||
devices: z.array(PairedDeviceSchema),
|
||||
});
|
||||
|
||||
export type RemoteAccessHeader = z.infer<typeof RemoteAccessHeaderSchema>;
|
||||
export type RemoteAccessHeaderDraftValue = z.infer<typeof RemoteAccessHeaderDraftValueSchema>;
|
||||
export type RemoteAccessHeaderList = z.infer<typeof RemoteAccessHeaderListSchema>;
|
||||
export type RemoteAccessHeaderSummary = z.infer<typeof RemoteAccessHeaderSummarySchema>;
|
||||
export type RemoteAccessHeadersResponse = z.infer<typeof RemoteAccessHeadersResponseSchema>;
|
||||
export type ReplaceRemoteAccessHeadersRequest = z.infer<typeof ReplaceRemoteAccessHeadersRequestSchema>;
|
||||
export type DevicePairingCode = z.infer<typeof DevicePairingCodeSchema>;
|
||||
export type DeviceName = z.infer<typeof DeviceNameSchema>;
|
||||
export type RedeemDevicePairingCodeRequest = z.infer<typeof RedeemDevicePairingCodeRequestSchema>;
|
||||
export type RedeemDevicePairingCodeResponse = z.infer<typeof RedeemDevicePairingCodeResponseSchema>;
|
||||
export type AppLinkBlockedReason = z.infer<typeof AppLinkBlockedReasonSchema>;
|
||||
export type DevicePairingLinkWarning = z.infer<typeof DevicePairingLinkWarningSchema>;
|
||||
export type CreateDevicePairingLinksRequest = z.infer<typeof CreateDevicePairingLinksRequestSchema>;
|
||||
export type DevicePairingLinksResponse = z.infer<typeof DevicePairingLinksResponseSchema>;
|
||||
export type PairedDevice = z.infer<typeof PairedDeviceSchema>;
|
||||
export type PairedDevicesResponse = z.infer<typeof PairedDevicesResponseSchema>;
|
||||
export type DevicePairingErrorCode =
|
||||
(typeof DEVICE_PAIRING_ERROR_CODES)[keyof typeof DEVICE_PAIRING_ERROR_CODES];
|
||||
|
||||
/** Builds the browser pairing link whose code stays in the URL fragment. */
|
||||
export function buildManagerBrowserPairingLink(origin: string, code: string): string {
|
||||
return `${trimUrlTrailingSlashes(origin)}${DEVICE_PAIRING_PATH}#c=${encodeURIComponent(code)}`;
|
||||
}
|
||||
|
||||
/** Reads a pairing code from a URL fragment, or null when the fragment holds no valid code. */
|
||||
export function readPairingCodeFromHash(hash: string): string | null {
|
||||
const code = new URLSearchParams(hash.replace(/^#/, "")).get("c");
|
||||
const parsed = DevicePairingCodeSchema.safeParse(code);
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
/** Parses a browser pairing link into its origin and code, or null when the text is not one. */
|
||||
export function parseManagerBrowserPairingLink(text: string): { origin: string; code: string } | null {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(text.trim());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
||||
if (url.pathname !== DEVICE_PAIRING_PATH) return null;
|
||||
const code = readPairingCodeFromHash(url.hash);
|
||||
return code === null ? null : { origin: url.origin, code };
|
||||
}
|
||||
@@ -25,3 +25,4 @@ export * from './preview'
|
||||
export * from './change-walkthroughs'
|
||||
export * from './opencode-servers'
|
||||
export * from './secrets'
|
||||
export * from './device-pairing'
|
||||
@@ -1,4 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
DevicePairingCodeSchema,
|
||||
RemoteAccessHeaderListSchema,
|
||||
formatRemoteAccessHeaderParam,
|
||||
} from "./device-pairing";
|
||||
|
||||
export const LOCAL_OPENCODE_SERVER_ID = "local";
|
||||
export const OPENCODE_SERVER_USERNAME = "opencode";
|
||||
@@ -77,6 +82,14 @@ export const OpenCodeServerLinkSchema = z.object({
|
||||
pairing: OpenCodeServerPairingSchema,
|
||||
});
|
||||
|
||||
export const ManagerAppLinkSchema = z.object({
|
||||
kind: z.literal("manager"),
|
||||
name: z.string().trim().min(1).max(100),
|
||||
baseUrl: HttpUrlSchema,
|
||||
code: DevicePairingCodeSchema,
|
||||
headers: RemoteAccessHeaderListSchema,
|
||||
});
|
||||
|
||||
export type OpenCodeServer = z.infer<typeof OpenCodeServerSchema>;
|
||||
export type OpenCodeServerPairing = z.infer<typeof OpenCodeServerPairingSchema>;
|
||||
export type CreateOpenCodeServerRequest = z.input<typeof CreateOpenCodeServerRequestSchema>;
|
||||
@@ -85,33 +98,42 @@ export type TestOpenCodeServerRequest = z.input<typeof TestOpenCodeServerRequest
|
||||
export type OpenCodeServerTestResult = z.infer<typeof OpenCodeServerTestResultSchema>;
|
||||
export type OpenCodeServerStatus = z.infer<typeof OpenCodeServerStatusSchema>;
|
||||
export type OpenCodeServerLink = z.infer<typeof OpenCodeServerLinkSchema>;
|
||||
export type ManagerAppLink = z.infer<typeof ManagerAppLinkSchema>;
|
||||
|
||||
/** Builds the `ocm://link` URL encoded into a pairing QR code. */
|
||||
export function buildOpenCodeServerLink(link: OpenCodeServerLink): string {
|
||||
const params = new URLSearchParams({
|
||||
v: OPENCODE_SERVER_LINK_VERSION,
|
||||
kind: link.kind,
|
||||
name: link.name,
|
||||
url: link.baseUrl,
|
||||
pair: link.pairing.pairUrl,
|
||||
code: link.pairing.code,
|
||||
});
|
||||
return `${OPENCODE_SERVER_LINK_PROTOCOL}//link?${params.toString()}`;
|
||||
const params = buildLinkParams(link);
|
||||
params.set("pair", link.pairing.pairUrl);
|
||||
params.set("code", link.pairing.code);
|
||||
return buildLinkUrl(params);
|
||||
}
|
||||
|
||||
/** Parses an `ocm://link` URL from a QR code or pasted text; returns null when it is not a valid link. */
|
||||
export function parseOpenCodeServerLink(text: string): OpenCodeServerLink | null {
|
||||
const url = parseOpenCodeServerLinkUrl(text);
|
||||
if (!url) return null;
|
||||
if (url.searchParams.get("v") !== OPENCODE_SERVER_LINK_VERSION) return null;
|
||||
|
||||
const parsed = OpenCodeServerLinkSchema.safeParse({
|
||||
kind: url.searchParams.get("kind"),
|
||||
name: url.searchParams.get("name"),
|
||||
baseUrl: url.searchParams.get("url"),
|
||||
return readLink(OpenCodeServerLinkSchema, text, (url) => ({
|
||||
pairing: { pairUrl: url.searchParams.get("pair"), code: url.searchParams.get("code") },
|
||||
}));
|
||||
}
|
||||
|
||||
/** Builds the `ocm://link` URL for a manager app pairing QR code, including remote-access headers. */
|
||||
export function buildManagerAppLink(link: ManagerAppLink): string {
|
||||
const params = buildLinkParams(link);
|
||||
params.set("code", link.code);
|
||||
for (const header of link.headers) params.append("h", formatRemoteAccessHeaderParam(header));
|
||||
return buildLinkUrl(params);
|
||||
}
|
||||
|
||||
/** Parses an `ocm://link` manager app link; returns null when it is not a valid manager link. */
|
||||
export function parseManagerAppLink(text: string): ManagerAppLink | null {
|
||||
return readLink(ManagerAppLinkSchema, text, (url) => {
|
||||
const headers: Array<{ name: string; value: string }> = [];
|
||||
for (const raw of url.searchParams.getAll("h")) {
|
||||
const separator = raw.indexOf(":");
|
||||
if (separator < 0) return null;
|
||||
headers.push({ name: raw.slice(0, separator), value: raw.slice(separator + 1) });
|
||||
}
|
||||
return { headers };
|
||||
});
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
/** Reads the `v` parameter of an `ocm://link` URL, or null when the text is not an `ocm://link` URL. */
|
||||
@@ -130,6 +152,53 @@ function parseOpenCodeServerLinkUrl(text: string): URL | null {
|
||||
return url;
|
||||
}
|
||||
|
||||
type LinkQueryFields = {
|
||||
kind: string | null;
|
||||
name: string | null;
|
||||
baseUrl: string | null;
|
||||
code: string | null;
|
||||
};
|
||||
|
||||
function buildLinkParams(link: { kind: string; name: string; baseUrl: string }): URLSearchParams {
|
||||
return new URLSearchParams({
|
||||
v: OPENCODE_SERVER_LINK_VERSION,
|
||||
kind: link.kind,
|
||||
name: link.name,
|
||||
url: link.baseUrl,
|
||||
});
|
||||
}
|
||||
|
||||
function buildLinkUrl(params: URLSearchParams): string {
|
||||
return `${OPENCODE_SERVER_LINK_PROTOCOL}//link?${params.toString()}`;
|
||||
}
|
||||
|
||||
function readLinkQueryFields(text: string): { url: URL; fields: LinkQueryFields } | null {
|
||||
const url = parseOpenCodeServerLinkUrl(text);
|
||||
if (!url || url.searchParams.get("v") !== OPENCODE_SERVER_LINK_VERSION) return null;
|
||||
return {
|
||||
url,
|
||||
fields: {
|
||||
kind: url.searchParams.get("kind"),
|
||||
name: url.searchParams.get("name"),
|
||||
baseUrl: url.searchParams.get("url"),
|
||||
code: url.searchParams.get("code"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function readLink<T>(
|
||||
schema: z.ZodType<T>,
|
||||
text: string,
|
||||
readDetails: (url: URL) => Record<string, unknown> | null,
|
||||
): T | null {
|
||||
const link = readLinkQueryFields(text);
|
||||
if (!link) return null;
|
||||
const details = readDetails(link.url);
|
||||
if (!details) return null;
|
||||
const parsed = schema.safeParse({ ...link.fields, ...details });
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
const REMOTE_DIRECTORY_KEY_PATTERN = /^(srv_[A-Za-z0-9_-]+)\|(.+)$/s;
|
||||
|
||||
/** Builds the event-stream subscription key for a directory; local directories stay unchanged. */
|
||||
|
||||
@@ -205,6 +205,12 @@ export const DEFAULT_SESSION_DEFAULTS = {
|
||||
goalMaxContinuations: 20,
|
||||
} satisfies SessionDefaults;
|
||||
|
||||
export const DevicePairingPreferencesSchema = z.object({
|
||||
allowPrivateNetworkHttp: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type DevicePairingPreferences = z.infer<typeof DevicePairingPreferencesSchema>;
|
||||
|
||||
export const UserPreferencesSchema = z.object({
|
||||
theme: z.enum(["dark", "light", "system"]),
|
||||
colorTheme: ColorThemeIdSchema.optional(),
|
||||
@@ -236,6 +242,7 @@ export const UserPreferencesSchema = z.object({
|
||||
serverEnvVars: z.array(ServerEnvVarSchema).optional(),
|
||||
sandbox: SandboxPreferencesSchema.optional(),
|
||||
sessionDefaults: SessionDefaultsSchema.optional(),
|
||||
devicePairing: DevicePairingPreferencesSchema.optional(),
|
||||
disabledDefaultServerEnvVars: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
|
||||
@@ -7,3 +7,4 @@ export * from './semver'
|
||||
export * from './terminal-title'
|
||||
export * from './unified-diff'
|
||||
export * from './url'
|
||||
export * from './user-agent'
|
||||
@@ -9,6 +9,50 @@ export function haveSameUrlOrigin(first: string, second: string): boolean {
|
||||
return origin !== null && origin === readUrlOrigin(second)
|
||||
}
|
||||
|
||||
/** Reports whether a hostname refers to the local machine. */
|
||||
export function isLoopbackHost(hostname: string): boolean {
|
||||
const host = normalizeHostname(hostname)
|
||||
if (host === 'localhost' || host === '::1') return true
|
||||
const octets = parseIpv4Octets(host)
|
||||
return octets !== null && octets[0] === 127
|
||||
}
|
||||
|
||||
/** Reports whether a hostname is an RFC 1918, link-local, or CGNAT address. */
|
||||
export function isPrivateNetworkHost(hostname: string): boolean {
|
||||
const host = normalizeHostname(hostname)
|
||||
const octets = parseIpv4Octets(host)
|
||||
if (octets !== null) {
|
||||
const [first, second] = octets
|
||||
return (
|
||||
first === 10 ||
|
||||
(first === 172 && second >= 16 && second <= 31) ||
|
||||
(first === 192 && second === 168) ||
|
||||
(first === 169 && second === 254) ||
|
||||
(first === 100 && second >= 64 && second <= 127)
|
||||
)
|
||||
}
|
||||
if (!host.includes(':')) return false
|
||||
const firstHextet = Number.parseInt(host.split(':')[0] ?? '', 16)
|
||||
return firstHextet >= 0xfc00 && firstHextet <= 0xfdff
|
||||
}
|
||||
|
||||
function normalizeHostname(hostname: string): string {
|
||||
return hostname.trim().toLowerCase().replace(/^\[/, '').replace(/\]$/, '')
|
||||
}
|
||||
|
||||
function parseIpv4Octets(host: string): [number, number, number, number] | null {
|
||||
const parts = host.split('.')
|
||||
if (parts.length !== 4) return null
|
||||
const octets: [number, number, number, number] = [0, 0, 0, 0]
|
||||
for (const [index, part] of parts.entries()) {
|
||||
if (!/^\d{1,3}$/.test(part)) return null
|
||||
const value = Number(part)
|
||||
if (value > 255) return null
|
||||
octets[index] = value
|
||||
}
|
||||
return octets
|
||||
}
|
||||
|
||||
function readUrlOrigin(value: string): string | null {
|
||||
try {
|
||||
return new URL(value).origin
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
const UNKNOWN_DEVICE = 'Unknown device'
|
||||
const RAW_USER_AGENT_MAX_LENGTH = 80
|
||||
|
||||
/** Describes a user agent as "browser on platform", falling back to the raw string. */
|
||||
export function describeUserAgent(userAgent: string | null | undefined): string {
|
||||
const value = userAgent?.trim()
|
||||
if (!value) return UNKNOWN_DEVICE
|
||||
|
||||
const platform = detectPlatform(value)
|
||||
const browser = detectBrowser(value)
|
||||
if (browser && platform) return `${browser} on ${platform}`
|
||||
return browser ?? platform ?? value.slice(0, RAW_USER_AGENT_MAX_LENGTH)
|
||||
}
|
||||
|
||||
function detectPlatform(userAgent: string): string | null {
|
||||
if (userAgent.includes('iPhone')) return 'iPhone'
|
||||
if (userAgent.includes('iPad')) return 'iPad'
|
||||
if (userAgent.includes('Android')) return 'Android'
|
||||
if (userAgent.includes('Macintosh')) return 'macOS'
|
||||
if (userAgent.includes('Windows')) return 'Windows'
|
||||
if (userAgent.includes('Linux')) return 'Linux'
|
||||
return null
|
||||
}
|
||||
|
||||
function detectBrowser(userAgent: string): string | null {
|
||||
if (userAgent.includes('Edg/')) return 'Edge'
|
||||
if (userAgent.includes('OPR/')) return 'Opera'
|
||||
if (userAgent.includes('Firefox/') || userAgent.includes('FxiOS/')) return 'Firefox'
|
||||
if (userAgent.includes('CriOS/') || userAgent.includes('Chrome/')) return 'Chrome'
|
||||
if (userAgent.includes('Safari/') && userAgent.includes('Version/')) return 'Safari'
|
||||
return null
|
||||
}
|
||||
Reference in new issue
Block a user