@n6k.io/serve 0.2.5 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -9
- package/package.json +6 -5
- package/src/assets.ts +1 -17
- package/src/bundle.ts +1 -2
- package/src/cli.ts +139 -68
- package/src/logout.test.ts +65 -0
- package/src/logout.ts +35 -0
- package/src/mcp-instructions.ts +1 -1
- package/src/mcp.test.ts +1 -1
- package/src/oidc-grants.ts +220 -0
- package/src/oidc.test.ts +303 -0
- package/src/oidc.ts +120 -0
- package/src/root.tsx +26 -5
- package/src/saved-logins.ts +114 -0
- package/src/server.ts +66 -1
- package/src/token-route.test.ts +87 -0
- package/src/virtual-modules.d.ts +0 -6
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
export class OidcError extends Error {}
|
|
2
|
+
|
|
3
|
+
const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
|
|
4
|
+
const LOGIN_SCOPES = ["openid", "email", "offline_access"];
|
|
5
|
+
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
6
|
+
|
|
7
|
+
export type OidcOptions = {
|
|
8
|
+
log?: (line: string) => void;
|
|
9
|
+
sleep?: (ms: number) => Promise<void>;
|
|
10
|
+
now?: () => number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
type Json = Record<string, unknown>;
|
|
14
|
+
|
|
15
|
+
export type Endpoints = {
|
|
16
|
+
issuer: string;
|
|
17
|
+
clientId: string;
|
|
18
|
+
tokenEndpoint: string;
|
|
19
|
+
deviceEndpoint: string;
|
|
20
|
+
scopes: string[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function isJson(value: unknown): value is Json {
|
|
24
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function str(doc: Json, key: string, where: string): string {
|
|
28
|
+
const value = doc[key];
|
|
29
|
+
if (typeof value !== "string" || value === "")
|
|
30
|
+
throw new OidcError(`${where}: missing ${key}`);
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function optionalStr(doc: Json, key: string): string | undefined {
|
|
35
|
+
const value = doc[key];
|
|
36
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function num(doc: Json, key: string): number | undefined {
|
|
40
|
+
const value = doc[key];
|
|
41
|
+
return typeof value === "number" && Number.isFinite(value)
|
|
42
|
+
? value
|
|
43
|
+
: undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function getJson(url: string): Promise<Json> {
|
|
47
|
+
let res: Response;
|
|
48
|
+
try {
|
|
49
|
+
res = await fetch(url);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
throw new OidcError(
|
|
52
|
+
`${url}: ${err instanceof Error ? err.message : String(err)}`,
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
if (res.status === 404)
|
|
56
|
+
throw new OidcError(`${url} not found: the server does not offer sign-in`);
|
|
57
|
+
if (!res.ok) throw new OidcError(`${url}: HTTP ${res.status}`);
|
|
58
|
+
const doc: unknown = await res.json().catch(() => {});
|
|
59
|
+
if (!isJson(doc)) throw new OidcError(`${url}: not a JSON object`);
|
|
60
|
+
return doc;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function postForm(
|
|
64
|
+
url: string,
|
|
65
|
+
form: Record<string, string>,
|
|
66
|
+
): Promise<{ status: number; doc: Json }> {
|
|
67
|
+
const res = await fetch(url, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: {
|
|
70
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
71
|
+
Accept: "application/json",
|
|
72
|
+
},
|
|
73
|
+
body: new URLSearchParams(form),
|
|
74
|
+
});
|
|
75
|
+
const doc: unknown = await res.json().catch(() => {});
|
|
76
|
+
if (!isJson(doc)) throw new OidcError(`${url}: HTTP ${res.status}`);
|
|
77
|
+
return { status: res.status, doc };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function oauthError(url: string, doc: Json): OidcError {
|
|
81
|
+
const description = optionalStr(doc, "error_description");
|
|
82
|
+
return new OidcError(
|
|
83
|
+
`${url}: ${optionalStr(doc, "error") ?? "request failed"}${description ? ` (${description})` : ""}`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function protectedResourceUrl(wsUrl: string): string {
|
|
88
|
+
const url = new URL(wsUrl);
|
|
89
|
+
const scheme = url.protocol === "wss:" ? "https:" : "http:";
|
|
90
|
+
return `${scheme}//${url.host}${PROTECTED_RESOURCE_PATH}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function discover(wsUrl: string): Promise<Endpoints> {
|
|
94
|
+
const metadataUrl = protectedResourceUrl(wsUrl);
|
|
95
|
+
const resource = await getJson(metadataUrl);
|
|
96
|
+
const servers = resource.authorization_servers;
|
|
97
|
+
if (
|
|
98
|
+
!Array.isArray(servers) ||
|
|
99
|
+
typeof servers[0] !== "string" ||
|
|
100
|
+
servers[0] === ""
|
|
101
|
+
)
|
|
102
|
+
throw new OidcError(`${metadataUrl}: missing authorization_servers`);
|
|
103
|
+
const issuer = servers[0];
|
|
104
|
+
const clientId = str(resource, "client_id", metadataUrl);
|
|
105
|
+
|
|
106
|
+
const configUrl = `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
107
|
+
const config = await getJson(configUrl);
|
|
108
|
+
const supported = Array.isArray(config.scopes_supported)
|
|
109
|
+
? config.scopes_supported.filter((s) => typeof s === "string")
|
|
110
|
+
: [];
|
|
111
|
+
return {
|
|
112
|
+
issuer,
|
|
113
|
+
clientId,
|
|
114
|
+
tokenEndpoint: str(config, "token_endpoint", configUrl),
|
|
115
|
+
deviceEndpoint: str(config, "device_authorization_endpoint", configUrl),
|
|
116
|
+
scopes:
|
|
117
|
+
supported.length === 0
|
|
118
|
+
? LOGIN_SCOPES
|
|
119
|
+
: LOGIN_SCOPES.filter((s) => supported.includes(s)),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export type Tokens = { access: string; refresh?: string; expiresAt: number };
|
|
124
|
+
|
|
125
|
+
function jwtClaims(token: string): Json {
|
|
126
|
+
const payload = token.split(".", 2)[1];
|
|
127
|
+
if (!payload) return {};
|
|
128
|
+
try {
|
|
129
|
+
const claims: unknown = JSON.parse(
|
|
130
|
+
Buffer.from(payload, "base64url").toString("utf8"),
|
|
131
|
+
);
|
|
132
|
+
return isJson(claims) ? claims : {};
|
|
133
|
+
} catch {
|
|
134
|
+
return {};
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function jwtExpiry(token: string): number | undefined {
|
|
139
|
+
const exp = num(jwtClaims(token), "exp");
|
|
140
|
+
return exp === undefined ? undefined : exp * 1000;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function who(token: string): string {
|
|
144
|
+
const claims = jwtClaims(token);
|
|
145
|
+
return (
|
|
146
|
+
optionalStr(claims, "preferred_username") ??
|
|
147
|
+
optionalStr(claims, "email") ??
|
|
148
|
+
optionalStr(claims, "sub") ??
|
|
149
|
+
"unknown user"
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function readTokens(doc: Json, url: string, now: number): Tokens {
|
|
154
|
+
const access = str(doc, "access_token", url);
|
|
155
|
+
const expiresIn = num(doc, "expires_in");
|
|
156
|
+
return {
|
|
157
|
+
access,
|
|
158
|
+
refresh: optionalStr(doc, "refresh_token"),
|
|
159
|
+
expiresAt:
|
|
160
|
+
expiresIn === undefined
|
|
161
|
+
? (jwtExpiry(access) ?? Number.POSITIVE_INFINITY)
|
|
162
|
+
: now + expiresIn * 1000,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function deviceLogin(
|
|
167
|
+
endpoints: Endpoints,
|
|
168
|
+
options: Required<OidcOptions>,
|
|
169
|
+
): Promise<Tokens> {
|
|
170
|
+
const { deviceEndpoint, tokenEndpoint, clientId } = endpoints;
|
|
171
|
+
const started = await postForm(deviceEndpoint, {
|
|
172
|
+
client_id: clientId,
|
|
173
|
+
scope: endpoints.scopes.join(" "),
|
|
174
|
+
});
|
|
175
|
+
if (started.status !== 200) throw oauthError(deviceEndpoint, started.doc);
|
|
176
|
+
const deviceCode = str(started.doc, "device_code", deviceEndpoint);
|
|
177
|
+
const userCode = str(started.doc, "user_code", deviceEndpoint);
|
|
178
|
+
const verify =
|
|
179
|
+
optionalStr(started.doc, "verification_uri_complete") ??
|
|
180
|
+
str(started.doc, "verification_uri", deviceEndpoint);
|
|
181
|
+
let interval = (num(started.doc, "interval") ?? 5) * 1000;
|
|
182
|
+
const deadline =
|
|
183
|
+
options.now() + (num(started.doc, "expires_in") ?? 600) * 1000;
|
|
184
|
+
|
|
185
|
+
options.log(`Sign in at ${verify} (code: ${userCode})`);
|
|
186
|
+
for (;;) {
|
|
187
|
+
if (options.now() >= deadline)
|
|
188
|
+
throw new OidcError(`${endpoints.issuer}: sign-in timed out`);
|
|
189
|
+
await options.sleep(interval);
|
|
190
|
+
const { status, doc } = await postForm(tokenEndpoint, {
|
|
191
|
+
grant_type: DEVICE_GRANT,
|
|
192
|
+
device_code: deviceCode,
|
|
193
|
+
client_id: clientId,
|
|
194
|
+
});
|
|
195
|
+
if (status === 200) return readTokens(doc, tokenEndpoint, options.now());
|
|
196
|
+
const error = optionalStr(doc, "error");
|
|
197
|
+
if (error === "authorization_pending") continue;
|
|
198
|
+
if (error === "slow_down") {
|
|
199
|
+
interval += 5000;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
throw oauthError(tokenEndpoint, doc);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export async function refreshGrant(
|
|
207
|
+
endpoints: Endpoints,
|
|
208
|
+
refresh: string,
|
|
209
|
+
now: number,
|
|
210
|
+
): Promise<Tokens> {
|
|
211
|
+
const { tokenEndpoint, clientId } = endpoints;
|
|
212
|
+
const { status, doc } = await postForm(tokenEndpoint, {
|
|
213
|
+
grant_type: "refresh_token",
|
|
214
|
+
refresh_token: refresh,
|
|
215
|
+
client_id: clientId,
|
|
216
|
+
});
|
|
217
|
+
if (status !== 200) throw oauthError(tokenEndpoint, doc);
|
|
218
|
+
const next = readTokens(doc, tokenEndpoint, now);
|
|
219
|
+
return { ...next, refresh: next.refresh ?? refresh };
|
|
220
|
+
}
|
package/src/oidc.test.ts
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { afterEach, expect, test } from "bun:test";
|
|
2
|
+
import { OidcError, OidcLogins, protectedResourceUrl } from "./oidc";
|
|
3
|
+
import { SavedLogins, type RefreshStore } from "./saved-logins";
|
|
4
|
+
|
|
5
|
+
type Form = Record<string, string>;
|
|
6
|
+
|
|
7
|
+
function fakeIdp(script: {
|
|
8
|
+
deviceReplies: object[];
|
|
9
|
+
refreshReplies: object[];
|
|
10
|
+
}) {
|
|
11
|
+
const deviceReplies = [...script.deviceReplies];
|
|
12
|
+
const refreshReplies = [...script.refreshReplies];
|
|
13
|
+
const requests: Form[] = [];
|
|
14
|
+
let deviceStarts = 0;
|
|
15
|
+
const server = Bun.serve({
|
|
16
|
+
port: 0,
|
|
17
|
+
async fetch(req) {
|
|
18
|
+
const { pathname, origin: base } = new URL(req.url);
|
|
19
|
+
if (pathname === "/n6kd/.well-known/oauth-protected-resource")
|
|
20
|
+
return Response.json({
|
|
21
|
+
resource: "n6kd",
|
|
22
|
+
authorization_servers: [`${base}/realm`],
|
|
23
|
+
client_id: "n6k-cli",
|
|
24
|
+
});
|
|
25
|
+
if (pathname === "/realm/.well-known/openid-configuration")
|
|
26
|
+
return Response.json({
|
|
27
|
+
token_endpoint: `${base}/token`,
|
|
28
|
+
device_authorization_endpoint: `${base}/device`,
|
|
29
|
+
scopes_supported: ["openid", "offline_access"],
|
|
30
|
+
});
|
|
31
|
+
const form = Object.fromEntries(new URLSearchParams(await req.text()));
|
|
32
|
+
requests.push(form);
|
|
33
|
+
if (pathname === "/device") {
|
|
34
|
+
deviceStarts++;
|
|
35
|
+
return Response.json({
|
|
36
|
+
device_code: "dc",
|
|
37
|
+
user_code: "UC",
|
|
38
|
+
verification_uri: `${base}/verify`,
|
|
39
|
+
interval: 1,
|
|
40
|
+
expires_in: 600,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (pathname === "/token") {
|
|
44
|
+
const reply =
|
|
45
|
+
form.grant_type === "refresh_token"
|
|
46
|
+
? refreshReplies.shift()
|
|
47
|
+
: deviceReplies.shift();
|
|
48
|
+
if (!reply)
|
|
49
|
+
return Response.json({ error: "exhausted" }, { status: 400 });
|
|
50
|
+
return Response.json(reply, {
|
|
51
|
+
status: "error" in reply ? 400 : 200,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return new Response("not found", { status: 404 });
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
return {
|
|
58
|
+
server,
|
|
59
|
+
requests,
|
|
60
|
+
deviceStarts: () => deviceStarts,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const servers: { stop: (force?: boolean) => unknown }[] = [];
|
|
65
|
+
afterEach(() => {
|
|
66
|
+
for (const s of servers.splice(0)) s.stop(true);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
function memoryStore(initial: Record<string, string> = {}) {
|
|
70
|
+
const saved = new Map(Object.entries(initial));
|
|
71
|
+
const store: RefreshStore = {
|
|
72
|
+
get: async (name) => saved.get(name) ?? null,
|
|
73
|
+
set: async (name, value) => {
|
|
74
|
+
saved.set(name, value);
|
|
75
|
+
},
|
|
76
|
+
delete: async (name) => saved.delete(name),
|
|
77
|
+
};
|
|
78
|
+
return { store, saved };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function harness(initial: Record<string, string> = {}) {
|
|
82
|
+
let now = 1_000_000;
|
|
83
|
+
const sleeps: number[] = [];
|
|
84
|
+
const logs: string[] = [];
|
|
85
|
+
const { store, saved } = memoryStore(initial);
|
|
86
|
+
const logins = new OidcLogins(new SavedLogins(store), {
|
|
87
|
+
log: (line) => logs.push(line),
|
|
88
|
+
sleep: async (ms) => {
|
|
89
|
+
sleeps.push(ms);
|
|
90
|
+
now += ms;
|
|
91
|
+
},
|
|
92
|
+
now: () => now,
|
|
93
|
+
});
|
|
94
|
+
return { logins, saved, sleeps, logs, advance: (ms: number) => (now += ms) };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function n6kdAt(idp: ReturnType<typeof fakeIdp>): string {
|
|
98
|
+
return `ws://localhost:${idp.server.port}/ws`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function withMetadataAtRoot(idp: ReturnType<typeof fakeIdp>) {
|
|
102
|
+
const proxy = Bun.serve({
|
|
103
|
+
port: 0,
|
|
104
|
+
fetch(req) {
|
|
105
|
+
const { pathname } = new URL(req.url);
|
|
106
|
+
if (pathname === "/.well-known/oauth-protected-resource")
|
|
107
|
+
return fetch(
|
|
108
|
+
`http://localhost:${idp.server.port}/n6kd/.well-known/oauth-protected-resource`,
|
|
109
|
+
);
|
|
110
|
+
return new Response("not found", { status: 404 });
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
servers.push(proxy);
|
|
114
|
+
return `ws://localhost:${proxy.port}/ws`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
test("protectedResourceUrl maps ws/wss to http/https on the same host", () => {
|
|
118
|
+
expect(protectedResourceUrl("ws://h:8080/ws")).toBe(
|
|
119
|
+
"http://h:8080/.well-known/oauth-protected-resource",
|
|
120
|
+
);
|
|
121
|
+
expect(protectedResourceUrl("wss://h/x/ws")).toBe(
|
|
122
|
+
"https://h/.well-known/oauth-protected-resource",
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("device login polls through pending and slow_down", async () => {
|
|
127
|
+
const idp = fakeIdp({
|
|
128
|
+
deviceReplies: [
|
|
129
|
+
{ error: "authorization_pending" },
|
|
130
|
+
{ error: "slow_down" },
|
|
131
|
+
{ access_token: "a1", refresh_token: "r1", expires_in: 300 },
|
|
132
|
+
],
|
|
133
|
+
refreshReplies: [],
|
|
134
|
+
});
|
|
135
|
+
servers.push(idp.server);
|
|
136
|
+
const h = harness();
|
|
137
|
+
const session = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
138
|
+
|
|
139
|
+
expect(await session.token()).toBe("a1");
|
|
140
|
+
expect(h.sleeps).toEqual([1000, 1000, 6000]);
|
|
141
|
+
expect(h.logs).toEqual([
|
|
142
|
+
`Sign in at http://localhost:${idp.server.port}/verify (code: UC)`,
|
|
143
|
+
`signed in to http://localhost:${idp.server.port}/realm as unknown user`,
|
|
144
|
+
]);
|
|
145
|
+
expect(idp.requests[0]).toEqual({
|
|
146
|
+
client_id: "n6k-cli",
|
|
147
|
+
scope: "openid offline_access",
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("refreshes near expiry and keeps the rotated refresh token", async () => {
|
|
152
|
+
const idp = fakeIdp({
|
|
153
|
+
deviceReplies: [
|
|
154
|
+
{ access_token: "a1", refresh_token: "r1", expires_in: 300 },
|
|
155
|
+
],
|
|
156
|
+
refreshReplies: [
|
|
157
|
+
{ access_token: "a2", refresh_token: "r2", expires_in: 300 },
|
|
158
|
+
{ access_token: "a3", expires_in: 300 },
|
|
159
|
+
{ access_token: "a4", expires_in: 300 },
|
|
160
|
+
],
|
|
161
|
+
});
|
|
162
|
+
servers.push(idp.server);
|
|
163
|
+
const h = harness();
|
|
164
|
+
const session = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
165
|
+
|
|
166
|
+
h.advance(250_000);
|
|
167
|
+
const [x, y] = await Promise.all([session.token(), session.token()]);
|
|
168
|
+
expect([x, y]).toEqual(["a2", "a2"]);
|
|
169
|
+
h.advance(250_000);
|
|
170
|
+
expect(await session.token()).toBe("a3");
|
|
171
|
+
h.advance(250_000);
|
|
172
|
+
expect(await session.token()).toBe("a4");
|
|
173
|
+
|
|
174
|
+
const refreshes = idp.requests.filter(
|
|
175
|
+
(r) => r.grant_type === "refresh_token",
|
|
176
|
+
);
|
|
177
|
+
expect(refreshes.map((r) => r.refresh_token)).toEqual(["r1", "r2", "r2"]);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
function savedKey(idp: ReturnType<typeof fakeIdp>): string {
|
|
181
|
+
return `http://localhost:${idp.server.port}/realm n6k-cli`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
test("device login saves the refresh token, refresh saves the rotated one", async () => {
|
|
185
|
+
const idp = fakeIdp({
|
|
186
|
+
deviceReplies: [
|
|
187
|
+
{ access_token: "a1", refresh_token: "r1", expires_in: 300 },
|
|
188
|
+
],
|
|
189
|
+
refreshReplies: [
|
|
190
|
+
{ access_token: "a2", refresh_token: "r2", expires_in: 300 },
|
|
191
|
+
],
|
|
192
|
+
});
|
|
193
|
+
servers.push(idp.server);
|
|
194
|
+
const h = harness();
|
|
195
|
+
const session = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
196
|
+
expect(h.saved.get(savedKey(idp))).toBe("r1");
|
|
197
|
+
h.advance(250_000);
|
|
198
|
+
expect(await session.token()).toBe("a2");
|
|
199
|
+
expect(h.saved.get(savedKey(idp))).toBe("r2");
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("a saved refresh token skips the device login", async () => {
|
|
203
|
+
const idp = fakeIdp({
|
|
204
|
+
deviceReplies: [],
|
|
205
|
+
refreshReplies: [
|
|
206
|
+
{ access_token: "a1", refresh_token: "r2", expires_in: 300 },
|
|
207
|
+
],
|
|
208
|
+
});
|
|
209
|
+
servers.push(idp.server);
|
|
210
|
+
const h = harness({ [savedKey(idp)]: "r1" });
|
|
211
|
+
const session = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
212
|
+
expect(await session.token()).toBe("a1");
|
|
213
|
+
expect(idp.deviceStarts()).toBe(0);
|
|
214
|
+
expect(h.logs).toEqual([
|
|
215
|
+
`using saved sign-in for http://localhost:${idp.server.port}/realm as unknown user`,
|
|
216
|
+
]);
|
|
217
|
+
expect(h.saved.get(savedKey(idp))).toBe("r2");
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
test("a rejected saved refresh token falls back to device login", async () => {
|
|
221
|
+
const idp = fakeIdp({
|
|
222
|
+
deviceReplies: [
|
|
223
|
+
{ access_token: "a1", refresh_token: "r9", expires_in: 300 },
|
|
224
|
+
],
|
|
225
|
+
refreshReplies: [{ error: "invalid_grant" }],
|
|
226
|
+
});
|
|
227
|
+
servers.push(idp.server);
|
|
228
|
+
const h = harness({ [savedKey(idp)]: "stale" });
|
|
229
|
+
const session = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
230
|
+
expect(await session.token()).toBe("a1");
|
|
231
|
+
expect(idp.deviceStarts()).toBe(1);
|
|
232
|
+
expect(h.logs[0]).toContain("rejected");
|
|
233
|
+
expect(h.saved.get(savedKey(idp))).toBe("r9");
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
function jwt(claims: object): string {
|
|
237
|
+
return `x.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.y`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
test("a rejected refresh while running signs in again", async () => {
|
|
241
|
+
const idp = fakeIdp({
|
|
242
|
+
deviceReplies: [
|
|
243
|
+
{ access_token: "a1", refresh_token: "r1", expires_in: 300 },
|
|
244
|
+
{
|
|
245
|
+
access_token: jwt({ preferred_username: "grace" }),
|
|
246
|
+
refresh_token: "r2",
|
|
247
|
+
expires_in: 300,
|
|
248
|
+
},
|
|
249
|
+
],
|
|
250
|
+
refreshReplies: [{ error: "invalid_grant", error_description: "revoked" }],
|
|
251
|
+
});
|
|
252
|
+
servers.push(idp.server);
|
|
253
|
+
const h = harness();
|
|
254
|
+
const session = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
255
|
+
h.advance(250_000);
|
|
256
|
+
expect(await session.token()).toBe(jwt({ preferred_username: "grace" }));
|
|
257
|
+
expect(idp.deviceStarts()).toBe(2);
|
|
258
|
+
const issuer = `http://localhost:${idp.server.port}/realm`;
|
|
259
|
+
expect(h.logs.slice(2)).toEqual([
|
|
260
|
+
`sign-in for ${issuer} expired: http://localhost:${idp.server.port}/token: invalid_grant (revoked)`,
|
|
261
|
+
`Sign in at http://localhost:${idp.server.port}/verify (code: UC)`,
|
|
262
|
+
`signed in to ${issuer} as grace`,
|
|
263
|
+
]);
|
|
264
|
+
expect(h.saved.get(savedKey(idp))).toBe("r2");
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
test("servers on one issuer share a single login", async () => {
|
|
268
|
+
const idp = fakeIdp({
|
|
269
|
+
deviceReplies: [
|
|
270
|
+
{ access_token: "a1", refresh_token: "r1", expires_in: 300 },
|
|
271
|
+
],
|
|
272
|
+
refreshReplies: [],
|
|
273
|
+
});
|
|
274
|
+
servers.push(idp.server);
|
|
275
|
+
const h = harness();
|
|
276
|
+
const a = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
277
|
+
const b = await h.logins.sessionFor(withMetadataAtRoot(idp));
|
|
278
|
+
expect(a).toBe(b);
|
|
279
|
+
expect(idp.deviceStarts()).toBe(1);
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
test("a server without protected-resource metadata fails", async () => {
|
|
283
|
+
const idp = fakeIdp({ deviceReplies: [], refreshReplies: [] });
|
|
284
|
+
servers.push(idp.server);
|
|
285
|
+
const h = harness();
|
|
286
|
+
const err = await h.logins.sessionFor(n6kdAt(idp)).catch((e) => e);
|
|
287
|
+
expect(err).toBeInstanceOf(OidcError);
|
|
288
|
+
expect(err.message).toContain("does not offer sign-in");
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
test("a denied device login fails", async () => {
|
|
292
|
+
const idp = fakeIdp({
|
|
293
|
+
deviceReplies: [{ error: "access_denied", error_description: "no" }],
|
|
294
|
+
refreshReplies: [],
|
|
295
|
+
});
|
|
296
|
+
servers.push(idp.server);
|
|
297
|
+
const h = harness();
|
|
298
|
+
const err = await h.logins
|
|
299
|
+
.sessionFor(withMetadataAtRoot(idp))
|
|
300
|
+
.catch((e) => e);
|
|
301
|
+
expect(err).toBeInstanceOf(OidcError);
|
|
302
|
+
expect(err.message).toContain("access_denied (no)");
|
|
303
|
+
});
|
package/src/oidc.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OidcError,
|
|
3
|
+
deviceLogin,
|
|
4
|
+
discover,
|
|
5
|
+
refreshGrant,
|
|
6
|
+
who,
|
|
7
|
+
type Endpoints,
|
|
8
|
+
type OidcOptions,
|
|
9
|
+
type Tokens,
|
|
10
|
+
} from "./oidc-grants";
|
|
11
|
+
|
|
12
|
+
import { SavedLogins, loginKey, serverOf } from "./saved-logins";
|
|
13
|
+
|
|
14
|
+
export { OidcError, protectedResourceUrl } from "./oidc-grants";
|
|
15
|
+
|
|
16
|
+
const REFRESH_MARGIN_MS = 60_000;
|
|
17
|
+
|
|
18
|
+
export class OidcSession {
|
|
19
|
+
private refreshing: Promise<string> | undefined;
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
private readonly endpoints: Endpoints,
|
|
23
|
+
private tokens: Tokens,
|
|
24
|
+
private readonly now: () => number,
|
|
25
|
+
private readonly log: (line: string) => void,
|
|
26
|
+
private readonly signIn: () => Promise<Tokens>,
|
|
27
|
+
private readonly save: (refresh: string) => Promise<void>,
|
|
28
|
+
) {}
|
|
29
|
+
|
|
30
|
+
token(): Promise<string> {
|
|
31
|
+
if (this.tokens.expiresAt - this.now() > REFRESH_MARGIN_MS)
|
|
32
|
+
return Promise.resolve(this.tokens.access);
|
|
33
|
+
this.refreshing ??= this.refresh().finally(() => {
|
|
34
|
+
this.refreshing = undefined;
|
|
35
|
+
});
|
|
36
|
+
return this.refreshing;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
private async refresh(): Promise<string> {
|
|
40
|
+
const { issuer } = this.endpoints;
|
|
41
|
+
const refresh = this.tokens.refresh;
|
|
42
|
+
if (refresh) {
|
|
43
|
+
try {
|
|
44
|
+
this.tokens = await refreshGrant(this.endpoints, refresh, this.now());
|
|
45
|
+
if (this.tokens.refresh !== refresh)
|
|
46
|
+
await this.save(this.tokens.refresh!);
|
|
47
|
+
return this.tokens.access;
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (!(err instanceof OidcError)) throw err;
|
|
50
|
+
this.log(`sign-in for ${issuer} expired: ${err.message}`);
|
|
51
|
+
}
|
|
52
|
+
} else {
|
|
53
|
+
this.log(`sign-in for ${issuer} expired and cannot be refreshed`);
|
|
54
|
+
}
|
|
55
|
+
this.tokens = await this.signIn();
|
|
56
|
+
return this.tokens.access;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class OidcLogins {
|
|
61
|
+
private readonly sessions = new Map<string, Promise<OidcSession>>();
|
|
62
|
+
private readonly options: Required<OidcOptions>;
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
private readonly saved: SavedLogins = new SavedLogins(),
|
|
66
|
+
options: OidcOptions = {},
|
|
67
|
+
) {
|
|
68
|
+
this.options = {
|
|
69
|
+
log: options.log ?? ((line) => console.error(line)),
|
|
70
|
+
sleep: options.sleep ?? ((ms) => Bun.sleep(ms)),
|
|
71
|
+
now: options.now ?? Date.now,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async sessionFor(wsUrl: string): Promise<OidcSession> {
|
|
76
|
+
const endpoints = await discover(wsUrl);
|
|
77
|
+
const key = loginKey(endpoints.issuer, endpoints.clientId);
|
|
78
|
+
let session = this.sessions.get(key);
|
|
79
|
+
if (!session) {
|
|
80
|
+
session = this.login(endpoints, key);
|
|
81
|
+
this.sessions.set(key, session);
|
|
82
|
+
session.catch(() => this.sessions.delete(key));
|
|
83
|
+
}
|
|
84
|
+
const ready = await session;
|
|
85
|
+
await this.saved.addServer(key, serverOf(wsUrl));
|
|
86
|
+
return ready;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private async login(endpoints: Endpoints, key: string): Promise<OidcSession> {
|
|
90
|
+
const { log, now } = this.options;
|
|
91
|
+
const stored = await this.saved.refreshToken(key);
|
|
92
|
+
let tokens: Tokens | undefined;
|
|
93
|
+
if (stored) {
|
|
94
|
+
try {
|
|
95
|
+
tokens = await refreshGrant(endpoints, stored, now());
|
|
96
|
+
log(
|
|
97
|
+
`using saved sign-in for ${endpoints.issuer} as ${who(tokens.access)}`,
|
|
98
|
+
);
|
|
99
|
+
} catch (err) {
|
|
100
|
+
if (!(err instanceof OidcError)) throw err;
|
|
101
|
+
log(`saved sign-in for ${endpoints.issuer} rejected: ${err.message}`);
|
|
102
|
+
await this.saved.remove(key);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const save = (refresh: string) => this.saved.setRefreshToken(key, refresh);
|
|
106
|
+
const signIn = async (): Promise<Tokens> => {
|
|
107
|
+
const fresh = await deviceLogin(endpoints, this.options);
|
|
108
|
+
log(`signed in to ${endpoints.issuer} as ${who(fresh.access)}`);
|
|
109
|
+
if (fresh.refresh) await save(fresh.refresh);
|
|
110
|
+
return fresh;
|
|
111
|
+
};
|
|
112
|
+
if (tokens) {
|
|
113
|
+
if (tokens.refresh && tokens.refresh !== stored)
|
|
114
|
+
await save(tokens.refresh);
|
|
115
|
+
} else {
|
|
116
|
+
tokens = await signIn();
|
|
117
|
+
}
|
|
118
|
+
return new OidcSession(endpoints, tokens, now, log, signIn, save);
|
|
119
|
+
}
|
|
120
|
+
}
|