@n6k.io/serve 0.2.5 → 0.3.0
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 +21 -1
- package/package.json +5 -5
- package/src/assets.ts +1 -17
- package/src/bundle.ts +1 -2
- package/src/cli.ts +70 -9
- package/src/logout.test.ts +65 -0
- package/src/logout.ts +35 -0
- package/src/mcp-instructions.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
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
|
+
}
|
package/src/root.tsx
CHANGED
|
@@ -1,28 +1,47 @@
|
|
|
1
1
|
import { useState, type ReactNode } from "react";
|
|
2
|
-
import { duckdbWorkerUrl, wsWorkerUrl } from "virtual:n6k-workers";
|
|
3
2
|
import { duckdbBundle } from "virtual:n6k-duckdb-bundle";
|
|
4
3
|
import { N6kDuckDB, type DatabaseSpec, type SocketSpec } from "@n6k.io/db";
|
|
5
4
|
import { DuckDBProvider, QueryProvider } from "@n6k.io/ui/duckdb";
|
|
6
5
|
import { ConnectionLost, DuckDBConnectionGuard } from "@n6k.io/runtime";
|
|
7
6
|
import { Page } from "@n6k.io/ui/components";
|
|
8
7
|
|
|
8
|
+
async function fetchToken(alias: string): Promise<string> {
|
|
9
|
+
const waiting = setTimeout(() => {
|
|
10
|
+
console.warn(`${alias}: waiting for sign-in, see the n6k-serve terminal`);
|
|
11
|
+
}, 2000);
|
|
12
|
+
try {
|
|
13
|
+
const res = await fetch(`/_n6k/token/${alias}`, { cache: "no-store" });
|
|
14
|
+
const body = await res.text();
|
|
15
|
+
if (!res.ok) {
|
|
16
|
+
console.error(`${alias}: no token: ${body}`);
|
|
17
|
+
throw new Error(`token for ${alias}: ${body}`);
|
|
18
|
+
}
|
|
19
|
+
return body;
|
|
20
|
+
} finally {
|
|
21
|
+
clearTimeout(waiting);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
9
25
|
function engine(
|
|
10
26
|
data: Record<string, string>,
|
|
11
27
|
tokens: Record<string, string>,
|
|
28
|
+
oidc: string[],
|
|
12
29
|
): N6kDuckDB {
|
|
13
30
|
const sockets: Record<string, SocketSpec> = {};
|
|
14
31
|
const databases: Record<string, DatabaseSpec> = {};
|
|
15
32
|
for (const [alias, url] of Object.entries(data)) {
|
|
16
33
|
sockets[alias] = {
|
|
17
34
|
connect: () => new WebSocket(url),
|
|
18
|
-
token:
|
|
35
|
+
token: oidc.includes(alias)
|
|
36
|
+
? () => fetchToken(alias)
|
|
37
|
+
: Object.hasOwn(tokens, alias)
|
|
38
|
+
? tokens[alias]!
|
|
39
|
+
: "",
|
|
19
40
|
};
|
|
20
41
|
databases[alias] = { socket: alias };
|
|
21
42
|
}
|
|
22
43
|
return new N6kDuckDB({
|
|
23
44
|
bundle: duckdbBundle,
|
|
24
|
-
duckdbWorkerUrl,
|
|
25
|
-
wsWorkerUrl,
|
|
26
45
|
sockets,
|
|
27
46
|
databases,
|
|
28
47
|
});
|
|
@@ -32,14 +51,16 @@ export default function Root({
|
|
|
32
51
|
children,
|
|
33
52
|
data = {},
|
|
34
53
|
tokens = {},
|
|
54
|
+
oidc = [],
|
|
35
55
|
bare = false,
|
|
36
56
|
}: {
|
|
37
57
|
children: ReactNode;
|
|
38
58
|
data?: Record<string, string>;
|
|
39
59
|
tokens?: Record<string, string>;
|
|
60
|
+
oidc?: string[];
|
|
40
61
|
bare?: boolean;
|
|
41
62
|
}) {
|
|
42
|
-
const [duckdb] = useState(() => engine(data, tokens));
|
|
63
|
+
const [duckdb] = useState(() => engine(data, tokens, oidc));
|
|
43
64
|
return (
|
|
44
65
|
<QueryProvider>
|
|
45
66
|
<DuckDBProvider connect={duckdb.connect} metadataFns={duckdb.metadataFns}>
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
export type RefreshStore = {
|
|
2
|
+
get(name: string): Promise<string | null>;
|
|
3
|
+
set(name: string, value: string): Promise<void>;
|
|
4
|
+
delete(name: string): Promise<boolean>;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
const SERVICE = "n6k-serve";
|
|
8
|
+
const INDEX = "index";
|
|
9
|
+
|
|
10
|
+
export const keychain: RefreshStore = {
|
|
11
|
+
get: (name) => Bun.secrets.get({ service: SERVICE, name }),
|
|
12
|
+
set: (name, value) => Bun.secrets.set({ service: SERVICE, name, value }),
|
|
13
|
+
delete: (name) => Bun.secrets.delete({ service: SERVICE, name }),
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type SavedLogin = {
|
|
17
|
+
issuer: string;
|
|
18
|
+
clientId: string;
|
|
19
|
+
servers: string[];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// describe() splits at the last space: a clientId containing a space is misparsed.
|
|
23
|
+
export function loginKey(issuer: string, clientId: string): string {
|
|
24
|
+
return `${issuer} ${clientId}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function serverOf(wsUrl: string): string {
|
|
28
|
+
const url = new URL(wsUrl);
|
|
29
|
+
return `${url.protocol}//${url.host}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function describe(key: string, servers: string[]): SavedLogin {
|
|
33
|
+
const space = key.lastIndexOf(" ");
|
|
34
|
+
return {
|
|
35
|
+
issuer: key.slice(0, space),
|
|
36
|
+
clientId: key.slice(space + 1),
|
|
37
|
+
servers,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Bun.secrets cannot enumerate, so the keys written are tracked in an index entry.
|
|
42
|
+
export class SavedLogins {
|
|
43
|
+
constructor(private readonly store: RefreshStore = keychain) {}
|
|
44
|
+
|
|
45
|
+
private async index(): Promise<Record<string, string[]>> {
|
|
46
|
+
const raw = await this.store.get(INDEX);
|
|
47
|
+
if (!raw) return {};
|
|
48
|
+
try {
|
|
49
|
+
const parsed: unknown = JSON.parse(raw);
|
|
50
|
+
if (typeof parsed !== "object" || parsed === null) return {};
|
|
51
|
+
const out: Record<string, string[]> = {};
|
|
52
|
+
for (const [key, servers] of Object.entries(parsed)) {
|
|
53
|
+
if (Array.isArray(servers))
|
|
54
|
+
out[key] = servers.filter((s) => typeof s === "string");
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
} catch {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private async writeIndex(index: Record<string, string[]>): Promise<void> {
|
|
63
|
+
await (Object.keys(index).length === 0
|
|
64
|
+
? this.store.delete(INDEX)
|
|
65
|
+
: this.store.set(INDEX, JSON.stringify(index)));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
refreshToken(key: string): Promise<string | null> {
|
|
69
|
+
return this.store.get(key);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
setRefreshToken(key: string, refresh: string): Promise<void> {
|
|
73
|
+
return this.store.set(key, refresh);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async addServer(key: string, server: string): Promise<void> {
|
|
77
|
+
const index = await this.index();
|
|
78
|
+
const servers = index[key] ?? [];
|
|
79
|
+
if (servers.includes(server)) return;
|
|
80
|
+
index[key] = [...servers, server];
|
|
81
|
+
await this.writeIndex(index);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async list(): Promise<SavedLogin[]> {
|
|
85
|
+
return Object.entries(await this.index()).map(([key, servers]) =>
|
|
86
|
+
describe(key, servers),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async remove(key: string): Promise<void> {
|
|
91
|
+
await this.store.delete(key);
|
|
92
|
+
const index = await this.index();
|
|
93
|
+
if (!Object.hasOwn(index, key)) return;
|
|
94
|
+
delete index[key];
|
|
95
|
+
await this.writeIndex(index);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async removeForServer(server: string): Promise<SavedLogin | undefined> {
|
|
99
|
+
const index = await this.index();
|
|
100
|
+
const key = Object.keys(index).find((k) => index[k]!.includes(server));
|
|
101
|
+
if (key === undefined) return undefined;
|
|
102
|
+
const removed = describe(key, index[key]!);
|
|
103
|
+
await this.remove(key);
|
|
104
|
+
return removed;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async removeAll(): Promise<SavedLogin[]> {
|
|
108
|
+
const removed = await this.list();
|
|
109
|
+
for (const login of removed)
|
|
110
|
+
await this.store.delete(loginKey(login.issuer, login.clientId));
|
|
111
|
+
await this.store.delete(INDEX);
|
|
112
|
+
return removed;
|
|
113
|
+
}
|
|
114
|
+
}
|