Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
import { DEV_FALLBACK_CLI_REFUSAL } from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { httpAuthQueryTransport } from './auth-query-transport';
type FetchFn = typeof globalThis.fetch;
let originalFetch: FetchFn;
let lastCall: { url: string; init: Parameters<FetchFn>[1] } | null;
let fetchCalls: Array<{ url: string; init: Parameters<FetchFn>[1] }>;
function stubFetch(make: () => Response | Promise<Response>): void {
globalThis.fetch = (async (input: Parameters<FetchFn>[0], init?: Parameters<FetchFn>[1]) => {
lastCall = { url: typeof input === 'string' ? input : String(input), init };
fetchCalls.push(lastCall);
return await make();
}) as FetchFn;
}
beforeEach(() => {
originalFetch = globalThis.fetch;
lastCall = null;
fetchCalls = [];
});
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe('httpAuthQueryTransport().status', () => {
function problem(status: number, body: Record<string, unknown>): Response {
return new Response(JSON.stringify({ status, instance: undefined, ...body }), {
status,
headers: { 'Content-Type': 'application/problem+json' },
});
}
it('reports a non-GitHub origin refusal with the rejected host instead of github.com', async () => {
stubFetch(() =>
problem(409, {
type: 'urn:ok:error:non-github-origin',
title: 'GitHub sign-in is unavailable for this host.',
detail: 'ghes.acme.test is not a declared GitHub host.',
host: 'ghes.acme.test',
}),
);
expect(await httpAuthQueryTransport().status()).toEqual({
authenticated: false,
host: 'ghes.acme.test',
error: 'GitHub sign-in is unavailable for this host.',
unsupportedOrigin: { host: 'ghes.acme.test' },
});
});
it('reports an origin refusal whose remote names no host', async () => {
stubFetch(() =>
problem(409, {
type: 'urn:ok:error:non-github-origin',
title: 'GitHub sign-in is unavailable for this host.',
host: null,
}),
);
const result = await httpAuthQueryTransport().status();
expect(result).toMatchObject({ authenticated: false, unsupportedOrigin: { host: null } });
});
it('keeps other failures as a plain unauthenticated result', async () => {
stubFetch(() =>
problem(500, { type: 'urn:ok:error:internal-server-error', title: 'Internal server error.' }),
);
const result = await httpAuthQueryTransport().status();
expect(result).toEqual({
authenticated: false,
host: 'github.com',
error: 'Internal server error.',
});
});
it('coalesces concurrent same-host checks across transport instances', async () => {
const { promise: pendingResponse, resolve: resolveFetch } = Promise.withResolvers<Response>();
stubFetch(() => pendingResponse);
const a = httpAuthQueryTransport().status();
const b = httpAuthQueryTransport().status({ host: 'github.com' });
expect(fetchCalls).toHaveLength(1);
expect(fetchCalls[0]?.url).toBe('/api/local-op/auth/status');
resolveFetch(
new Response(JSON.stringify({ authenticated: true, host: 'github.com', login: 'octocat' }), {
status: 200,
}),
);
const [resA, resB] = await Promise.all([a, b]);
expect(resA).toEqual({
authenticated: true,
host: 'github.com',
login: 'octocat',
ghAvailable: false,
});
expect(resB).toEqual(resA);
});
it('keeps concurrent different-host checks isolated', async () => {
const { promise: githubResponse, resolve: resolveGithub } = Promise.withResolvers<Response>();
const { promise: gitlabResponse, resolve: resolveGitlab } = Promise.withResolvers<Response>();
const pendingResponses = [githubResponse, gitlabResponse];
stubFetch(() => {
const response = pendingResponses.shift();
if (!response) throw new Error('unexpected extra fetch');
return response;
});
const githubStatus = httpAuthQueryTransport().status({ host: 'github.com' });
const gitlabStatus = httpAuthQueryTransport().status({ host: 'gitlab.com' });
expect(fetchCalls).toHaveLength(2);
expect(fetchCalls.map((call) => JSON.parse(String(call.init?.body)).host)).toEqual([
'github.com',
'gitlab.com',
]);
resolveGithub(
new Response(JSON.stringify({ authenticated: true, host: 'github.com', login: 'octocat' })),
);
resolveGitlab(new Response(JSON.stringify({ authenticated: false, host: 'gitlab.com' })));
await expect(githubStatus).resolves.toEqual({
authenticated: true,
host: 'github.com',
login: 'octocat',
ghAvailable: false,
});
await expect(gitlabStatus).resolves.toEqual({
authenticated: false,
host: 'gitlab.com',
ghAvailable: false,
});
});
it('clears the coalescing slot after the status check settles', async () => {
stubFetch(() => new Response(JSON.stringify({ authenticated: false, host: 'github.com' })));
const transport = httpAuthQueryTransport();
await transport.status();
await transport.status();
expect(fetchCalls).toHaveLength(2);
});
it('clears the coalescing slot after the status check rejects', async () => {
let callCount = 0;
stubFetch(() => {
callCount += 1;
if (callCount === 1) throw new Error('network down');
return new Response(JSON.stringify({ authenticated: false, host: 'github.com' }));
});
const transport = httpAuthQueryTransport();
await expect(transport.status()).rejects.toThrow('network down');
await expect(transport.status()).resolves.toEqual({
authenticated: false,
host: 'github.com',
ghAvailable: false,
});
expect(fetchCalls).toHaveLength(2);
});
it('leaves an ordinary signed-out 200 free of an origin refusal', async () => {
stubFetch(
() =>
new Response(JSON.stringify({ authenticated: false, host: 'github.com', error: 'nope' })),
);
const result = await httpAuthQueryTransport().status();
expect(result.authenticated).toBe(false);
expect(result.authenticated ? undefined : result.unsupportedOrigin).toBeUndefined();
});
});
describe('httpAuthQueryTransport().signout', () => {
it('POSTs to the signout endpoint and resolves ok on a 200 empty body', async () => {
stubFetch(() => new Response('{}', { status: 200 }));
const transport = httpAuthQueryTransport();
if (!transport.signout) throw new Error('http transport must implement signout');
const result = await transport.signout({ host: 'github.com' });
expect(result).toEqual({ ok: true });
expect(lastCall?.url).toBe('/api/local-op/auth/signout');
expect(lastCall?.init?.method).toBe('POST');
expect(JSON.parse(String(lastCall?.init?.body))).toEqual({ host: 'github.com' });
});
it('surfaces the RFC 9457 problem title when the endpoint returns problem+json', async () => {
stubFetch(
() =>
new Response(
JSON.stringify({
type: 'urn:ok:error:auth-failed',
title: 'Auth signout failed.',
status: 500,
}),
{ status: 500, headers: { 'content-type': 'application/problem+json' } },
),
);
const transport = httpAuthQueryTransport();
if (!transport.signout) throw new Error('http transport must implement signout');
const result = await transport.signout();
expect(result).toEqual({ ok: false, error: 'Auth signout failed.' });
});
it('surfaces the problem detail over the title, so a refusal keeps its remedy', async () => {
stubFetch(
() =>
new Response(
JSON.stringify({
type: 'urn:ok:error:auth-failed',
title: 'This dev build has no built CLI.',
status: 409,
detail: DEV_FALLBACK_CLI_REFUSAL,
}),
{ status: 409, headers: { 'content-type': 'application/problem+json' } },
),
);
const transport = httpAuthQueryTransport();
if (!transport.signout) throw new Error('http transport must implement signout');
expect(await transport.signout()).toEqual({ ok: false, error: DEV_FALLBACK_CLI_REFUSAL });
});
it('returns failure with no error title when the body is not problem+json', async () => {
stubFetch(() => new Response('upstream boom', { status: 502 }));
const transport = httpAuthQueryTransport();
if (!transport.signout) throw new Error('http transport must implement signout');
const result = await transport.signout();
expect(result).toEqual({ ok: false });
});
it('omits host from the body when none is supplied (server applies its default)', async () => {
stubFetch(() => new Response('{}', { status: 200 }));
const transport = httpAuthQueryTransport();
if (!transport.signout) throw new Error('http transport must implement signout');
await transport.signout();
expect(JSON.parse(String(lastCall?.init?.body))).toEqual({});
});
});