-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopsClient.ts
More file actions
139 lines (117 loc) · 4.08 KB
/
Copy pathopsClient.ts
File metadata and controls
139 lines (117 loc) · 4.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import { OPS_BASE_URL } from './dashboardConfig';
export const OPS_BASE = OPS_BASE_URL;
export const OPS_STREAM_URL = buildOpsUrl('/stream');
const OPS_SESSION_PATH = '/ops/session';
const OPS_TOKEN_HEADER = 'x-ops-token';
let opsAuthToken: string | null = null;
export interface OpsSessionStatus {
authenticated: boolean;
authRequired: boolean;
expiresAt?: number;
prefillToken?: string;
}
export class OpsRequestError extends Error {
readonly path: string;
readonly status: number;
readonly reason: string;
constructor(path: string, status: number, reason: string) {
super(`${path}:${reason}`);
this.name = 'OpsRequestError';
this.path = path;
this.status = status;
this.reason = reason;
}
}
export function buildOpsUrl(path: string): string {
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
return `${OPS_BASE_URL}${normalizedPath}`;
}
export function getOpsStreamUrl(): string {
const base = OPS_STREAM_URL;
if (!opsAuthToken) return base;
if (!shouldAppendStreamToken(base) && hasOpsSessionCookie()) return base;
const separator = base.includes('?') ? '&' : '?';
return `${base}${separator}token=${encodeURIComponent(opsAuthToken)}`;
}
export function opsFetch(path: string, init?: RequestInit): Promise<Response> {
const headers = toHeaders(init?.headers);
if (opsAuthToken && !headers.has('authorization') && !headers.has(OPS_TOKEN_HEADER)) {
headers.set(OPS_TOKEN_HEADER, opsAuthToken);
}
const hasHeaders = Array.from(headers.keys()).length > 0;
return fetch(buildOpsUrl(path), {
...init,
headers: hasHeaders ? headers : undefined,
credentials: 'include'
});
}
export async function opsFetchJson<T>(path: string, init?: RequestInit): Promise<T> {
const response = await opsFetch(path, init);
const text = await response.text();
const parsed = text.trim().length > 0 ? safeParseJSON(text) : null;
if (!response.ok) {
const message =
parsed &&
typeof parsed === 'object' &&
parsed !== null &&
typeof (parsed as Record<string, unknown>).error === 'string'
? String((parsed as Record<string, unknown>).error)
: `http_${response.status}`;
throw new OpsRequestError(path, response.status, message);
}
return parsed as T;
}
export function isOpsUnauthorizedError(error: unknown): boolean {
if (error instanceof OpsRequestError) {
return error.status === 401;
}
if (error instanceof Error) {
return error.message.endsWith(':unauthorized') || error.message.endsWith(':http_401');
}
return false;
}
export function getOpsSession(options?: { prefill?: boolean }): Promise<OpsSessionStatus> {
const query = options?.prefill ? '?prefill=1' : '';
return opsFetchJson<OpsSessionStatus>(`${OPS_SESSION_PATH}${query}`);
}
export function createOpsSession(token: string): Promise<OpsSessionStatus> {
return opsFetchJson<OpsSessionStatus>(OPS_SESSION_PATH, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token })
});
}
export async function clearOpsSession(): Promise<void> {
await opsFetch(OPS_SESSION_PATH, { method: 'DELETE' });
}
export function setOpsAuthToken(token: string | undefined | null): void {
const normalized = typeof token === 'string' ? token.trim() : '';
opsAuthToken = normalized.length > 0 ? normalized : null;
}
export function clearOpsAuthToken(): void {
opsAuthToken = null;
}
function safeParseJSON(value: string): unknown {
try {
return JSON.parse(value);
} catch {
return null;
}
}
function toHeaders(input: HeadersInit | undefined): Headers {
if (!input) return new Headers();
return new Headers(input);
}
function shouldAppendStreamToken(streamUrl: string): boolean {
if (typeof window === 'undefined') return false;
try {
const resolved = new URL(streamUrl, window.location.href);
return resolved.hostname !== window.location.hostname;
} catch {
return false;
}
}
function hasOpsSessionCookie(): boolean {
if (typeof document === 'undefined') return false;
return document.cookie.split(';').some((part) => part.trim().startsWith('ops_session='));
}