@clegra/sdk 0.0.0-stage → 0.1.0-next.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/CHANGELOG.md +158 -0
- package/LICENSE +21 -0
- package/NOTICE.md +25 -0
- package/README.md +258 -2
- package/dist/spec/kinds.json +211 -0
- package/dist/spec/schema/clegra.schema.json +1249 -0
- package/dist/spec/src/cli.d.ts +2 -0
- package/dist/spec/src/cli.js +21 -0
- package/dist/spec/src/cli.js.map +1 -0
- package/dist/spec/src/conformance.d.ts +34 -0
- package/dist/spec/src/conformance.js +704 -0
- package/dist/spec/src/conformance.js.map +1 -0
- package/dist/spec/src/init/index.d.ts +31 -0
- package/dist/spec/src/init/index.js +151 -0
- package/dist/spec/src/init/index.js.map +1 -0
- package/dist/spec/src/init/next-config.d.ts +19 -0
- package/dist/spec/src/init/next-config.js +77 -0
- package/dist/spec/src/init/next-config.js.map +1 -0
- package/dist/spec/src/init/project.d.ts +44 -0
- package/dist/spec/src/init/project.js +141 -0
- package/dist/spec/src/init/project.js.map +1 -0
- package/dist/spec/src/init/templates.d.ts +20 -0
- package/dist/spec/src/init/templates.js +166 -0
- package/dist/spec/src/init/templates.js.map +1 -0
- package/dist/spec/src/init/ui.d.ts +30 -0
- package/dist/spec/src/init/ui.js +82 -0
- package/dist/spec/src/init/ui.js.map +1 -0
- package/dist/spec/src/kinds.d.ts +89 -0
- package/dist/spec/src/kinds.js +319 -0
- package/dist/spec/src/kinds.js.map +1 -0
- package/dist/spec/src/protocol.d.ts +50 -0
- package/dist/spec/src/protocol.js +52 -0
- package/dist/spec/src/protocol.js.map +1 -0
- package/dist/spec/src/rules.d.ts +132 -0
- package/dist/spec/src/rules.js +282 -0
- package/dist/spec/src/rules.js.map +1 -0
- package/dist/src/auth.d.ts +371 -0
- package/dist/src/auth.js +964 -0
- package/dist/src/auth.js.map +1 -0
- package/dist/src/define.d.ts +249 -0
- package/dist/src/define.js +83 -0
- package/dist/src/define.js.map +1 -0
- package/dist/src/embed.d.ts +98 -0
- package/dist/src/embed.js +256 -0
- package/dist/src/embed.js.map +1 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +11 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/labels.d.ts +10 -0
- package/dist/src/labels.js +22 -0
- package/dist/src/labels.js.map +1 -0
- package/dist/src/manifest.d.ts +499 -0
- package/dist/src/manifest.js +188 -0
- package/dist/src/manifest.js.map +1 -0
- package/dist/src/meaning.d.ts +64 -0
- package/dist/src/meaning.js +116 -0
- package/dist/src/meaning.js.map +1 -0
- package/dist/src/next/index.d.ts +101 -0
- package/dist/src/next/index.js +187 -0
- package/dist/src/next/index.js.map +1 -0
- package/dist/src/node.d.ts +14 -0
- package/dist/src/node.js +64 -0
- package/dist/src/node.js.map +1 -0
- package/dist/src/server.d.ts +229 -0
- package/dist/src/server.js +2256 -0
- package/dist/src/server.js.map +1 -0
- package/dist/src/store.d.ts +129 -0
- package/dist/src/store.js +213 -0
- package/dist/src/store.js.map +1 -0
- package/dist/src/testing.d.ts +133 -0
- package/dist/src/testing.js +81 -0
- package/dist/src/testing.js.map +1 -0
- package/dist/src/types.d.ts +352 -0
- package/dist/src/types.js +2 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/view.d.ts +35 -0
- package/dist/src/view.js +442 -0
- package/dist/src/view.js.map +1 -0
- package/docs/quickstart.md +350 -0
- package/docs/spec.md +997 -0
- package/package.json +89 -4
package/dist/src/auth.js
ADDED
|
@@ -0,0 +1,964 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
3
|
+
import { isIP } from "node:net";
|
|
4
|
+
import { createLocalJWKSet, createRemoteJWKSet, decodeJwt, decodeProtectedHeader, exportJWK, generateKeyPair, importJWK, jwtVerify, SignJWT, } from "jose";
|
|
5
|
+
import { CONFIRMATION_TYPE, OAUTH_SCOPE, PROTOCOL_ID, TOKEN_CLAIM } from "../spec/src/protocol.js";
|
|
6
|
+
/**
|
|
7
|
+
* AUTH (spec §7). Two kinds of access token reach an app:
|
|
8
|
+
*
|
|
9
|
+
* - **its own** (the common case: a web app with its own users): issued by
|
|
10
|
+
* the app's own authorization server (better-auth, Clerk, …) to an MCP
|
|
11
|
+
* client such as ChatGPT, Claude or Clegra. The SDK does not read them: the
|
|
12
|
+
* app verifies them in `auth.resolve(token, request, { resource })` and says
|
|
13
|
+
* who is calling (installation, person, permissions).
|
|
14
|
+
* - **a workspace host's** (in-house apps a company installs into its own
|
|
15
|
+
* host): JWTs (`typ: at+jwt`) from a trusted issuer listed in
|
|
16
|
+
* `auth.issuers`,
|
|
17
|
+
* verified with the issuer's JWKS. Their audience is this server's own
|
|
18
|
+
* public MCP address (`auth.resource`, RFC 8707): a token signed for another
|
|
19
|
+
* app is refused whatever that app calls itself. The `clegra` claim says
|
|
20
|
+
* who is calling for which installation; the tenant handlers see is the
|
|
21
|
+
* installation of that issuer (`<installation>@<issuer>`), so one issuer
|
|
22
|
+
* can never name another's. A workspace host's token is for one request
|
|
23
|
+
* (60 seconds, used once). A workspace host proves a person's confirmation
|
|
24
|
+
* with a second JWT (`clegra-confirm+jwt`) bound to the installation, the
|
|
25
|
+
* call and the arguments as sent.
|
|
26
|
+
*
|
|
27
|
+
* Dev mode: the SDK is its own authorization server with a local key
|
|
28
|
+
* (DevAuthority below), for callers on a loopback address only.
|
|
29
|
+
*/
|
|
30
|
+
export { CONFIRMATION_TYPE };
|
|
31
|
+
export const DEV_ISSUER = `${PROTOCOL_ID}-dev`;
|
|
32
|
+
/** The `typ` of an access token (RFC 9068). */
|
|
33
|
+
export const ACCESS_TOKEN_TYPE = "at+jwt";
|
|
34
|
+
/** How long a workspace host's access token may live: it is for one request. */
|
|
35
|
+
export const HOST_TOKEN_SECONDS = 60;
|
|
36
|
+
export const INSTALLATION = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
37
|
+
/** The tenant of a caller: the installation as its issuer names it, bound to that issuer. */
|
|
38
|
+
export const tenantOf = (installation, issuer) => `${installation}@${issuer}`;
|
|
39
|
+
export class AuthError extends Error {
|
|
40
|
+
constructor(message) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.name = "AuthError";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
// ------------------------------------------------------------ hashing
|
|
46
|
+
/** JSON with object keys sorted at every depth: what `args` hashes. */
|
|
47
|
+
export function canonicalJson(value) {
|
|
48
|
+
if (value === null || typeof value !== "object")
|
|
49
|
+
return JSON.stringify(value) ?? "null";
|
|
50
|
+
if (Array.isArray(value))
|
|
51
|
+
return `[${value.map((v) => canonicalJson(v === undefined ? null : v)).join(",")}]`;
|
|
52
|
+
const entries = Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
53
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
|
|
54
|
+
}
|
|
55
|
+
/** base64url SHA-256 of the arguments' canonical JSON (the proof's `args`). */
|
|
56
|
+
export function argsHash(args) {
|
|
57
|
+
return createHash("sha256").update(canonicalJson(args ?? {})).digest("base64url");
|
|
58
|
+
}
|
|
59
|
+
export class TokenVerifier {
|
|
60
|
+
#issuers = new Map();
|
|
61
|
+
#resource;
|
|
62
|
+
#once;
|
|
63
|
+
#dev = null;
|
|
64
|
+
constructor(options, once) {
|
|
65
|
+
this.#once = once;
|
|
66
|
+
this.#resource = options.resource ?? null;
|
|
67
|
+
for (const i of options.issuers ?? []) {
|
|
68
|
+
if (!i.issuer)
|
|
69
|
+
throw new Error("auth.issuers: every issuer needs its `issuer`");
|
|
70
|
+
const keys = i.jwks ? createLocalJWKSet(i.jwks) : createRemoteJWKSet(new URL(i.jwksUri ?? `${i.issuer.replace(/\/+$/, "")}/.well-known/jwks.json`), { cooldownDuration: 30_000, cacheMaxAge: 10 * 60_000 });
|
|
71
|
+
this.#issuers.set(i.issuer, keys);
|
|
72
|
+
}
|
|
73
|
+
if (this.#issuers.size && !this.#resource)
|
|
74
|
+
throw new Error("auth.resource: with issuers, give this server's public MCP address (https://…/mcp); it is the only audience their tokens are accepted for");
|
|
75
|
+
if (this.#resource) {
|
|
76
|
+
let url;
|
|
77
|
+
try {
|
|
78
|
+
url = new URL(this.#resource);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new Error(`auth.resource: "${this.#resource}" is not a URL`);
|
|
82
|
+
}
|
|
83
|
+
if (!/^https?:$/.test(url.protocol) || url.hash || url.search)
|
|
84
|
+
throw new Error(`auth.resource: "${this.#resource}" must be an http(s) URL without query or fragment`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
useDev(dev) {
|
|
88
|
+
this.#dev = dev;
|
|
89
|
+
}
|
|
90
|
+
/** Whether a token is one this verifier answers for (a JWT whose `iss` is a configured issuer or the dev authority's), so it is never handed to `auth.resolve`. */
|
|
91
|
+
knows(token) {
|
|
92
|
+
let iss;
|
|
93
|
+
try {
|
|
94
|
+
iss = decodeJwt(token).iss;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
return Boolean(iss && (this.#issuers.has(iss) || this.#dev?.issues(iss)));
|
|
100
|
+
}
|
|
101
|
+
/** The keys and the audiences of an issuer for this request; why not, as an AuthError. */
|
|
102
|
+
#trustOf(iss, trust) {
|
|
103
|
+
// A configured issuer always keeps its own keys: the dev authority's names come from request headers and must never shadow one.
|
|
104
|
+
const configured = iss ? this.#issuers.get(iss) : undefined;
|
|
105
|
+
if (configured)
|
|
106
|
+
return { keys: configured, audience: [this.#resource], issuer: iss };
|
|
107
|
+
if (this.#dev && iss && this.#dev.issues(iss)) {
|
|
108
|
+
if (!trust.dev)
|
|
109
|
+
throw new AuthError("dev sign-in answers callers on a loopback address only");
|
|
110
|
+
// Every name the dev authority answers under is one authority, one tenant space.
|
|
111
|
+
return { keys: this.#dev.publicKey, audience: [DEV_ISSUER, ...(trust.requestResource ? [trust.requestResource] : [])], issuer: DEV_ISSUER };
|
|
112
|
+
}
|
|
113
|
+
throw new AuthError(`untrusted issuer ${iss ?? "(none)"}`);
|
|
114
|
+
}
|
|
115
|
+
/** The caller an access token names. Throws AuthError with the reason. */
|
|
116
|
+
async verify(token, trust) {
|
|
117
|
+
let iss;
|
|
118
|
+
try {
|
|
119
|
+
iss = decodeJwt(token).iss;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw new AuthError("malformed token");
|
|
123
|
+
}
|
|
124
|
+
const { keys, audience, issuer } = this.#trustOf(iss, trust);
|
|
125
|
+
let payload;
|
|
126
|
+
try {
|
|
127
|
+
;
|
|
128
|
+
({ payload } = await jwtVerify(token, keys, { typ: ACCESS_TOKEN_TYPE, audience, clockTolerance: 30, requiredClaims: ["exp", "sub", "aud"] }));
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
const message = error instanceof Error ? error.message : "invalid token";
|
|
132
|
+
throw new AuthError(/"aud"/.test(message) ? `the token is for another server (this one is ${audience.join(" or ")})` : message);
|
|
133
|
+
}
|
|
134
|
+
const m = payload[TOKEN_CLAIM];
|
|
135
|
+
if (!m || typeof m.installation !== "string" || !INSTALLATION.test(m.installation))
|
|
136
|
+
throw new AuthError(`the token has no valid ${TOKEN_CLAIM}.installation`);
|
|
137
|
+
const host = m.host === "workspace" ? "workspace" : "plain";
|
|
138
|
+
if (host === "workspace") {
|
|
139
|
+
// A workspace host signs a token per request: short, with an id, used once.
|
|
140
|
+
if (typeof payload.jti !== "string" || !payload.jti || typeof payload.iat !== "number")
|
|
141
|
+
throw new AuthError("a workspace host's token needs jti and iat");
|
|
142
|
+
if (payload.exp - payload.iat > HOST_TOKEN_SECONDS)
|
|
143
|
+
throw new AuthError(`a workspace host's token lives ${HOST_TOKEN_SECONDS} seconds at most`);
|
|
144
|
+
const left = Math.max(1, payload.exp + 30 - Math.floor(Date.now() / 1000));
|
|
145
|
+
if (!(await this.#once(`jti:${issuer}:${payload.jti}`, left * 1000)))
|
|
146
|
+
throw new AuthError("this token was already used (a workspace host's token is for one request)");
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
installation: tenantOf(m.installation, issuer),
|
|
150
|
+
installationId: m.installation,
|
|
151
|
+
person: m.person && typeof m.person.id === "string" ? { id: m.person.id, name: String(m.person.name ?? "") } : null,
|
|
152
|
+
permissions: new Set(Array.isArray(m.permissions) ? m.permissions.filter((p) => typeof p === "string") : []),
|
|
153
|
+
...(typeof m.locale === "string" ? { locale: m.locale } : {}),
|
|
154
|
+
host,
|
|
155
|
+
issuer: iss,
|
|
156
|
+
subject: String(payload.sub ?? ""),
|
|
157
|
+
claims: payload,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Checks a confirmation proof for this caller, installation, tool, arguments (as received), call id and, for a
|
|
162
|
+
* later run, its deadline (`until`, epoch seconds). `at`: verify it as of that moment (a stored proof, checked
|
|
163
|
+
* again when its run is due, at its confirmation time). Gives the proof's `iat` when it holds, else why not.
|
|
164
|
+
*/
|
|
165
|
+
async checkConfirmation(proof, expected, trust, at) {
|
|
166
|
+
const no = (why) => ({ ok: false, why });
|
|
167
|
+
try {
|
|
168
|
+
const { keys, audience } = this.#trustOf(expected.issuer, trust);
|
|
169
|
+
const { payload } = await jwtVerify(proof, keys, { typ: CONFIRMATION_TYPE, issuer: expected.issuer, audience, clockTolerance: 30, ...(at ? { currentDate: at } : {}) });
|
|
170
|
+
if (typeof payload.iat !== "number" || typeof payload.exp !== "number" || payload.exp - payload.iat > 300)
|
|
171
|
+
return no("a proof lives 5 minutes at most");
|
|
172
|
+
if (payload.sub !== expected.subject)
|
|
173
|
+
return no("the proof is for someone else");
|
|
174
|
+
if (payload.installation !== expected.installation)
|
|
175
|
+
return no("the proof is for another installation");
|
|
176
|
+
if (payload.tool !== expected.tool)
|
|
177
|
+
return no("the proof is for another tool");
|
|
178
|
+
if (payload.args !== argsHash(expected.args))
|
|
179
|
+
return no("the proof is for other arguments");
|
|
180
|
+
if (!expected.call || payload.call !== expected.call)
|
|
181
|
+
return no("the proof is for another call");
|
|
182
|
+
if (expected.until !== undefined && payload.until !== expected.until)
|
|
183
|
+
return no("the proof is for another deadline");
|
|
184
|
+
return { ok: true, iat: payload.iat };
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
return no(error instanceof Error ? error.message : "invalid proof");
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
// ------------------------------------------------------------ signing (hosts, tests, dev)
|
|
192
|
+
/** A later run's deadline, epoch seconds: its `at` (a date-time string) plus `window` minutes, rounded down. NaN when `at` is not a date-time. */
|
|
193
|
+
export function laterDeadline(at, windowMinutes) {
|
|
194
|
+
return Math.floor(Date.parse(at) / 1000 + windowMinutes * 60);
|
|
195
|
+
}
|
|
196
|
+
export async function generateSigningKey() {
|
|
197
|
+
const { privateKey, publicKey } = await generateKeyPair("EdDSA", { crv: "Ed25519", extractable: true });
|
|
198
|
+
const publicJwk = await exportJWK(publicKey);
|
|
199
|
+
const kid = createHash("sha256").update(String(publicJwk.x)).digest("base64url").slice(0, 16);
|
|
200
|
+
return { privateKey, publicJwk: { ...publicJwk, kid, alg: "EdDSA", use: "sig" }, kid };
|
|
201
|
+
}
|
|
202
|
+
/** An access token as a host or the dev authority signs it. */
|
|
203
|
+
export async function signAccessToken(key, claims) {
|
|
204
|
+
const now = Math.floor(Date.now() / 1000);
|
|
205
|
+
return new SignJWT({ [TOKEN_CLAIM]: claims.clegra, ...(claims.scope ? { scope: claims.scope } : {}) })
|
|
206
|
+
.setProtectedHeader({ alg: "EdDSA", typ: ACCESS_TOKEN_TYPE, kid: key.kid })
|
|
207
|
+
.setIssuer(claims.iss)
|
|
208
|
+
.setAudience(claims.aud)
|
|
209
|
+
.setSubject(claims.sub)
|
|
210
|
+
.setIssuedAt(now)
|
|
211
|
+
.setExpirationTime(now + (claims.lifetimeSeconds ?? 3600))
|
|
212
|
+
.setJti(randomUUID())
|
|
213
|
+
.sign(key.privateKey);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* A confirmation proof (spec §7): the person confirmed exactly these arguments, as sent, for this call of this
|
|
217
|
+
* installation. `until` (epoch seconds), for an action with `later`: the run's deadline, `at` + `window` minutes
|
|
218
|
+
* (`laterDeadline`).
|
|
219
|
+
*/
|
|
220
|
+
export async function signConfirmation(key, claims) {
|
|
221
|
+
const now = Math.floor(Date.now() / 1000);
|
|
222
|
+
return new SignJWT({ installation: claims.installation, tool: claims.tool, args: argsHash(claims.args), call: claims.call, ...(claims.until !== undefined ? { until: claims.until } : {}) })
|
|
223
|
+
.setProtectedHeader({ alg: "EdDSA", typ: CONFIRMATION_TYPE, kid: key.kid })
|
|
224
|
+
.setIssuer(claims.iss)
|
|
225
|
+
.setAudience(claims.aud)
|
|
226
|
+
.setSubject(claims.sub)
|
|
227
|
+
.setIssuedAt(now)
|
|
228
|
+
.setExpirationTime(now + Math.min(claims.lifetimeSeconds ?? 120, 300))
|
|
229
|
+
.sign(key.privateKey);
|
|
230
|
+
}
|
|
231
|
+
// ------------------------------------------------------------ the dev authority
|
|
232
|
+
const LOOPBACK = /^(127\.\d+\.\d+\.\d+|::1|::ffff:127\.\d+\.\d+\.\d+|localhost)$/;
|
|
233
|
+
export function isLoopback(host) {
|
|
234
|
+
return typeof host === "string" && LOOPBACK.test(host);
|
|
235
|
+
}
|
|
236
|
+
const DEV_CODE_TYPE = `${PROTOCOL_ID}-dev-code+jwt`;
|
|
237
|
+
const DEV_REFRESH_TYPE = `${PROTOCOL_ID}-dev-refresh+jwt`;
|
|
238
|
+
/** Wrong sign-in codes before the dev sign-in closes until the app restarts. */
|
|
239
|
+
export const DEV_CODE_ATTEMPTS = 5;
|
|
240
|
+
const html = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
241
|
+
// ------------------------------------------------------------ client id metadata documents
|
|
242
|
+
/**
|
|
243
|
+
* A client may identify itself with the https URL of a JSON document that
|
|
244
|
+
* describes it (OAuth Client ID Metadata Documents, what MCP clients use
|
|
245
|
+
* since the 2025-11-25 authorization spec). The server fetches a URL that
|
|
246
|
+
* whoever opens the sign-in page chose (through a tunnel that is anyone), so
|
|
247
|
+
* the fetch must never reach this machine or its network: everything below
|
|
248
|
+
* that refuses an address is there for that.
|
|
249
|
+
*/
|
|
250
|
+
/** How a client with a key pair may sign its `client_assertion` (RFC 7523): asymmetric only, never `none` or a shared-secret HMAC. */
|
|
251
|
+
export const CLIENT_ASSERTION_ALGS = ["RS256", "ES256", "PS256"];
|
|
252
|
+
/** The `client_assertion_type` of a signed-JWT client authentication (RFC 7523 §2.2). */
|
|
253
|
+
export const CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
|
|
254
|
+
/** How long a client assertion may live (exp − now, and exp − iat), and the clock skew allowed on top. */
|
|
255
|
+
export const CLIENT_ASSERTION_MAX_SECONDS = 300;
|
|
256
|
+
const CLIENT_ASSERTION_SKEW_SECONDS = 30;
|
|
257
|
+
const CLIENT_JWKS_MAX_KEYS = 20;
|
|
258
|
+
/** A fetched client key set is kept this long; an unknown `kid` fetches it again, but not more often than every 10 seconds. */
|
|
259
|
+
const CLIENT_JWKS_CACHE_SECONDS = 300;
|
|
260
|
+
const CLIENT_JWKS_REFETCH_MS = 10_000;
|
|
261
|
+
/** Why a client's metadata document, or its address, is refused. */
|
|
262
|
+
export class ClientMetadataError extends Error {
|
|
263
|
+
constructor(message) {
|
|
264
|
+
super(message);
|
|
265
|
+
this.name = "ClientMetadataError";
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
export const CLIENT_METADATA_MAX_BYTES = 64 * 1024;
|
|
269
|
+
export const CLIENT_METADATA_TIMEOUT_MS = 5000;
|
|
270
|
+
const CLIENT_CACHE_ENTRIES = 100;
|
|
271
|
+
const CLIENT_CACHE_DEFAULT_SECONDS = 300;
|
|
272
|
+
const CLIENT_CACHE_MIN_SECONDS = 60;
|
|
273
|
+
const CLIENT_CACHE_MAX_SECONDS = 24 * 3600;
|
|
274
|
+
const CLIENT_CACHE_FAILED_SECONDS = 30;
|
|
275
|
+
/** A `client_id` that claims to be a URL: it is handled as a metadata document address (and refused when it is not a valid one), never as an opaque id. */
|
|
276
|
+
const claimsUrl = (clientId) => /^https?:\/\//i.test(clientId);
|
|
277
|
+
function publicV4(a, b, c) {
|
|
278
|
+
if (a === 0 || a === 10 || a === 127 || a >= 224)
|
|
279
|
+
return false; // "this network", private, loopback, multicast and reserved
|
|
280
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
281
|
+
return false; // carrier-grade NAT
|
|
282
|
+
if (a === 169 && b === 254)
|
|
283
|
+
return false; // link-local (cloud metadata services live here)
|
|
284
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
285
|
+
return false;
|
|
286
|
+
if (a === 192 && b === 168)
|
|
287
|
+
return false;
|
|
288
|
+
if (a === 192 && b === 0 && (c === 0 || c === 2))
|
|
289
|
+
return false; // protocol assignments, documentation
|
|
290
|
+
if (a === 198 && (b === 18 || b === 19))
|
|
291
|
+
return false; // benchmarking
|
|
292
|
+
if ((a === 198 && b === 51 && c === 100) || (a === 203 && b === 0 && c === 113))
|
|
293
|
+
return false; // documentation
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
/** The eight 16-bit groups of an IPv6 address `isIP` accepted. */
|
|
297
|
+
function v6Groups(ip) {
|
|
298
|
+
let s = ip.split("%")[0];
|
|
299
|
+
if (s.includes(".")) {
|
|
300
|
+
const cut = s.lastIndexOf(":");
|
|
301
|
+
const [a = 0, b = 0, c = 0, d = 0] = s.slice(cut + 1).split(".").map(Number);
|
|
302
|
+
s = `${s.slice(0, cut + 1)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
|
|
303
|
+
}
|
|
304
|
+
const [head = "", tail] = s.split("::");
|
|
305
|
+
const parse = (part) => part.split(":").filter(Boolean).map((g) => parseInt(g, 16));
|
|
306
|
+
const left = parse(head);
|
|
307
|
+
const right = tail === undefined ? [] : parse(tail);
|
|
308
|
+
return [...left, ...new Array(Math.max(0, 8 - left.length - right.length)).fill(0), ...right];
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Whether an IP address (v4 or v6, brackets allowed) is one on the public
|
|
312
|
+
* internet. False for loopback, private, link-local, carrier-grade NAT,
|
|
313
|
+
* unique-local, multicast, unspecified, documentation and reserved ranges,
|
|
314
|
+
* for an IPv6 address that carries one of those IPv4 addresses (mapped,
|
|
315
|
+
* NAT64, 6to4), and for anything that is not an IP address.
|
|
316
|
+
*/
|
|
317
|
+
export function isPublicAddress(address) {
|
|
318
|
+
const ip = address.replace(/^\[|\]$/g, "");
|
|
319
|
+
const kind = isIP(ip);
|
|
320
|
+
if (kind === 4) {
|
|
321
|
+
const [a = 0, b = 0, c = 0] = ip.split(".").map(Number);
|
|
322
|
+
return publicV4(a, b, c);
|
|
323
|
+
}
|
|
324
|
+
if (kind !== 6)
|
|
325
|
+
return false;
|
|
326
|
+
const [g0 = 0, g1 = 0, g2 = 0, g3 = 0, g4 = 0, g5 = 0, g6 = 0, g7 = 0] = v6Groups(ip);
|
|
327
|
+
const embedded = (hi, lo) => publicV4(hi >> 8, hi & 255, lo >> 8);
|
|
328
|
+
// ::ffff:a.b.c.d (IPv4-mapped) and the old ::a.b.c.d: the IPv4 address decides (so `::` and `::1` are refused too).
|
|
329
|
+
if (!g0 && !g1 && !g2 && !g3 && !g4 && (g5 === 0xffff || g5 === 0))
|
|
330
|
+
return embedded(g6, g7);
|
|
331
|
+
if (g0 === 0x64 && g1 === 0xff9b)
|
|
332
|
+
return !g2 && !g3 && !g4 && !g5 && embedded(g6, g7); // NAT64; its local-use prefix is refused
|
|
333
|
+
if (g0 === 0x2002)
|
|
334
|
+
return embedded(g1, g2); // 6to4
|
|
335
|
+
if (g0 === 0x2001 && (g1 === 0 || g1 === 0xdb8))
|
|
336
|
+
return false; // Teredo, documentation
|
|
337
|
+
// What is left is public only inside global unicast (2000::/3): unique-local fc00::/7, link-local fe80::/10 and multicast ff00::/8 are outside it.
|
|
338
|
+
return (g0 & 0xe000) === 0x2000;
|
|
339
|
+
}
|
|
340
|
+
/** Why a host may not be fetched from, before any DNS: a non-public IP literal, or a name that is local by definition. Null when it may. */
|
|
341
|
+
function hostProblem(hostname) {
|
|
342
|
+
const host = hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "").toLowerCase();
|
|
343
|
+
if (isIP(host))
|
|
344
|
+
return isPublicAddress(host) ? null : `${host} is not a public address`;
|
|
345
|
+
if (!host.includes(".") || /(^|\.)(localhost|local|internal)$/.test(host))
|
|
346
|
+
return `${host || "(no host)"} is not a public host name`;
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
/** Why a `client_id` is not a valid Client ID Metadata Document URL; null when it is one. */
|
|
350
|
+
export function clientMetadataUrlProblem(clientId) {
|
|
351
|
+
// Checked on the text as sent: the URL parser would quietly drop spaces and resolve dot segments.
|
|
352
|
+
if (/[\s\x00-\x1f\\]/.test(clientId))
|
|
353
|
+
return "it contains spaces, control characters or backslashes";
|
|
354
|
+
let url;
|
|
355
|
+
try {
|
|
356
|
+
url = new URL(clientId);
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
return "it is not a URL";
|
|
360
|
+
}
|
|
361
|
+
if (url.protocol !== "https:" || !/^https:\/\//i.test(clientId))
|
|
362
|
+
return "it must be an https URL";
|
|
363
|
+
if (clientId.includes("#"))
|
|
364
|
+
return "it must not have a fragment";
|
|
365
|
+
const [authority = "", ...rest] = clientId.slice(8).split(/[?]/)[0].split("/");
|
|
366
|
+
if (authority.includes("@") || url.username || url.password)
|
|
367
|
+
return "it must not carry a user name or password";
|
|
368
|
+
if (url.pathname === "/" || !rest.length)
|
|
369
|
+
return "it needs a path (https://host/path), not only a host";
|
|
370
|
+
if (rest.some((segment) => /^(\.|%2e){1,2}$/i.test(segment)))
|
|
371
|
+
return "its path must not contain . or .. segments";
|
|
372
|
+
return hostProblem(url.hostname);
|
|
373
|
+
}
|
|
374
|
+
export const isClientMetadataUrl = (clientId) => clientMetadataUrlProblem(clientId) === null;
|
|
375
|
+
/** A client's key set, checked: 1–20 public keys (no private or symmetric key material). Throws ClientMetadataError. */
|
|
376
|
+
export function validateClientJwks(value, where = "jwks") {
|
|
377
|
+
const keys = value && typeof value === "object" && !Array.isArray(value) ? value.keys : undefined;
|
|
378
|
+
if (!Array.isArray(keys) || !keys.length || keys.length > CLIENT_JWKS_MAX_KEYS)
|
|
379
|
+
throw new ClientMetadataError(`the client's ${where} must be a key set ({ "keys": [...] }) with 1 to ${CLIENT_JWKS_MAX_KEYS} keys`);
|
|
380
|
+
for (const key of keys) {
|
|
381
|
+
if (!key || typeof key !== "object" || Array.isArray(key) || typeof key.kty !== "string")
|
|
382
|
+
throw new ClientMetadataError(`a key of the client's ${where} is not a JWK`);
|
|
383
|
+
if (key.kty === "oct" || ["d", "p", "q", "dp", "dq", "qi", "k"].some((f) => f in key))
|
|
384
|
+
throw new ClientMetadataError(`the client's ${where} must hold public keys only`);
|
|
385
|
+
}
|
|
386
|
+
return { keys: keys };
|
|
387
|
+
}
|
|
388
|
+
/** A fetched metadata document, checked: it must be the document of exactly this `client_id`, of a public client or of one that signs with a key pair (`private_key_jwt`). Throws ClientMetadataError. */
|
|
389
|
+
export function validateClientMetadata(clientId, document) {
|
|
390
|
+
if (!document || typeof document !== "object" || Array.isArray(document))
|
|
391
|
+
throw new ClientMetadataError("the metadata document is not a JSON object");
|
|
392
|
+
const d = document;
|
|
393
|
+
if (d.client_id !== clientId)
|
|
394
|
+
throw new ClientMetadataError("the metadata document's client_id is not the URL it was fetched from (they must be the same string)");
|
|
395
|
+
if (!Array.isArray(d.redirect_uris) || !d.redirect_uris.length || !d.redirect_uris.every((u) => typeof u === "string" && u))
|
|
396
|
+
throw new ClientMetadataError("the metadata document needs redirect_uris, a non-empty array of strings");
|
|
397
|
+
for (const uri of d.redirect_uris) {
|
|
398
|
+
let scheme;
|
|
399
|
+
try {
|
|
400
|
+
scheme = new URL(uri).protocol;
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
throw new ClientMetadataError("a redirect_uri of the metadata document is not an absolute URL");
|
|
404
|
+
}
|
|
405
|
+
if (uri.includes("#") || /^(javascript|data|vbscript|file|blob|about):$/.test(scheme))
|
|
406
|
+
throw new ClientMetadataError("a redirect_uri of the metadata document has a fragment or a scheme a browser must not be sent to");
|
|
407
|
+
}
|
|
408
|
+
if (d.client_name !== undefined && typeof d.client_name !== "string")
|
|
409
|
+
throw new ClientMetadataError("the metadata document's client_name must be a string");
|
|
410
|
+
// A document anyone can read cannot hold a shared secret (the draft forbids it); a client may prove itself with a key pair instead (private_key_jwt).
|
|
411
|
+
if ("client_secret" in d || "client_secret_expires_at" in d)
|
|
412
|
+
throw new ClientMetadataError("the metadata document must not carry client_secret or client_secret_expires_at");
|
|
413
|
+
const method = d.token_endpoint_auth_method;
|
|
414
|
+
if (method !== undefined && method !== "none" && method !== "private_key_jwt")
|
|
415
|
+
throw new ClientMetadataError(`token_endpoint_auth_method must be "none" (a public client), "private_key_jwt" (with jwks_uri or jwks) or absent: client secrets are not supported`);
|
|
416
|
+
const base = { client_id: clientId, redirect_uris: [...d.redirect_uris], ...(typeof d.client_name === "string" && d.client_name.trim() ? { client_name: d.client_name.trim() } : {}) };
|
|
417
|
+
if (method !== "private_key_jwt")
|
|
418
|
+
return base;
|
|
419
|
+
const alg = d.token_endpoint_auth_signing_alg ?? "RS256";
|
|
420
|
+
if (!CLIENT_ASSERTION_ALGS.includes(alg))
|
|
421
|
+
throw new ClientMetadataError(`token_endpoint_auth_signing_alg must be one of ${CLIENT_ASSERTION_ALGS.join(", ")} (default RS256)`);
|
|
422
|
+
if ((d.jwks_uri === undefined) === (d.jwks === undefined))
|
|
423
|
+
throw new ClientMetadataError("a private_key_jwt client needs its keys: jwks_uri or jwks (exactly one of them)");
|
|
424
|
+
const keys = {};
|
|
425
|
+
if (d.jwks_uri !== undefined) {
|
|
426
|
+
// Fetched like the document itself: https, a public host, no fragment, no user name.
|
|
427
|
+
const problem = typeof d.jwks_uri === "string" ? clientMetadataUrlProblem(d.jwks_uri) : "it is not a string";
|
|
428
|
+
if (problem)
|
|
429
|
+
throw new ClientMetadataError(`the metadata document's jwks_uri is not a valid key set URL: ${problem}`);
|
|
430
|
+
keys.jwks_uri = d.jwks_uri;
|
|
431
|
+
}
|
|
432
|
+
else
|
|
433
|
+
keys.jwks = validateClientJwks(d.jwks, "jwks");
|
|
434
|
+
return { ...base, token_endpoint_auth_method: "private_key_jwt", token_endpoint_auth_signing_alg: alg, ...keys };
|
|
435
|
+
}
|
|
436
|
+
const LOOPBACK_REDIRECT = /^(127\.0\.0\.1|localhost|\[::1\])$/;
|
|
437
|
+
/**
|
|
438
|
+
* Whether `redirect` is one of a client's registered redirect URIs: the same
|
|
439
|
+
* string, with one exception (RFC 8252 §7.3): for `http://127.0.0.1`,
|
|
440
|
+
* `http://localhost` and `http://[::1]` the port may differ, because a native
|
|
441
|
+
* client listens on whatever port the system gives it.
|
|
442
|
+
*/
|
|
443
|
+
export function redirectUriAllowed(redirect, registered) {
|
|
444
|
+
if (!redirect)
|
|
445
|
+
return false;
|
|
446
|
+
if (registered.includes(redirect))
|
|
447
|
+
return true;
|
|
448
|
+
let asked;
|
|
449
|
+
try {
|
|
450
|
+
asked = new URL(redirect);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
return false;
|
|
454
|
+
}
|
|
455
|
+
if (asked.protocol !== "http:" || !LOOPBACK_REDIRECT.test(asked.hostname) || redirect.includes("#") || /[\s\\]/.test(redirect))
|
|
456
|
+
return false;
|
|
457
|
+
asked.port = "";
|
|
458
|
+
return registered.some((r) => {
|
|
459
|
+
try {
|
|
460
|
+
const known = new URL(r);
|
|
461
|
+
if (known.protocol !== "http:" || !LOOPBACK_REDIRECT.test(known.hostname))
|
|
462
|
+
return false;
|
|
463
|
+
known.port = "";
|
|
464
|
+
return known.href === asked.href;
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
return false;
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
/** How long a fetched document may be kept, in seconds, from its `Cache-Control`: 0 for `no-store`/`no-cache`, else `max-age` held between a minute and a day, five minutes without one. */
|
|
472
|
+
export function clientMetadataCacheSeconds(cacheControl) {
|
|
473
|
+
const value = (cacheControl ?? "").toLowerCase();
|
|
474
|
+
if (/(^|[\s,])no-(store|cache)\b/.test(value))
|
|
475
|
+
return 0;
|
|
476
|
+
const age = /(?:^|[\s,])max-age\s*=\s*"?(\d{1,12})/.exec(value);
|
|
477
|
+
return age ? Math.min(CLIENT_CACHE_MAX_SECONDS, Math.max(CLIENT_CACHE_MIN_SECONDS, Number(age[1]))) : CLIENT_CACHE_DEFAULT_SECONDS;
|
|
478
|
+
}
|
|
479
|
+
const systemLookup = async (host) => (await dnsLookup(host, { all: true })).map((a) => a.address);
|
|
480
|
+
/**
|
|
481
|
+
* Fetches and checks the metadata document of a URL `client_id`. Nothing is
|
|
482
|
+
* requested unless the URL is valid and every address its host resolves to
|
|
483
|
+
* is public; redirects are not followed; the answer must be 200, JSON, at
|
|
484
|
+
* most 64 KB, within 5 seconds. Throws ClientMetadataError.
|
|
485
|
+
*
|
|
486
|
+
* The limit of this: the addresses are checked, then `fetch` resolves the
|
|
487
|
+
* name again, so a DNS server that answers differently the second time (DNS
|
|
488
|
+
* rebinding) gets the request sent to an address that was not checked. What
|
|
489
|
+
* it can do with that is small (https only, so the internal host would have
|
|
490
|
+
* to hold a certificate for the attacker's name; no redirects; the body is
|
|
491
|
+
* only ever parsed as a metadata document), but it is not nothing: a
|
|
492
|
+
* production authorization server should pin the connection to the address
|
|
493
|
+
* it checked.
|
|
494
|
+
*/
|
|
495
|
+
export async function fetchClientMetadata(clientId, transport = {}) {
|
|
496
|
+
const problem = clientMetadataUrlProblem(clientId);
|
|
497
|
+
if (problem)
|
|
498
|
+
throw new ClientMetadataError(`client_id is not a valid metadata document URL: ${problem}`);
|
|
499
|
+
const { value, cacheSeconds } = await fetchPublicJson(clientId, transport, "metadata document");
|
|
500
|
+
return { metadata: validateClientMetadata(clientId, value), cacheSeconds };
|
|
501
|
+
}
|
|
502
|
+
/** Fetches and checks the key set of a `private_key_jwt` client from its `jwks_uri`, with the same protections as the metadata document. Throws ClientMetadataError. */
|
|
503
|
+
export async function fetchClientJwks(jwksUri, transport = {}) {
|
|
504
|
+
const problem = clientMetadataUrlProblem(jwksUri);
|
|
505
|
+
if (problem)
|
|
506
|
+
throw new ClientMetadataError(`jwks_uri is not a valid key set URL: ${problem}`);
|
|
507
|
+
const { value, cacheSeconds } = await fetchPublicJson(jwksUri, transport, "key set (jwks_uri)");
|
|
508
|
+
return { jwks: validateClientJwks(value, "key set (jwks_uri)"), cacheSeconds };
|
|
509
|
+
}
|
|
510
|
+
/** A JSON document at a checked https URL `address`, fetched only when every address of its host is public (see fetchClientMetadata). `what` names it in errors. */
|
|
511
|
+
async function fetchPublicJson(address, transport, what) {
|
|
512
|
+
const host = new URL(address).hostname.replace(/^\[|\]$/g, "");
|
|
513
|
+
if (!isIP(host)) {
|
|
514
|
+
let addresses;
|
|
515
|
+
try {
|
|
516
|
+
addresses = await (transport.lookup ?? systemLookup)(host);
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
throw new ClientMetadataError(`the client's host ${host} does not resolve`);
|
|
520
|
+
}
|
|
521
|
+
if (!addresses.length)
|
|
522
|
+
throw new ClientMetadataError(`the client's host ${host} does not resolve`);
|
|
523
|
+
// One private address among public ones is enough to refuse: which one the connection would use is not ours to choose.
|
|
524
|
+
const inside = addresses.find((a) => !isPublicAddress(a));
|
|
525
|
+
if (inside)
|
|
526
|
+
throw new ClientMetadataError(`the client's host ${host} resolves to ${inside}, which is not a public address`);
|
|
527
|
+
}
|
|
528
|
+
let response;
|
|
529
|
+
let text;
|
|
530
|
+
try {
|
|
531
|
+
response = await (transport.fetch ?? fetch)(address, { method: "GET", redirect: "error", credentials: "omit", headers: { accept: "application/json" }, signal: AbortSignal.timeout(CLIENT_METADATA_TIMEOUT_MS) });
|
|
532
|
+
// A redirect could lead inside the network after the host was checked. `redirect: "error"` already refuses it; this is for a fetch that does not.
|
|
533
|
+
if (response.redirected || response.status !== 200) {
|
|
534
|
+
void response.body?.cancel().catch(() => { });
|
|
535
|
+
throw new ClientMetadataError(`the client's ${what} answered ${response.redirected ? "with a redirect" : response.status} (it must answer 200, without redirects)`);
|
|
536
|
+
}
|
|
537
|
+
if (!/^application\/([\w.!#$&^-]+\+)?json\s*(;|$)/i.test(response.headers.get("content-type") ?? "")) {
|
|
538
|
+
void response.body?.cancel().catch(() => { });
|
|
539
|
+
throw new ClientMetadataError(`the client's ${what} is not served as JSON (content-type application/json)`);
|
|
540
|
+
}
|
|
541
|
+
text = await readCapped(response, CLIENT_METADATA_MAX_BYTES, what);
|
|
542
|
+
}
|
|
543
|
+
catch (error) {
|
|
544
|
+
if (error instanceof ClientMetadataError)
|
|
545
|
+
throw error;
|
|
546
|
+
throw new ClientMetadataError(`the client's ${what} could not be fetched (${error instanceof Error && error.name === "TimeoutError" ? "no answer in time" : "network error or redirect"})`);
|
|
547
|
+
}
|
|
548
|
+
let document;
|
|
549
|
+
try {
|
|
550
|
+
document = JSON.parse(text);
|
|
551
|
+
}
|
|
552
|
+
catch {
|
|
553
|
+
throw new ClientMetadataError(`the client's ${what} is not valid JSON`);
|
|
554
|
+
}
|
|
555
|
+
return { value: document, cacheSeconds: clientMetadataCacheSeconds(response.headers.get("cache-control")) };
|
|
556
|
+
}
|
|
557
|
+
/** The body as text, read piece by piece and dropped as soon as it passes `max` bytes (a Content-Length can lie, so the bytes are counted). */
|
|
558
|
+
async function readCapped(response, max, what) {
|
|
559
|
+
const tooLarge = () => new ClientMetadataError(`the client's ${what} is larger than ${max / 1024} KB`);
|
|
560
|
+
if (Number(response.headers.get("content-length") ?? 0) > max) {
|
|
561
|
+
void response.body?.cancel().catch(() => { });
|
|
562
|
+
throw tooLarge();
|
|
563
|
+
}
|
|
564
|
+
if (!response.body)
|
|
565
|
+
return "";
|
|
566
|
+
const reader = response.body.getReader();
|
|
567
|
+
const chunks = [];
|
|
568
|
+
let size = 0;
|
|
569
|
+
for (;;) {
|
|
570
|
+
const { done, value } = await reader.read();
|
|
571
|
+
if (done)
|
|
572
|
+
break;
|
|
573
|
+
size += value.byteLength;
|
|
574
|
+
if (size > max) {
|
|
575
|
+
void reader.cancel().catch(() => { });
|
|
576
|
+
throw tooLarge();
|
|
577
|
+
}
|
|
578
|
+
chunks.push(value);
|
|
579
|
+
}
|
|
580
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* A minimal OAuth 2.1 authorization server for development (spec §7): clients
|
|
584
|
+
* identify themselves with a Client ID Metadata Document URL (fetched and
|
|
585
|
+
* checked, above) or register dynamically (any client); authorization code
|
|
586
|
+
* with PKCE S256, a sign-in page listing test people that asks for the code
|
|
587
|
+
* printed on the console (five wrong codes close the sign-in until the app
|
|
588
|
+
* restarts), refresh tokens. Stateless but for a small cache of client
|
|
589
|
+
* documents: codes and refresh tokens are JWTs signed with the dev key.
|
|
590
|
+
* Every token's issuer is the origin the request came to (so a tunnel
|
|
591
|
+
* works); the key is what is checked. The server answers it only to callers
|
|
592
|
+
* on a loopback address (server.ts).
|
|
593
|
+
*/
|
|
594
|
+
export class DevAuthority {
|
|
595
|
+
options;
|
|
596
|
+
app;
|
|
597
|
+
code;
|
|
598
|
+
people;
|
|
599
|
+
installation;
|
|
600
|
+
#key = null;
|
|
601
|
+
#wrongCodes = 0;
|
|
602
|
+
publicKey;
|
|
603
|
+
#origins = new Set([DEV_ISSUER]);
|
|
604
|
+
/** Client documents by client_id, oldest first; a failed fetch is kept too, briefly, so a broken client cannot make this server hammer a host. */
|
|
605
|
+
#clients = new Map();
|
|
606
|
+
/** Key sets of private_key_jwt clients by jwks_uri, oldest first (a failure is kept briefly too). */
|
|
607
|
+
#keySets = new Map();
|
|
608
|
+
/** Client assertion ids already used, until their expiry (ms): an assertion is good for one request. */
|
|
609
|
+
#usedAssertions = new Map();
|
|
610
|
+
constructor(options, app) {
|
|
611
|
+
this.options = options;
|
|
612
|
+
this.app = app;
|
|
613
|
+
this.code = options.code ?? randomBytes(4).toString("hex").toUpperCase();
|
|
614
|
+
this.people = options.people?.length ? options.people : [{ id: "test-person", name: "Test person", permissions: "all" }];
|
|
615
|
+
this.installation = options.installation ?? "dev";
|
|
616
|
+
}
|
|
617
|
+
async start() {
|
|
618
|
+
const fromJwk = async (jwk) => {
|
|
619
|
+
const privateKey = (await importJWK(jwk, "EdDSA"));
|
|
620
|
+
const { d: _d, ...pub } = jwk;
|
|
621
|
+
const kid = String(jwk.kid ?? createHash("sha256").update(String(jwk.x)).digest("base64url").slice(0, 16));
|
|
622
|
+
return { privateKey, publicJwk: { ...pub, kid, alg: "EdDSA", use: "sig" }, kid };
|
|
623
|
+
};
|
|
624
|
+
const env = process.env.CLEGRA_DEV_KEY;
|
|
625
|
+
const file = this.options.keyFile === false ? null : (this.options.keyFile ?? `.${PROTOCOL_ID}-dev-key.json`);
|
|
626
|
+
if (env)
|
|
627
|
+
this.#key = await fromJwk(JSON.parse(env));
|
|
628
|
+
else if (!file)
|
|
629
|
+
this.#key = await generateSigningKey();
|
|
630
|
+
else {
|
|
631
|
+
// Loaded only here, in development on Node: nothing else in the SDK touches the disk.
|
|
632
|
+
const fs = await import("node:fs");
|
|
633
|
+
if (fs.existsSync(file))
|
|
634
|
+
this.#key = await fromJwk(JSON.parse(fs.readFileSync(file, "utf8")));
|
|
635
|
+
else {
|
|
636
|
+
this.#key = await generateSigningKey();
|
|
637
|
+
const priv = await exportJWK(this.#key.privateKey);
|
|
638
|
+
fs.writeFileSync(file, JSON.stringify({ ...priv, kid: this.#key.kid }), { mode: 0o600 });
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
this.publicKey = (await importJWK(this.#key.publicJwk, "EdDSA"));
|
|
642
|
+
}
|
|
643
|
+
get key() {
|
|
644
|
+
if (!this.#key)
|
|
645
|
+
throw new Error("dev authority not started");
|
|
646
|
+
return this.#key;
|
|
647
|
+
}
|
|
648
|
+
/** Whether `iss` is one of the dev authority's (its fixed name or an origin it answered on). */
|
|
649
|
+
issues(iss) {
|
|
650
|
+
return this.#origins.has(iss);
|
|
651
|
+
}
|
|
652
|
+
permissionsOf(person) {
|
|
653
|
+
const p = person?.permissions ?? "all";
|
|
654
|
+
return p === "all" ? this.app.allPermissions() : p;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* A dev access token. `person: null`: no person — with `host: "workspace"` the installation-level caller (the host
|
|
658
|
+
* calling for the installation itself: schedules, later runs, lifecycle), `sub` = `installation:<installation>`,
|
|
659
|
+
* no permissions unless given.
|
|
660
|
+
*/
|
|
661
|
+
async token(input) {
|
|
662
|
+
const installation = input.installation ?? this.installation;
|
|
663
|
+
const known = typeof input.person === "string" ? this.people.find((p) => p.id === input.person) : undefined;
|
|
664
|
+
const person = input.person === null ? null : typeof input.person === "object" ? input.person : (known ?? this.people[0]);
|
|
665
|
+
const permissions = input.permissions ? (input.permissions === "all" ? this.app.allPermissions() : input.permissions) : person ? this.permissionsOf(known ?? this.people[0]) : [];
|
|
666
|
+
const iss = input.issuer ?? DEV_ISSUER;
|
|
667
|
+
this.#origins.add(iss);
|
|
668
|
+
return signAccessToken(this.key, {
|
|
669
|
+
// A workspace host's token is for one request.
|
|
670
|
+
...(input.host === "workspace" ? { lifetimeSeconds: HOST_TOKEN_SECONDS } : {}),
|
|
671
|
+
iss,
|
|
672
|
+
aud: input.audience,
|
|
673
|
+
sub: person ? person.id : `installation:${installation}`,
|
|
674
|
+
[TOKEN_CLAIM]: { installation, ...(person ? { person: { id: person.id, name: person.name } } : {}), permissions, ...(input.locale ? { locale: input.locale } : {}), host: input.host ?? "plain" },
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
/** The checked metadata document of a URL `client_id`, from the cache or fetched. Throws ClientMetadataError. */
|
|
678
|
+
#client(clientId) {
|
|
679
|
+
const kept = this.#clients.get(clientId);
|
|
680
|
+
if (kept && kept.until > Date.now())
|
|
681
|
+
return kept.result;
|
|
682
|
+
this.#clients.delete(clientId);
|
|
683
|
+
// An address that is refused without a request costs nothing to refuse again: only what was fetched is kept.
|
|
684
|
+
if (clientMetadataUrlProblem(clientId))
|
|
685
|
+
return fetchClientMetadata(clientId, this.options.clientMetadata).then((r) => r.metadata);
|
|
686
|
+
while (this.#clients.size >= CLIENT_CACHE_ENTRIES)
|
|
687
|
+
this.#clients.delete(this.#clients.keys().next().value);
|
|
688
|
+
const entry = { until: Date.now() + CLIENT_CACHE_FAILED_SECONDS * 1000, result: Promise.resolve(null) };
|
|
689
|
+
entry.result = fetchClientMetadata(clientId, this.options.clientMetadata).then(({ metadata, cacheSeconds }) => {
|
|
690
|
+
// `no-store`: requests already waiting share this answer, the next one fetches again.
|
|
691
|
+
if (!cacheSeconds) {
|
|
692
|
+
if (this.#clients.get(clientId) === entry)
|
|
693
|
+
this.#clients.delete(clientId);
|
|
694
|
+
}
|
|
695
|
+
else
|
|
696
|
+
entry.until = Date.now() + cacheSeconds * 1000;
|
|
697
|
+
return metadata;
|
|
698
|
+
});
|
|
699
|
+
entry.result.catch(() => { });
|
|
700
|
+
this.#clients.set(clientId, entry);
|
|
701
|
+
return entry.result;
|
|
702
|
+
}
|
|
703
|
+
/** The key set of a private_key_jwt client: inline, or from its jwks_uri (kept a few minutes; `fresh` fetches again unless it was fetched in the last 10 seconds). */
|
|
704
|
+
#clientKeys(client, fresh = false) {
|
|
705
|
+
if (client.jwks)
|
|
706
|
+
return Promise.resolve(client.jwks);
|
|
707
|
+
const uri = client.jwks_uri;
|
|
708
|
+
const now = Date.now();
|
|
709
|
+
const kept = this.#keySets.get(uri);
|
|
710
|
+
if (kept && (fresh ? now - kept.fetchedAt < CLIENT_JWKS_REFETCH_MS : kept.until > now))
|
|
711
|
+
return kept.result;
|
|
712
|
+
this.#keySets.delete(uri);
|
|
713
|
+
while (this.#keySets.size >= CLIENT_CACHE_ENTRIES)
|
|
714
|
+
this.#keySets.delete(this.#keySets.keys().next().value);
|
|
715
|
+
const entry = { fetchedAt: now, until: now + CLIENT_CACHE_FAILED_SECONDS * 1000, result: Promise.resolve({ keys: [] }) };
|
|
716
|
+
entry.result = fetchClientJwks(uri, this.options.clientMetadata).then(({ jwks, cacheSeconds }) => {
|
|
717
|
+
entry.until = Date.now() + Math.min(cacheSeconds, CLIENT_JWKS_CACHE_SECONDS) * 1000;
|
|
718
|
+
return jwks;
|
|
719
|
+
});
|
|
720
|
+
entry.result.catch(() => { });
|
|
721
|
+
this.#keySets.set(uri, entry);
|
|
722
|
+
return entry.result;
|
|
723
|
+
}
|
|
724
|
+
/** Whether an assertion id is new (and from now on used, until `untilMs`). */
|
|
725
|
+
#firstUse(key, untilMs) {
|
|
726
|
+
const now = Date.now();
|
|
727
|
+
for (const [k, until] of this.#usedAssertions)
|
|
728
|
+
if (until <= now)
|
|
729
|
+
this.#usedAssertions.delete(k);
|
|
730
|
+
if (this.#usedAssertions.has(key))
|
|
731
|
+
return false;
|
|
732
|
+
this.#usedAssertions.set(key, untilMs);
|
|
733
|
+
return true;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Client authentication with a signed JWT (RFC 7523 §2.2, `private_key_jwt`):
|
|
737
|
+
* signed with the client's algorithm by a key of its key set, `iss` = `sub`
|
|
738
|
+
* = its client_id, `aud` this server's token endpoint or issuer, short-lived,
|
|
739
|
+
* with a `jti` that is used once. Returns why not, or null when it holds.
|
|
740
|
+
*/
|
|
741
|
+
async #authenticate(client, form, origin) {
|
|
742
|
+
const assertion = form.get("client_assertion") ?? "";
|
|
743
|
+
if (!assertion)
|
|
744
|
+
return "this client authenticates with private_key_jwt: client_assertion is required";
|
|
745
|
+
if (form.get("client_assertion_type") !== CLIENT_ASSERTION_TYPE)
|
|
746
|
+
return `client_assertion_type must be ${CLIENT_ASSERTION_TYPE}`;
|
|
747
|
+
const alg = client.token_endpoint_auth_signing_alg ?? "RS256";
|
|
748
|
+
let header;
|
|
749
|
+
try {
|
|
750
|
+
header = decodeProtectedHeader(assertion);
|
|
751
|
+
}
|
|
752
|
+
catch {
|
|
753
|
+
return "client_assertion is not a JWT";
|
|
754
|
+
}
|
|
755
|
+
if (header.alg !== alg)
|
|
756
|
+
return `client_assertion must be signed with ${alg} (the client's token_endpoint_auth_signing_alg)`;
|
|
757
|
+
const options = { algorithms: [alg], issuer: client.client_id, subject: client.client_id, audience: [`${origin}/oauth/token`, origin], clockTolerance: CLIENT_ASSERTION_SKEW_SECONDS, requiredClaims: ["exp", "jti"] };
|
|
758
|
+
let payload;
|
|
759
|
+
try {
|
|
760
|
+
try {
|
|
761
|
+
;
|
|
762
|
+
({ payload } = await jwtVerify(assertion, createLocalJWKSet(await this.#clientKeys(client)), options));
|
|
763
|
+
}
|
|
764
|
+
catch (error) {
|
|
765
|
+
// A key the cached set does not have: the client may have rotated its keys, so its jwks_uri is asked once more.
|
|
766
|
+
if (!client.jwks_uri || error.code !== "ERR_JWKS_NO_MATCHING_KEY")
|
|
767
|
+
throw error;
|
|
768
|
+
({ payload } = await jwtVerify(assertion, createLocalJWKSet(await this.#clientKeys(client, true)), options));
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
catch (error) {
|
|
772
|
+
if (error instanceof ClientMetadataError)
|
|
773
|
+
return error.message;
|
|
774
|
+
return `client_assertion: ${error.code === "ERR_JWKS_NO_MATCHING_KEY" ? "no key of the client's key set matches it" : error instanceof Error ? error.message : "invalid"}`;
|
|
775
|
+
}
|
|
776
|
+
const now = Math.floor(Date.now() / 1000);
|
|
777
|
+
const exp = payload.exp;
|
|
778
|
+
if (exp - now > CLIENT_ASSERTION_MAX_SECONDS + CLIENT_ASSERTION_SKEW_SECONDS || (typeof payload.iat === "number" && exp - payload.iat > CLIENT_ASSERTION_MAX_SECONDS))
|
|
779
|
+
return `a client_assertion lives ${CLIENT_ASSERTION_MAX_SECONDS / 60} minutes at most`;
|
|
780
|
+
if (typeof payload.jti !== "string" || !payload.jti)
|
|
781
|
+
return "client_assertion needs a jti";
|
|
782
|
+
if (!this.#firstUse(`${client.client_id}\n${payload.jti}`, (exp + CLIENT_ASSERTION_SKEW_SECONDS) * 1000))
|
|
783
|
+
return "this client_assertion was already used (its jti is for one request)";
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
/** Answers the authorization server's paths; null for any other path. */
|
|
787
|
+
async handle(request, origin, resource) {
|
|
788
|
+
const url = new URL(request.url);
|
|
789
|
+
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "access-control-allow-origin": "*", "cache-control": "no-store" } });
|
|
790
|
+
const path = url.pathname;
|
|
791
|
+
if (path === "/.well-known/oauth-authorization-server" || path === "/.well-known/openid-configuration") {
|
|
792
|
+
this.#origins.add(origin);
|
|
793
|
+
return json({
|
|
794
|
+
issuer: origin,
|
|
795
|
+
authorization_endpoint: `${origin}/oauth/authorize`,
|
|
796
|
+
token_endpoint: `${origin}/oauth/token`,
|
|
797
|
+
registration_endpoint: `${origin}/oauth/register`,
|
|
798
|
+
client_id_metadata_document_supported: true,
|
|
799
|
+
jwks_uri: `${origin}/.well-known/jwks.json`,
|
|
800
|
+
response_types_supported: ["code"],
|
|
801
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
802
|
+
code_challenge_methods_supported: ["S256"],
|
|
803
|
+
// Public clients, and metadata-document clients that sign a client assertion with a key pair (RFC 7523).
|
|
804
|
+
token_endpoint_auth_methods_supported: ["none", "private_key_jwt"],
|
|
805
|
+
token_endpoint_auth_signing_alg_values_supported: [...CLIENT_ASSERTION_ALGS],
|
|
806
|
+
scopes_supported: [OAUTH_SCOPE],
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
if (path === "/.well-known/jwks.json")
|
|
810
|
+
return json({ keys: [this.key.publicJwk] });
|
|
811
|
+
if (path === "/oauth/register" && request.method === "POST") {
|
|
812
|
+
const body = (await request.json().catch(() => ({})));
|
|
813
|
+
return json({ ...body, client_id: `dev-${randomUUID()}`, client_id_issued_at: Math.floor(Date.now() / 1000), token_endpoint_auth_method: "none" }, 201);
|
|
814
|
+
}
|
|
815
|
+
if (path === "/oauth/authorize")
|
|
816
|
+
return this.#authorize(request, url, origin, resource);
|
|
817
|
+
if (path === "/oauth/token" && request.method === "POST")
|
|
818
|
+
return this.#token(request, origin, resource, json);
|
|
819
|
+
return null;
|
|
820
|
+
}
|
|
821
|
+
async #authorize(request, url, origin, resource) {
|
|
822
|
+
const form = request.method === "POST" ? new URLSearchParams(await request.text()) : url.searchParams;
|
|
823
|
+
const p = (k) => form.get(k) ?? "";
|
|
824
|
+
const shell = (body, status) => new Response(`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in · ${html(this.app.title)} (dev)</title>
|
|
825
|
+
<style>body{font:15px system-ui,sans-serif;max-width:420px;margin:48px auto;padding:0 16px;color:#1d1d1f}h1{font-size:20px}label{display:block;margin:12px 0 4px}select,input,button{font:inherit;padding:8px;width:100%;box-sizing:border-box}button{margin-top:16px;background:#1d1d1f;color:#fff;border:0;border-radius:8px}.e{color:#b00020}.n{color:#666;font-size:13px}.c{padding:10px 12px;border:1px solid #d2d2d7;border-radius:8px;overflow-wrap:anywhere}</style></head>
|
|
826
|
+
<body><h1>${html(this.app.title)} — development sign-in</h1>${body}</body></html>`, { status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-frame-options": "DENY" } });
|
|
827
|
+
let client = null;
|
|
828
|
+
// Who is asking, as its own metadata document says: shown so the developer sees which client the sign-in is for.
|
|
829
|
+
const asking = () => {
|
|
830
|
+
if (!client)
|
|
831
|
+
return "";
|
|
832
|
+
const host = html(new URL(client.client_id).host);
|
|
833
|
+
const name = client.client_name ? `<strong>${html(client.client_name.slice(0, 80))}</strong> (${host})` : `<strong>${host}</strong>`;
|
|
834
|
+
return `<p class="c">${name} is asking to sign in.<br><span class="n">From the client's metadata document: ${html(client.client_id)}</span></p>`;
|
|
835
|
+
};
|
|
836
|
+
const page = (error = "") => shell(`<p class="n">Test people only. The code is printed on the app's console.</p>${asking()}${error ? `<p class="e">${html(error)}</p>` : ""}
|
|
837
|
+
<form method="post" action="/oauth/authorize">${["client_id", "redirect_uri", "state", "code_challenge", "code_challenge_method", "scope", "resource"].map((k) => `<input type="hidden" name="${k}" value="${html(p(k))}">`).join("")}
|
|
838
|
+
<label>Person</label><select name="person">${this.people.map((x) => `<option value="${html(x.id)}">${html(x.name)}</option>`).join("")}</select>
|
|
839
|
+
<label>Code</label><input name="code" autocomplete="off" required autofocus>
|
|
840
|
+
<button type="submit">Sign in</button></form>`, error ? 400 : 200);
|
|
841
|
+
// A client that is not who it says, or a redirect address that is not its own: the answer stays here, nothing is ever sent to that address.
|
|
842
|
+
const refuse = (why) => shell(`<p class="e">This client cannot sign in: ${html(why)}.</p><p class="n">Nothing was sent to the client: its redirect address is not trusted.</p>`, 400);
|
|
843
|
+
if (!p("redirect_uri") || !p("code_challenge") || p("code_challenge_method") !== "S256")
|
|
844
|
+
return new Response("redirect_uri and a S256 code_challenge are required", { status: 400 });
|
|
845
|
+
if (claimsUrl(p("client_id"))) {
|
|
846
|
+
try {
|
|
847
|
+
client = await this.#client(p("client_id"));
|
|
848
|
+
}
|
|
849
|
+
catch (error) {
|
|
850
|
+
return refuse(error instanceof ClientMetadataError ? error.message : "its metadata document could not be read");
|
|
851
|
+
}
|
|
852
|
+
if (!redirectUriAllowed(p("redirect_uri"), client.redirect_uris))
|
|
853
|
+
return refuse("redirect_uri is not one of the redirect_uris of its metadata document (it must match exactly; only the port of a loopback address may differ)");
|
|
854
|
+
}
|
|
855
|
+
if (request.method !== "POST")
|
|
856
|
+
return page();
|
|
857
|
+
if (this.#wrongCodes >= DEV_CODE_ATTEMPTS)
|
|
858
|
+
return page("Too many wrong codes: restart the app to sign in again.");
|
|
859
|
+
if (p("code").trim().toUpperCase() !== this.code.toUpperCase()) {
|
|
860
|
+
this.#wrongCodes++;
|
|
861
|
+
if (this.#wrongCodes >= DEV_CODE_ATTEMPTS)
|
|
862
|
+
console.warn(`[${PROTOCOL_ID}] dev sign-in closed after ${DEV_CODE_ATTEMPTS} wrong codes: restart the app to open it again`);
|
|
863
|
+
return page("Wrong code.");
|
|
864
|
+
}
|
|
865
|
+
const person = this.people.find((x) => x.id === p("person"));
|
|
866
|
+
if (!person)
|
|
867
|
+
return page("Unknown person.");
|
|
868
|
+
this.#origins.add(origin);
|
|
869
|
+
const code = await new SignJWT({ k: "code", person: person.id, challenge: p("code_challenge"), redirect: p("redirect_uri"), client: p("client_id") })
|
|
870
|
+
.setProtectedHeader({ alg: "EdDSA", typ: DEV_CODE_TYPE, kid: this.key.kid })
|
|
871
|
+
.setIssuer(origin)
|
|
872
|
+
.setAudience(`${PROTOCOL_ID}-dev-code`)
|
|
873
|
+
.setIssuedAt()
|
|
874
|
+
.setExpirationTime("5m")
|
|
875
|
+
.sign(this.key.privateKey);
|
|
876
|
+
const back = new URL(p("redirect_uri"));
|
|
877
|
+
back.searchParams.set("code", code);
|
|
878
|
+
if (p("state"))
|
|
879
|
+
back.searchParams.set("state", p("state"));
|
|
880
|
+
void resource;
|
|
881
|
+
return new Response(null, { status: 302, headers: { location: back.toString() } });
|
|
882
|
+
}
|
|
883
|
+
async #token(request, origin, resource, json) {
|
|
884
|
+
const form = new URLSearchParams(await request.text());
|
|
885
|
+
const fail = (error, description) => json({ error, error_description: description }, 400);
|
|
886
|
+
let person;
|
|
887
|
+
let client = "";
|
|
888
|
+
/** The redirect address a code was issued for (authorization_code only). */
|
|
889
|
+
let redirect = null;
|
|
890
|
+
let sent = form.get("client_id") ?? "";
|
|
891
|
+
// A client that authenticates with a signed JWT may leave client_id out (RFC 7523 §3): the assertion names it, and is checked below.
|
|
892
|
+
if (!sent && form.get("client_assertion")) {
|
|
893
|
+
try {
|
|
894
|
+
const sub = decodeJwt(form.get("client_assertion")).sub;
|
|
895
|
+
if (typeof sub === "string")
|
|
896
|
+
sent = sub;
|
|
897
|
+
}
|
|
898
|
+
catch {
|
|
899
|
+
// Refused below, as an assertion that does not verify.
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
if (form.get("grant_type") === "authorization_code") {
|
|
903
|
+
let claims;
|
|
904
|
+
try {
|
|
905
|
+
;
|
|
906
|
+
({ payload: claims } = await jwtVerify(form.get("code") ?? "", this.publicKey, { typ: DEV_CODE_TYPE, audience: `${PROTOCOL_ID}-dev-code` }));
|
|
907
|
+
}
|
|
908
|
+
catch {
|
|
909
|
+
return fail("invalid_grant", "unknown or expired code");
|
|
910
|
+
}
|
|
911
|
+
const verifier = form.get("code_verifier") ?? "";
|
|
912
|
+
if (createHash("sha256").update(verifier).digest("base64url") !== claims.challenge)
|
|
913
|
+
return fail("invalid_grant", "PKCE check failed");
|
|
914
|
+
if (form.get("redirect_uri") && form.get("redirect_uri") !== claims.redirect)
|
|
915
|
+
return fail("invalid_grant", "redirect_uri differs");
|
|
916
|
+
// A code is for the client it was given to. A client known by its metadata document must say who it is; others may leave client_id out, as before.
|
|
917
|
+
client = typeof claims.client === "string" ? claims.client : "";
|
|
918
|
+
if (sent ? sent !== client : claimsUrl(client))
|
|
919
|
+
return fail("invalid_grant", sent ? "the code was issued to another client_id" : "client_id is required");
|
|
920
|
+
person = String(claims.person);
|
|
921
|
+
redirect = String(claims.redirect ?? "");
|
|
922
|
+
}
|
|
923
|
+
else if (form.get("grant_type") === "refresh_token") {
|
|
924
|
+
try {
|
|
925
|
+
const { payload } = await jwtVerify(form.get("refresh_token") ?? "", this.publicKey, { typ: DEV_REFRESH_TYPE, audience: `${PROTOCOL_ID}-dev-refresh` });
|
|
926
|
+
person = String(payload.person);
|
|
927
|
+
client = typeof payload.client === "string" ? payload.client : "";
|
|
928
|
+
}
|
|
929
|
+
catch {
|
|
930
|
+
return fail("invalid_grant", "unknown or expired refresh token");
|
|
931
|
+
}
|
|
932
|
+
// A refresh token stays with the metadata-document client it was issued to.
|
|
933
|
+
if (claimsUrl(client) && sent !== client)
|
|
934
|
+
return fail("invalid_grant", "the refresh token was issued to another client_id");
|
|
935
|
+
}
|
|
936
|
+
else
|
|
937
|
+
return fail("unsupported_grant_type", "authorization_code or refresh_token");
|
|
938
|
+
if (claimsUrl(client)) {
|
|
939
|
+
let metadata;
|
|
940
|
+
try {
|
|
941
|
+
metadata = await this.#client(client);
|
|
942
|
+
}
|
|
943
|
+
catch (error) {
|
|
944
|
+
return fail("invalid_client", error instanceof ClientMetadataError ? error.message : "the client's metadata document could not be read");
|
|
945
|
+
}
|
|
946
|
+
if (redirect !== null && !redirectUriAllowed(redirect, metadata.redirect_uris))
|
|
947
|
+
return fail("invalid_grant", "redirect_uri is no longer one of the client's redirect_uris");
|
|
948
|
+
// A client with a key pair proves it is itself on every grant; a public client has nothing to prove.
|
|
949
|
+
if (metadata.token_endpoint_auth_method === "private_key_jwt") {
|
|
950
|
+
const why = await this.#authenticate(metadata, form, origin);
|
|
951
|
+
if (why)
|
|
952
|
+
return json({ error: "invalid_client", error_description: why }, 401);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
const who = this.people.find((x) => x.id === person);
|
|
956
|
+
if (!who)
|
|
957
|
+
return fail("invalid_grant", "unknown person");
|
|
958
|
+
this.#origins.add(origin);
|
|
959
|
+
const access = await this.token({ person: who.id, audience: resource, issuer: origin });
|
|
960
|
+
const refresh = await new SignJWT({ person: who.id, ...(client ? { client } : {}) }).setProtectedHeader({ alg: "EdDSA", typ: DEV_REFRESH_TYPE, kid: this.key.kid }).setIssuer(origin).setAudience(`${PROTOCOL_ID}-dev-refresh`).setIssuedAt().setExpirationTime("30d").sign(this.key.privateKey);
|
|
961
|
+
return json({ access_token: access, token_type: "Bearer", expires_in: 3600, refresh_token: refresh, scope: OAUTH_SCOPE });
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
//# sourceMappingURL=auth.js.map
|