@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/README.md
CHANGED
|
@@ -14,6 +14,26 @@ n6k-serve page.mdx --port 3000 # default 3000
|
|
|
14
14
|
A token in `--data` is removed from the URL and sent as the connection token.
|
|
15
15
|
Frontmatter `attach:` URLs may not carry one.
|
|
16
16
|
|
|
17
|
+
```sh
|
|
18
|
+
n6k-serve page.mdx --data nyc=ws://localhost:8080/ws --oidc-login
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`--oidc-login` signs in to every source without a token, using the server's
|
|
22
|
+
`/.well-known/oauth-protected-resource` and the OAuth device flow (as
|
|
23
|
+
`n6kd auth login`). The refresh token stays in n6k-serve; the page fetches a
|
|
24
|
+
fresh access token on each connect. A source whose server does not offer
|
|
25
|
+
sign-in is an error. The sign-in is saved in the OS credential store and reused
|
|
26
|
+
on the next start.
|
|
27
|
+
|
|
28
|
+
With `--oidc-login`, n6k-serve prints a URL with a per-launch `?secret=`. Open
|
|
29
|
+
that URL: it sets a cookie, and the token route refuses requests without it.
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
n6k-serve logout # list saved sign-ins
|
|
33
|
+
n6k-serve logout ws://localhost:8080 # sign out of the sign-in that server uses
|
|
34
|
+
n6k-serve logout --all # sign out of all
|
|
35
|
+
```
|
|
36
|
+
|
|
17
37
|
Or in the page's frontmatter (`--data` wins for the same alias):
|
|
18
38
|
|
|
19
39
|
```yaml
|
|
@@ -40,6 +60,6 @@ claude mcp add n6k-serve -- bunx @n6k.io/serve --mcp --port 4000
|
|
|
40
60
|
```
|
|
41
61
|
|
|
42
62
|
`--mcp` serves pages at `/<page>/` and is driven over stdio by one MCP client.
|
|
43
|
-
It takes `--port`, `--host` and `--origin
|
|
63
|
+
It takes only `--port`, `--host` and `--origin`. Data
|
|
44
64
|
sources and pages are set with MCP tools (see `tools/list`); frontmatter
|
|
45
65
|
`attach:` is ignored. The process exits when stdin closes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n6k.io/serve",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Serve .mdx pages with live data from n6kd or pykit",
|
|
6
6
|
"repository": "https://github.com/n6k-io/js-serve",
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@duckdb/duckdb-wasm": "1.33.1-dev114.0",
|
|
28
28
|
"@modelcontextprotocol/server": "^2.4.0",
|
|
29
|
-
"@n6k.io/build": "^0.
|
|
30
|
-
"@n6k.io/db": "^0.13.
|
|
31
|
-
"@n6k.io/runtime": "^0.1.
|
|
32
|
-
"@n6k.io/ui": "^0.
|
|
29
|
+
"@n6k.io/build": "^0.6.0",
|
|
30
|
+
"@n6k.io/db": "^0.13.3",
|
|
31
|
+
"@n6k.io/runtime": "^0.1.3",
|
|
32
|
+
"@n6k.io/ui": "^0.11.0",
|
|
33
33
|
"@tailwindcss/node": "^4.3.5",
|
|
34
34
|
"@tailwindcss/oxide": "^4.3.5",
|
|
35
35
|
"@tailwindcss/typography": "^0.5.20",
|
package/src/assets.ts
CHANGED
|
@@ -3,15 +3,12 @@ import { wasmDir } from "@n6k.io/db/wasm-dir";
|
|
|
3
3
|
import {
|
|
4
4
|
N6K_DUCKDB_FILES,
|
|
5
5
|
N6K_WASM_MIME,
|
|
6
|
-
N6K_WORKER_DEV_URLS,
|
|
7
|
-
bundleN6kWorker,
|
|
8
6
|
collectN6kWasmFiles,
|
|
9
7
|
findFontFile,
|
|
10
8
|
n6kDuckDBUrl,
|
|
11
9
|
resolveDuckDBDist,
|
|
12
|
-
resolveN6kWorkerSource,
|
|
13
10
|
} from "@n6k.io/build/pipeline";
|
|
14
|
-
import { SERVE_NODE_MODULES
|
|
11
|
+
import { SERVE_NODE_MODULES } from "./paths";
|
|
15
12
|
|
|
16
13
|
const SAME_ORIGIN = { "Cross-Origin-Resource-Policy": "same-origin" };
|
|
17
14
|
|
|
@@ -50,19 +47,6 @@ export async function serveAsset(
|
|
|
50
47
|
});
|
|
51
48
|
}
|
|
52
49
|
}
|
|
53
|
-
const workerRel = N6K_WORKER_DEV_URLS[pathname];
|
|
54
|
-
if (workerRel) {
|
|
55
|
-
const code = await bundleN6kWorker(
|
|
56
|
-
resolveN6kWorkerSource(workerRel, SERVE_ROOT),
|
|
57
|
-
);
|
|
58
|
-
return new Response(code, {
|
|
59
|
-
headers: {
|
|
60
|
-
"Content-Type": "text/javascript",
|
|
61
|
-
"Cache-Control": "no-store",
|
|
62
|
-
...SAME_ORIGIN,
|
|
63
|
-
},
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
50
|
return undefined;
|
|
67
51
|
}
|
|
68
52
|
|
package/src/bundle.ts
CHANGED
|
@@ -2,7 +2,6 @@ import path from "node:path";
|
|
|
2
2
|
import * as esbuild from "esbuild";
|
|
3
3
|
import {
|
|
4
4
|
n6kDuckDBPlugin,
|
|
5
|
-
n6kWorkersPlugin,
|
|
6
5
|
preprocess,
|
|
7
6
|
virtualModulesPlugin,
|
|
8
7
|
} from "@n6k.io/build/pipeline";
|
|
@@ -19,6 +18,7 @@ export type Bundle = Map<string, string>;
|
|
|
19
18
|
export type RootProps = {
|
|
20
19
|
data: Record<string, string>;
|
|
21
20
|
tokens: Record<string, string>;
|
|
21
|
+
oidc?: string[];
|
|
22
22
|
bare?: boolean;
|
|
23
23
|
};
|
|
24
24
|
|
|
@@ -57,7 +57,6 @@ export async function bundlePage(
|
|
|
57
57
|
logLevel: "silent",
|
|
58
58
|
plugins: [
|
|
59
59
|
virtualModulesPlugin(modules, mdxDir),
|
|
60
|
-
n6kWorkersPlugin(undefined, { used: false }),
|
|
61
60
|
n6kDuckDBPlugin(undefined, { used: false }),
|
|
62
61
|
],
|
|
63
62
|
alias: {
|
package/src/cli.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { hasWasmExtensions } from "./assets";
|
|
|
10
10
|
import { parsePages, type PagesConfig } from "./pages";
|
|
11
11
|
import { PagesSite } from "./pages-site";
|
|
12
12
|
import {
|
|
13
|
+
SECRET_PARAM,
|
|
13
14
|
reloadPage,
|
|
14
15
|
startServer,
|
|
15
16
|
type PageState,
|
|
@@ -19,13 +20,16 @@ import {
|
|
|
19
20
|
} from "./server";
|
|
20
21
|
import { watchFile } from "./watch";
|
|
21
22
|
import { McpSite, startMcp } from "./mcp";
|
|
23
|
+
import { OidcError, OidcLogins, type OidcSession } from "./oidc";
|
|
24
|
+
import { LogoutError, logout } from "./logout";
|
|
22
25
|
import { SRC_DIR } from "./paths";
|
|
23
26
|
import pkg from "../package.json";
|
|
24
27
|
|
|
25
|
-
const USAGE = `usage: n6k-serve <page.mdx> [--data [alias=]ws://…]... [options]
|
|
28
|
+
const USAGE = `usage: n6k-serve <page.mdx> [--data [alias=]ws://…]... [--oidc-login] [options]
|
|
26
29
|
n6k-serve --pages <pages.yml> [options]
|
|
27
|
-
n6k-serve sql [--console] [--data [alias=]ws://…]... [options]
|
|
30
|
+
n6k-serve sql [--console] [--data [alias=]ws://…]... [--oidc-login] [options]
|
|
28
31
|
n6k-serve --mcp [options]
|
|
32
|
+
n6k-serve logout [ws://host[:port] | --all]
|
|
29
33
|
options: [--port 3000] [--host 127.0.0.1] [--origin <origin>]...`;
|
|
30
34
|
|
|
31
35
|
function fail(message: string): never {
|
|
@@ -40,6 +44,8 @@ const { values, positionals } = parseArgs({
|
|
|
40
44
|
pages: { type: "string" },
|
|
41
45
|
mcp: { type: "boolean", default: false },
|
|
42
46
|
console: { type: "boolean", default: false },
|
|
47
|
+
"oidc-login": { type: "boolean", default: false },
|
|
48
|
+
all: { type: "boolean", default: false },
|
|
43
49
|
port: { type: "string", default: "3000" },
|
|
44
50
|
host: { type: "string", default: "127.0.0.1" },
|
|
45
51
|
origin: { type: "string", multiple: true, default: [] },
|
|
@@ -48,6 +54,20 @@ const { values, positionals } = parseArgs({
|
|
|
48
54
|
strict: true,
|
|
49
55
|
});
|
|
50
56
|
|
|
57
|
+
if (positionals[0] === "logout") {
|
|
58
|
+
if (positionals.length > 2 || (values.all && positionals.length === 2))
|
|
59
|
+
fail(USAGE);
|
|
60
|
+
try {
|
|
61
|
+
for (const out of await logout(positionals[1], values.all))
|
|
62
|
+
console.error(out);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
if (err instanceof LogoutError) fail(err.message);
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
process.exit(0);
|
|
68
|
+
}
|
|
69
|
+
if (values.all) fail(USAGE);
|
|
70
|
+
|
|
51
71
|
const port = Number(values.port);
|
|
52
72
|
if (!Number.isInteger(port) || port < 0)
|
|
53
73
|
fail(`--port ${values.port}: not a port`);
|
|
@@ -61,6 +81,8 @@ const options: ServeOptions = {
|
|
|
61
81
|
};
|
|
62
82
|
|
|
63
83
|
if (values.console && positionals[0] !== "sql") fail(USAGE);
|
|
84
|
+
if (values["oidc-login"] && (values.mcp || values.pages !== undefined))
|
|
85
|
+
fail(USAGE);
|
|
64
86
|
|
|
65
87
|
if (positionals[0] === "sql") {
|
|
66
88
|
if (positionals.length !== 1 || values.mcp || values.pages !== undefined)
|
|
@@ -90,18 +112,32 @@ async function servePage(arg: string, bare = false): Promise<void> {
|
|
|
90
112
|
if (!mdxPath.endsWith(".mdx")) fail(`${arg}: not an .mdx file`);
|
|
91
113
|
if (!existsSync(mdxPath)) fail(`${arg}: no such file`);
|
|
92
114
|
const dataFlags = values.data;
|
|
115
|
+
const logins = values["oidc-login"] ? new OidcLogins() : undefined;
|
|
116
|
+
|
|
117
|
+
const login = async (
|
|
118
|
+
sources: Record<string, DataSource>,
|
|
119
|
+
): Promise<Map<string, OidcSession>> => {
|
|
120
|
+
const out = new Map<string, OidcSession>();
|
|
121
|
+
if (!logins) return out;
|
|
122
|
+
for (const [alias, { url, token }] of Object.entries(sources)) {
|
|
123
|
+
if (token === "") out.set(alias, await logins.sessionFor(url));
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
};
|
|
93
127
|
|
|
94
128
|
const resolveDataFor = (): Record<string, DataSource> =>
|
|
95
129
|
resolveData(parseAttachUrls(readFileSync(mdxPath, "utf8")), dataFlags);
|
|
96
130
|
|
|
97
131
|
const build = async (
|
|
98
132
|
sources: Record<string, DataSource>,
|
|
133
|
+
oidc: string[],
|
|
99
134
|
): Promise<PageState> => {
|
|
100
135
|
const entries = Object.entries(sources);
|
|
101
136
|
const [bundle, css] = await Promise.all([
|
|
102
137
|
bundlePage(mdxPath, {
|
|
103
138
|
data: Object.fromEntries(entries.map(([a, s]) => [a, s.url])),
|
|
104
139
|
tokens: Object.fromEntries(entries.map(([a, s]) => [a, s.token])),
|
|
140
|
+
oidc,
|
|
105
141
|
bare,
|
|
106
142
|
}),
|
|
107
143
|
buildCss(mdxPath),
|
|
@@ -110,13 +146,16 @@ async function servePage(arg: string, bare = false): Promise<void> {
|
|
|
110
146
|
};
|
|
111
147
|
|
|
112
148
|
let data: Record<string, DataSource>;
|
|
149
|
+
let sessions: Map<string, OidcSession>;
|
|
113
150
|
try {
|
|
114
151
|
data = resolveDataFor();
|
|
152
|
+
sessions = await login(data);
|
|
115
153
|
} catch (err) {
|
|
116
|
-
if (err instanceof DataArgError
|
|
154
|
+
if (err instanceof DataArgError || err instanceof OidcError)
|
|
155
|
+
fail(err.message);
|
|
117
156
|
throw err;
|
|
118
157
|
}
|
|
119
|
-
let state = await build(data);
|
|
158
|
+
let state = await build(data, [...sessions.keys()]);
|
|
120
159
|
const page: ServedPage = {
|
|
121
160
|
title: path.basename(mdxPath),
|
|
122
161
|
key: "",
|
|
@@ -126,18 +165,40 @@ async function servePage(arg: string, bare = false): Promise<void> {
|
|
|
126
165
|
resolve: (pathname) => ({ kind: "page", page, rest: pathname }),
|
|
127
166
|
page: (key) => (key === "" ? page : undefined),
|
|
128
167
|
};
|
|
129
|
-
const
|
|
168
|
+
const secret = logins
|
|
169
|
+
? Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(
|
|
170
|
+
"base64url",
|
|
171
|
+
)
|
|
172
|
+
: undefined;
|
|
173
|
+
const server = startServer(site, {
|
|
174
|
+
...options,
|
|
175
|
+
token: (alias) => sessions.get(alias)?.token(),
|
|
176
|
+
secret,
|
|
177
|
+
});
|
|
130
178
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
179
|
+
const url = new URL(server.url);
|
|
180
|
+
if (secret) url.searchParams.set(SECRET_PARAM, secret);
|
|
181
|
+
console.error(`n6k-serve ${url}`);
|
|
182
|
+
const flagged = new Set(Object.keys(resolveData({}, dataFlags)));
|
|
183
|
+
const rows = Object.entries(data).map(([alias, { url }]) => {
|
|
184
|
+
const tags = [flagged.has(alias) ? "--data" : "attach:"];
|
|
185
|
+
if (sessions.has(alias)) tags.push("oidc");
|
|
186
|
+
return [`${alias}=${url}`, `(${tags.join(", ")})`];
|
|
187
|
+
});
|
|
188
|
+
if (rows.length > 0) {
|
|
189
|
+
const width = Math.max(...rows.map(([entry]) => entry!.length));
|
|
190
|
+
console.error("\ndata:");
|
|
191
|
+
for (const [entry, tags] of rows)
|
|
192
|
+
console.error(` ${entry!.padEnd(width)} ${tags}`);
|
|
134
193
|
}
|
|
135
194
|
|
|
136
195
|
watchFile(mdxPath, async () => {
|
|
137
196
|
try {
|
|
138
197
|
const nextData = resolveDataFor();
|
|
139
|
-
|
|
198
|
+
const nextSessions = await login(nextData);
|
|
199
|
+
state = await build(nextData, [...nextSessions.keys()]);
|
|
140
200
|
data = nextData;
|
|
201
|
+
sessions = nextSessions;
|
|
141
202
|
reloadPage(server, "");
|
|
142
203
|
console.error(`rebuilt ${path.basename(mdxPath)}`);
|
|
143
204
|
} catch (err) {
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { LogoutError, logout } from "./logout";
|
|
3
|
+
import { SavedLogins, type RefreshStore } from "./saved-logins";
|
|
4
|
+
|
|
5
|
+
async function seeded() {
|
|
6
|
+
const saved = new Map<string, string>();
|
|
7
|
+
const store: RefreshStore = {
|
|
8
|
+
get: async (name) => saved.get(name) ?? null,
|
|
9
|
+
set: async (name, value) => {
|
|
10
|
+
saved.set(name, value);
|
|
11
|
+
},
|
|
12
|
+
delete: async (name) => saved.delete(name),
|
|
13
|
+
};
|
|
14
|
+
const logins = new SavedLogins(store);
|
|
15
|
+
await logins.setRefreshToken("http://kc/realms/a cli", "ra");
|
|
16
|
+
await logins.addServer("http://kc/realms/a cli", "ws://h1:8080");
|
|
17
|
+
await logins.addServer("http://kc/realms/a cli", "ws://h2:8080");
|
|
18
|
+
await logins.setRefreshToken("http://kc/realms/b cli", "rb");
|
|
19
|
+
await logins.addServer("http://kc/realms/b cli", "wss://h3");
|
|
20
|
+
return { saved, logins };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
test("no server lists sign-ins and deletes nothing", async () => {
|
|
24
|
+
const { saved, logins } = await seeded();
|
|
25
|
+
expect(await logout(undefined, false, logins)).toEqual([
|
|
26
|
+
"saved sign-ins:",
|
|
27
|
+
" http://kc/realms/a (client cli): ws://h1:8080, ws://h2:8080",
|
|
28
|
+
" http://kc/realms/b (client cli): wss://h3",
|
|
29
|
+
"",
|
|
30
|
+
"sign out with: n6k-serve logout ws://host[:port] | --all",
|
|
31
|
+
]);
|
|
32
|
+
expect(saved.get("http://kc/realms/a cli")).toBe("ra");
|
|
33
|
+
expect(saved.get("http://kc/realms/b cli")).toBe("rb");
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("a server removes only the sign-in it uses", async () => {
|
|
37
|
+
const { saved, logins } = await seeded();
|
|
38
|
+
expect(await logout("ws://h1:8080/ws", false, logins)).toEqual([
|
|
39
|
+
"signed out of:",
|
|
40
|
+
" http://kc/realms/a (client cli): ws://h1:8080, ws://h2:8080",
|
|
41
|
+
]);
|
|
42
|
+
expect(saved.has("http://kc/realms/a cli")).toBe(false);
|
|
43
|
+
expect(saved.get("http://kc/realms/b cli")).toBe("rb");
|
|
44
|
+
const left = await logins.list();
|
|
45
|
+
expect(left.map((l) => l.issuer)).toEqual(["http://kc/realms/b"]);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("an unknown server or bad URL is an error", async () => {
|
|
49
|
+
const { logins } = await seeded();
|
|
50
|
+
await expect(logout("ws://other/ws", false, logins)).rejects.toThrow(
|
|
51
|
+
new LogoutError("no saved sign-in for ws://other"),
|
|
52
|
+
);
|
|
53
|
+
await expect(logout("http://h1:8080", false, logins)).rejects.toThrow(
|
|
54
|
+
LogoutError,
|
|
55
|
+
);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("--all removes every sign-in and the index", async () => {
|
|
59
|
+
const { saved, logins } = await seeded();
|
|
60
|
+
const out = await logout(undefined, true, logins);
|
|
61
|
+
expect(out[0]).toBe("signed out of:");
|
|
62
|
+
expect(out).toHaveLength(3);
|
|
63
|
+
expect(saved.size).toBe(0);
|
|
64
|
+
expect(await logout(undefined, false, logins)).toEqual(["no saved sign-ins"]);
|
|
65
|
+
});
|
package/src/logout.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { SavedLogins, serverOf, type SavedLogin } from "./saved-logins";
|
|
2
|
+
|
|
3
|
+
export class LogoutError extends Error {}
|
|
4
|
+
|
|
5
|
+
function line({ issuer, clientId, servers }: SavedLogin): string {
|
|
6
|
+
return ` ${issuer} (client ${clientId}): ${servers.join(", ")}`;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export async function logout(
|
|
10
|
+
server: string | undefined,
|
|
11
|
+
all: boolean,
|
|
12
|
+
saved: SavedLogins = new SavedLogins(),
|
|
13
|
+
): Promise<string[]> {
|
|
14
|
+
if (all) {
|
|
15
|
+
const removed = await saved.removeAll();
|
|
16
|
+
if (removed.length === 0) return ["no saved sign-ins"];
|
|
17
|
+
return ["signed out of:", ...removed.map((l) => line(l))];
|
|
18
|
+
}
|
|
19
|
+
if (server === undefined) {
|
|
20
|
+
const logins = await saved.list();
|
|
21
|
+
if (logins.length === 0) return ["no saved sign-ins"];
|
|
22
|
+
return [
|
|
23
|
+
"saved sign-ins:",
|
|
24
|
+
...logins.map((l) => line(l)),
|
|
25
|
+
"",
|
|
26
|
+
"sign out with: n6k-serve logout ws://host[:port] | --all",
|
|
27
|
+
];
|
|
28
|
+
}
|
|
29
|
+
if (!/^wss?:\/\//.test(server) || !URL.canParse(server))
|
|
30
|
+
throw new LogoutError(`${server}: not a ws:// or wss:// URL`);
|
|
31
|
+
const removed = await saved.removeForServer(serverOf(server));
|
|
32
|
+
if (!removed)
|
|
33
|
+
throw new LogoutError(`no saved sign-in for ${serverOf(server)}`);
|
|
34
|
+
return ["signed out of:", line(removed)];
|
|
35
|
+
}
|
package/src/mcp-instructions.ts
CHANGED
|
@@ -19,4 +19,4 @@ Controls
|
|
|
19
19
|
<SelectContent><SelectItem value="2020-09">Sep 2020</SelectItem></SelectContent>
|
|
20
20
|
:::
|
|
21
21
|
- The bracketed name is a variable usable in expressions, e.g. filters={{ category }} or query={\`SELECT … LIMIT \${sims}\`}.
|
|
22
|
-
- Attributes are strings coerced to numbers/booleans; \`options\` and \`default\`
|
|
22
|
+
- Attributes are strings coerced to numbers/booleans; \`options\` and \`default\` containing a comma become lists; an option "value:label" sets a separate label.`;
|
|
@@ -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
|
+
}
|