99 lines
No EOL
3.8 KiB
TypeScript
99 lines
No EOL
3.8 KiB
TypeScript
import { createTRPCProxyClient, httpBatchLink, TRPCClientError } from '@trpc/client';
|
|
import { createTRPCReact } from '@trpc/react-query';
|
|
import { AppRouter } from '@backend/trpc/router'
|
|
import { BASE_API_URL } from '@packages/shared';
|
|
import { getJWT } from '@/hooks/useJWT';
|
|
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs';
|
|
import { DeviceEventEmitter } from 'react-native';
|
|
|
|
// TEMP DIAGNOSTIC: decode (not verify) so we can see expiry/identity.
|
|
function decodeJwtClaims(token: string): Record<string, any> | null {
|
|
try {
|
|
const part = token.split('.')[1];
|
|
if (!part) return null;
|
|
const b64 = part.replace(/-/g, '+').replace(/_/g, '/');
|
|
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
|
|
const atobFn = (globalThis as any).atob as ((value: string) => string) | undefined;
|
|
if (!atobFn) return null;
|
|
const json = decodeURIComponent(
|
|
atobFn(padded)
|
|
.split('')
|
|
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
|
|
.join('')
|
|
);
|
|
return JSON.parse(json);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// Create tRPC React hooks without strict typing for now
|
|
export const trpc = createTRPCReact<AppRouter>();
|
|
|
|
// Create tRPC client for direct usage
|
|
export const trpcClient = createTRPCProxyClient<AppRouter>({
|
|
links: [
|
|
httpBatchLink({
|
|
url: BASE_API_URL+'/api/trpc',
|
|
headers: async () => {
|
|
const token = await getJWT();
|
|
const claims = token ? decodeJwtClaims(token) : null;
|
|
console.log(
|
|
`[admin-ui][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
|
|
);
|
|
console.log(
|
|
`[admin-ui][trpc] token claims: ${
|
|
claims
|
|
? `staffId=${claims.staffId ?? '-'} userId=${claims.userId ?? '-'} exp=${
|
|
claims.exp ? new Date(claims.exp * 1000).toISOString() : '-'
|
|
} expired=${claims.exp ? claims.exp * 1000 <= Date.now() : '?'}`
|
|
: 'unreadable'
|
|
}`
|
|
);
|
|
return token ? { Authorization: `Bearer ${token}` } : {};
|
|
},
|
|
fetch: async (url, options) => {
|
|
const rawHeaders: any = options?.headers;
|
|
const authHeader =
|
|
typeof rawHeaders?.get === 'function'
|
|
? rawHeaders.get('authorization')
|
|
: rawHeaders?.Authorization ?? rawHeaders?.authorization;
|
|
console.log(
|
|
`[admin-ui][trpc] request ${String(url)} | auth: ${
|
|
authHeader ? `PRESENT (${String(authHeader).length} chars)` : 'MISSING'
|
|
}`
|
|
);
|
|
const response = await fetch(url, options);
|
|
if (response.status === 401) {
|
|
console.log(
|
|
`[admin-ui][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
|
|
);
|
|
// TEMP DIAGNOSTIC: is the same bearer still accepted on a trivial protected query?
|
|
// Skipped in tests: it adds a fetch, and ATRPC-01 asserts exactly one.
|
|
if (process.env.NODE_ENV !== 'test') {
|
|
try {
|
|
const probe = await fetch(
|
|
`${BASE_API_URL}/api/trpc/admin.staffUser.me?batch=1&input=%7B%7D`,
|
|
{ method: 'GET', headers: options?.headers }
|
|
);
|
|
console.log(`[admin-ui][trpc] 401 probe (staffUser.me) -> ${probe.status}`);
|
|
} catch (probeError: any) {
|
|
console.log(
|
|
`[admin-ui][trpc] 401 probe failed: ${probeError?.message ?? probeError}`
|
|
);
|
|
}
|
|
}
|
|
const data = await response.clone().json().catch(() => ({}));
|
|
let code = '';
|
|
if(data[0]?.error || data?.error) {
|
|
code = data[0]?.error?.message || data?.error?.message
|
|
}
|
|
if (code === 'UNAUTHORIZED') {
|
|
DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT);
|
|
}
|
|
}
|
|
return response;
|
|
},
|
|
}),
|
|
],
|
|
}); |