@soroi/auth 0.0.0-stage → 0.1.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/AGENTS.md +154 -0
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/account.d.ts +52 -0
- package/dist/account.js +177 -0
- package/dist/adapters/next.d.ts +6 -0
- package/dist/adapters/next.js +35 -0
- package/dist/adapters/tanstack.d.ts +12 -0
- package/dist/adapters/tanstack.js +40 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +76 -0
- package/dist/core.d.ts +122 -0
- package/dist/core.js +351 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +69 -0
- package/dist/db.d.ts +29 -0
- package/dist/db.js +55 -0
- package/dist/email.d.ts +9 -0
- package/dist/email.js +64 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.js +88 -0
- package/dist/index.d.ts +202 -0
- package/dist/index.js +255 -0
- package/dist/methods.d.ts +16 -0
- package/dist/methods.js +21 -0
- package/dist/migrations.d.ts +5 -0
- package/dist/migrations.js +154 -0
- package/dist/modules/oauth-server.d.ts +110 -0
- package/dist/modules/oauth-server.js +568 -0
- package/dist/modules/tokens.d.ts +31 -0
- package/dist/modules/tokens.js +107 -0
- package/dist/modules/two-factor.d.ts +41 -0
- package/dist/modules/two-factor.js +169 -0
- package/dist/modules/workspaces.d.ts +140 -0
- package/dist/modules/workspaces.js +297 -0
- package/dist/oauth/flow.d.ts +5 -0
- package/dist/oauth/flow.js +161 -0
- package/dist/oauth/providers.d.ts +29 -0
- package/dist/oauth/providers.js +124 -0
- package/dist/password-hash.d.ts +8 -0
- package/dist/password-hash.js +68 -0
- package/dist/password.d.ts +49 -0
- package/dist/password.js +181 -0
- package/dist/routes.d.ts +5 -0
- package/dist/routes.js +77 -0
- package/dist/sessions.d.ts +51 -0
- package/dist/sessions.js +184 -0
- package/dist/testing.d.ts +15 -0
- package/dist/testing.js +32 -0
- package/dist/types.d.ts +184 -0
- package/dist/types.js +1 -0
- package/package.json +75 -4
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { randomToken, safeEqual, sha256, sha256Base64Url } from "../crypto.js";
|
|
3
|
+
import { quoteSchema, resolveDb } from "../db.js";
|
|
4
|
+
import { AuthConfigError } from "../errors.js";
|
|
5
|
+
// An OAuth 2.1 authorization server for MCP clients: dynamic client registration (RFC 7591), the
|
|
6
|
+
// authorization code flow with PKCE S256 only, refresh token rotation and revocation (RFC 7009).
|
|
7
|
+
// The app owns the consent page and what a connection may do. This module owns clients, codes and tokens.
|
|
8
|
+
export const ACCESS_TOKEN_SECONDS = 3600;
|
|
9
|
+
export const REFRESH_TOKEN_SECONDS = 30 * 24 * 3600;
|
|
10
|
+
const CONSENT_SECONDS = 10 * 60;
|
|
11
|
+
const CODE_SECONDS = 5 * 60;
|
|
12
|
+
const MAX_REDIRECT_URIS = 10;
|
|
13
|
+
const NEW_CLIENT_MS = 60 * 60_000;
|
|
14
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
15
|
+
const BLOCKED_SCHEMES = new Set([
|
|
16
|
+
"javascript:",
|
|
17
|
+
"data:",
|
|
18
|
+
"file:",
|
|
19
|
+
"vbscript:",
|
|
20
|
+
"blob:",
|
|
21
|
+
"about:",
|
|
22
|
+
"filesystem:",
|
|
23
|
+
"ws:",
|
|
24
|
+
"wss:",
|
|
25
|
+
"ftp:",
|
|
26
|
+
]);
|
|
27
|
+
const failure = (error, description, status = 400) => ({
|
|
28
|
+
ok: false,
|
|
29
|
+
status,
|
|
30
|
+
error,
|
|
31
|
+
description,
|
|
32
|
+
});
|
|
33
|
+
/**
|
|
34
|
+
* Null when the URI may be a redirect target: https, http on a loopback host, or a private-use
|
|
35
|
+
* scheme of a native app (RFC 8252, e.g. cursor://). The consent page sends the browser there,
|
|
36
|
+
* so a script scheme would run as the signed-in user.
|
|
37
|
+
*/
|
|
38
|
+
export function redirectUriProblem(value) {
|
|
39
|
+
if (typeof value !== "string")
|
|
40
|
+
return "is not a string";
|
|
41
|
+
let url;
|
|
42
|
+
try {
|
|
43
|
+
url = new URL(value);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return "is not a URL";
|
|
47
|
+
}
|
|
48
|
+
if (value.length > 2000)
|
|
49
|
+
return "is too long";
|
|
50
|
+
// Some servers store a client's URIs joined by commas, so a comma could hide a second URI.
|
|
51
|
+
if (value.includes(","))
|
|
52
|
+
return "has a comma";
|
|
53
|
+
if (url.hash)
|
|
54
|
+
return "has a fragment";
|
|
55
|
+
if (url.username || url.password)
|
|
56
|
+
return "has a user name";
|
|
57
|
+
if (url.protocol === "https:")
|
|
58
|
+
return null;
|
|
59
|
+
if (url.protocol === "http:")
|
|
60
|
+
return LOOPBACK_HOSTS.has(url.hostname) ? null : "must use https outside localhost";
|
|
61
|
+
if (BLOCKED_SCHEMES.has(url.protocol))
|
|
62
|
+
return "uses a blocked scheme";
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
/** Exact match. Loopback redirects may use another port (RFC 8252 section 7.3). */
|
|
66
|
+
export function redirectUriMatches(registered, requested) {
|
|
67
|
+
if (registered === requested)
|
|
68
|
+
return true;
|
|
69
|
+
if (redirectUriProblem(requested))
|
|
70
|
+
return false;
|
|
71
|
+
try {
|
|
72
|
+
const a = new URL(registered);
|
|
73
|
+
const b = new URL(requested);
|
|
74
|
+
return (a.protocol === "http:" &&
|
|
75
|
+
b.protocol === "http:" &&
|
|
76
|
+
LOOPBACK_HOSTS.has(a.hostname) &&
|
|
77
|
+
a.hostname === b.hostname &&
|
|
78
|
+
a.pathname === b.pathname &&
|
|
79
|
+
a.search === b.search);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export function redirectTarget(uri) {
|
|
86
|
+
const url = new URL(uri);
|
|
87
|
+
if (url.protocol === "https:")
|
|
88
|
+
return { kind: "web", label: url.host };
|
|
89
|
+
if (url.protocol === "http:")
|
|
90
|
+
return { kind: "loopback", label: url.host };
|
|
91
|
+
return { kind: "app", label: url.protocol };
|
|
92
|
+
}
|
|
93
|
+
function redirectWith(uri, params) {
|
|
94
|
+
const url = new URL(uri);
|
|
95
|
+
for (const [key, value] of Object.entries(params))
|
|
96
|
+
if (value !== null)
|
|
97
|
+
url.searchParams.set(key, value);
|
|
98
|
+
return url.toString();
|
|
99
|
+
}
|
|
100
|
+
/** Fixed-window counters in memory, per process. */
|
|
101
|
+
export function createRateLimit(max, windowMs) {
|
|
102
|
+
const windows = new Map();
|
|
103
|
+
return (key, now = Date.now()) => {
|
|
104
|
+
const current = windows.get(key);
|
|
105
|
+
if (!current || now - current.start >= windowMs) {
|
|
106
|
+
if (windows.size > 10_000) {
|
|
107
|
+
for (const [entry, value] of windows)
|
|
108
|
+
if (now - value.start >= windowMs)
|
|
109
|
+
windows.delete(entry);
|
|
110
|
+
}
|
|
111
|
+
windows.set(key, { start: now, count: 1 });
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
if (current.count >= max)
|
|
115
|
+
return false;
|
|
116
|
+
current.count += 1;
|
|
117
|
+
return true;
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** The SQL of the module's tables, for apps that keep them in their own migrations. `s` is a quoted schema. */
|
|
121
|
+
export const oauthServerTables = (s) => [
|
|
122
|
+
`create table ${s}.oauth_client (
|
|
123
|
+
client_id text primary key,
|
|
124
|
+
client_secret_hash text,
|
|
125
|
+
name text,
|
|
126
|
+
redirect_uris jsonb not null,
|
|
127
|
+
created_at timestamptz not null default now()
|
|
128
|
+
)`,
|
|
129
|
+
`create table ${s}.oauth_authorization (
|
|
130
|
+
id uuid primary key default gen_random_uuid(),
|
|
131
|
+
client_id text not null references ${s}.oauth_client(client_id) on delete cascade,
|
|
132
|
+
user_id text not null,
|
|
133
|
+
redirect_uri text not null,
|
|
134
|
+
state text,
|
|
135
|
+
code_challenge text not null,
|
|
136
|
+
scope text not null default '',
|
|
137
|
+
resource text,
|
|
138
|
+
code_hash text unique,
|
|
139
|
+
expires_at timestamptz not null,
|
|
140
|
+
created_at timestamptz not null default now()
|
|
141
|
+
)`,
|
|
142
|
+
`create index oauth_authorization_user_idx on ${s}.oauth_authorization(user_id)`,
|
|
143
|
+
`create table ${s}.oauth_token (
|
|
144
|
+
id uuid primary key default gen_random_uuid(),
|
|
145
|
+
access_token_hash text not null unique,
|
|
146
|
+
refresh_token_hash text unique,
|
|
147
|
+
client_id text not null references ${s}.oauth_client(client_id) on delete cascade,
|
|
148
|
+
user_id text not null,
|
|
149
|
+
scope text not null default '',
|
|
150
|
+
resource text,
|
|
151
|
+
access_expires_at timestamptz not null,
|
|
152
|
+
refresh_expires_at timestamptz,
|
|
153
|
+
rotated_at timestamptz,
|
|
154
|
+
created_at timestamptz not null default now()
|
|
155
|
+
)`,
|
|
156
|
+
`create index oauth_token_client_user_idx on ${s}.oauth_token(client_id, user_id)`,
|
|
157
|
+
];
|
|
158
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
159
|
+
const VERIFIER = /^[A-Za-z0-9\-._~]{43,128}$/;
|
|
160
|
+
const CHALLENGE = /^[A-Za-z0-9\-_]{43}$/;
|
|
161
|
+
const AUTH_METHODS = ["none", "client_secret_post", "client_secret_basic"];
|
|
162
|
+
const date = (value) => new Date(value);
|
|
163
|
+
const strings = (value) => {
|
|
164
|
+
const list = typeof value === "string" ? JSON.parse(value) : value;
|
|
165
|
+
return Array.isArray(list) ? list.filter((item) => typeof item === "string") : [];
|
|
166
|
+
};
|
|
167
|
+
function credentialsOf(headers, body) {
|
|
168
|
+
// client_secret_basic form-encodes both parts (RFC 6749 section 2.3.1).
|
|
169
|
+
const basic = /^Basic\s+(\S+)$/i.exec(headers.get("authorization") ?? "")?.[1];
|
|
170
|
+
const decoded = basic ? Buffer.from(basic, "base64").toString("utf8") : "";
|
|
171
|
+
const split = decoded.indexOf(":");
|
|
172
|
+
if (split > 0) {
|
|
173
|
+
const decode = (value) => {
|
|
174
|
+
try {
|
|
175
|
+
return decodeURIComponent(value.replace(/\+/g, " "));
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return value;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
return { clientId: decode(decoded.slice(0, split)), secret: decode(decoded.slice(split + 1)) };
|
|
182
|
+
}
|
|
183
|
+
return { clientId: body.get("client_id"), secret: body.get("client_secret") };
|
|
184
|
+
}
|
|
185
|
+
async function formBody(request) {
|
|
186
|
+
if (!(request.headers.get("content-type") ?? "").includes("application/json")) {
|
|
187
|
+
return new URLSearchParams(await request.text());
|
|
188
|
+
}
|
|
189
|
+
const value = await request.json().catch(() => null);
|
|
190
|
+
const params = new URLSearchParams();
|
|
191
|
+
for (const [key, item] of Object.entries(value && typeof value === "object" ? value : {})) {
|
|
192
|
+
if (typeof item === "string")
|
|
193
|
+
params.set(key, item);
|
|
194
|
+
}
|
|
195
|
+
return params;
|
|
196
|
+
}
|
|
197
|
+
const trimSlash = (value) => value.replace(/\/+$/, "");
|
|
198
|
+
export function createOAuthServer(config) {
|
|
199
|
+
if (trimSlash(config.url) !== config.url)
|
|
200
|
+
throw new AuthConfigError("`url` of the OAuth server cannot end with a slash.");
|
|
201
|
+
const s = quoteSchema(config.schema ?? "auth");
|
|
202
|
+
const main = resolveDb(config.db);
|
|
203
|
+
const now = config.now ?? (() => new Date());
|
|
204
|
+
const paths = {
|
|
205
|
+
authorize: "/oauth/authorize",
|
|
206
|
+
token: "/oauth/token",
|
|
207
|
+
register: "/oauth/register",
|
|
208
|
+
revoke: "/oauth/revoke",
|
|
209
|
+
...config.paths,
|
|
210
|
+
};
|
|
211
|
+
const scopes = config.scopes ?? ["offline_access"];
|
|
212
|
+
const later = (seconds, at = now()) => new Date(at.getTime() + seconds * 1000).toISOString();
|
|
213
|
+
const limited = config.rateLimit ?? true;
|
|
214
|
+
const takeRegistration = createRateLimit(20, 3_600_000);
|
|
215
|
+
const takeTokenCall = createRateLimit(120, 60_000);
|
|
216
|
+
function clientIp(request) {
|
|
217
|
+
const own = config.ip?.(request);
|
|
218
|
+
if (own !== undefined)
|
|
219
|
+
return own ?? "unknown";
|
|
220
|
+
// The nearest proxy adds the last entry. A client can forge the ones before it.
|
|
221
|
+
const forwarded = request.headers.get("x-forwarded-for")?.split(",").at(-1)?.trim();
|
|
222
|
+
return forwarded || request.headers.get("x-real-ip") || "unknown";
|
|
223
|
+
}
|
|
224
|
+
// ---- clients
|
|
225
|
+
async function getClient(clientId, db = main) {
|
|
226
|
+
if (!clientId || clientId.length > 200)
|
|
227
|
+
return null;
|
|
228
|
+
const [row] = await db.query(`select client_id, client_secret_hash, name, redirect_uris, created_at from ${s}.oauth_client where client_id = $1`, [clientId]);
|
|
229
|
+
if (!row)
|
|
230
|
+
return null;
|
|
231
|
+
return {
|
|
232
|
+
clientId: String(row.client_id),
|
|
233
|
+
secretHash: row.client_secret_hash ?? null,
|
|
234
|
+
name: row.name ?? null,
|
|
235
|
+
redirectUris: strings(row.redirect_uris),
|
|
236
|
+
createdAt: date(row.created_at),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
async function registerClient(body) {
|
|
240
|
+
const input = (body && typeof body === "object" ? body : {});
|
|
241
|
+
const uris = input.redirect_uris;
|
|
242
|
+
if (!Array.isArray(uris) || uris.length === 0 || uris.length > MAX_REDIRECT_URIS) {
|
|
243
|
+
return failure("invalid_client_metadata", "Send 1 to 10 redirect URIs.");
|
|
244
|
+
}
|
|
245
|
+
for (const uri of uris) {
|
|
246
|
+
const problem = redirectUriProblem(uri);
|
|
247
|
+
if (problem)
|
|
248
|
+
return failure("invalid_redirect_uri", `The redirect URI ${problem}.`);
|
|
249
|
+
}
|
|
250
|
+
const rawName = input.client_name;
|
|
251
|
+
if (rawName !== undefined && (typeof rawName !== "string" || rawName.trim().length > 100)) {
|
|
252
|
+
return failure("invalid_client_metadata", "The client name is too long.");
|
|
253
|
+
}
|
|
254
|
+
const method = input.token_endpoint_auth_method ?? "none";
|
|
255
|
+
if (typeof method !== "string" || !AUTH_METHODS.includes(method)) {
|
|
256
|
+
return failure("invalid_client_metadata", "The token endpoint auth method is not supported.");
|
|
257
|
+
}
|
|
258
|
+
const list = (value, fallback) => value === undefined ? fallback : Array.isArray(value) && value.every((item) => typeof item === "string") ? value : null;
|
|
259
|
+
const grants = list(input.grant_types, ["authorization_code"]);
|
|
260
|
+
const responses = list(input.response_types, ["code"]);
|
|
261
|
+
if (!grants?.every((grant) => grant === "authorization_code" || grant === "refresh_token") ||
|
|
262
|
+
!responses?.every((type) => type === "code")) {
|
|
263
|
+
return failure("invalid_client_metadata", "Only the authorization code flow with refresh tokens is supported.");
|
|
264
|
+
}
|
|
265
|
+
const clientId = randomUUID();
|
|
266
|
+
const secret = method === "none" ? null : randomToken();
|
|
267
|
+
const createdAt = now();
|
|
268
|
+
const name = typeof rawName === "string" ? rawName.trim() || null : null;
|
|
269
|
+
await main.query(`insert into ${s}.oauth_client (client_id, client_secret_hash, name, redirect_uris, created_at)
|
|
270
|
+
values ($1, $2, $3, $4::text::jsonb, $5::timestamptz)`, [clientId, secret ? sha256(secret) : null, name, JSON.stringify(uris), createdAt.toISOString()]);
|
|
271
|
+
return {
|
|
272
|
+
ok: true,
|
|
273
|
+
client: {
|
|
274
|
+
client_id: clientId,
|
|
275
|
+
client_id_issued_at: Math.floor(createdAt.getTime() / 1000),
|
|
276
|
+
...(secret ? { client_secret: secret, client_secret_expires_at: 0 } : {}),
|
|
277
|
+
...(name ? { client_name: name } : {}),
|
|
278
|
+
redirect_uris: uris,
|
|
279
|
+
token_endpoint_auth_method: method,
|
|
280
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
281
|
+
response_types: ["code"],
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
async function authenticateClient(headers, body) {
|
|
286
|
+
const { clientId, secret } = credentialsOf(headers, body);
|
|
287
|
+
const client = await getClient(clientId);
|
|
288
|
+
if (!client)
|
|
289
|
+
return null;
|
|
290
|
+
if (client.secretHash && (!secret || !safeEqual(sha256(secret), client.secretHash)))
|
|
291
|
+
return null;
|
|
292
|
+
return client;
|
|
293
|
+
}
|
|
294
|
+
// ---- authorize and consent
|
|
295
|
+
function resourceOf(value) {
|
|
296
|
+
if (value === null)
|
|
297
|
+
return config.resource;
|
|
298
|
+
const asked = trimSlash(value);
|
|
299
|
+
return asked === trimSlash(config.resource) || asked === config.url ? config.resource : null;
|
|
300
|
+
}
|
|
301
|
+
async function checkAuthorize(params) {
|
|
302
|
+
const client = await getClient(params.get("client_id"));
|
|
303
|
+
if (!client)
|
|
304
|
+
return { ok: false, kind: "page", message: "This agent is not registered. Connect it again." };
|
|
305
|
+
const requested = params.get("redirect_uri") ?? (client.redirectUris.length === 1 ? client.redirectUris[0] : null);
|
|
306
|
+
// The check also covers clients that were stored before the rules of redirectUriProblem.
|
|
307
|
+
if (!requested || redirectUriProblem(requested) || !client.redirectUris.some((uri) => redirectUriMatches(uri, requested))) {
|
|
308
|
+
return { ok: false, kind: "page", message: "The agent asked to return to an address it did not register." };
|
|
309
|
+
}
|
|
310
|
+
const state = params.get("state");
|
|
311
|
+
const refuse = (error, description) => ({
|
|
312
|
+
ok: false,
|
|
313
|
+
kind: "redirect",
|
|
314
|
+
location: redirectWith(requested, { error, error_description: description, state }),
|
|
315
|
+
});
|
|
316
|
+
if (params.get("response_type") !== "code")
|
|
317
|
+
return refuse("unsupported_response_type", "Only response_type=code is supported.");
|
|
318
|
+
const codeChallenge = params.get("code_challenge") ?? "";
|
|
319
|
+
if (params.get("code_challenge_method") !== "S256" || !CHALLENGE.test(codeChallenge)) {
|
|
320
|
+
return refuse("invalid_request", "PKCE with S256 is required.");
|
|
321
|
+
}
|
|
322
|
+
if (!resourceOf(params.get("resource")))
|
|
323
|
+
return refuse("invalid_target", "This server has no such resource.");
|
|
324
|
+
return {
|
|
325
|
+
ok: true,
|
|
326
|
+
request: { clientId: client.clientId, redirectUri: requested, state, codeChallenge, scope: (params.get("scope") ?? "").slice(0, 500) },
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
async function createAuthorization(request, userId) {
|
|
330
|
+
const at = now();
|
|
331
|
+
await main.query(`delete from ${s}.oauth_authorization where expires_at < $1::timestamptz`, [later(-86_400, at)]);
|
|
332
|
+
const [row] = await main.query(`insert into ${s}.oauth_authorization (client_id, user_id, redirect_uri, state, code_challenge, scope, resource, expires_at, created_at)
|
|
333
|
+
values ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz, $9::timestamptz) returning id::text as id`, [
|
|
334
|
+
request.clientId,
|
|
335
|
+
userId,
|
|
336
|
+
request.redirectUri,
|
|
337
|
+
request.state,
|
|
338
|
+
request.codeChallenge,
|
|
339
|
+
request.scope,
|
|
340
|
+
config.resource,
|
|
341
|
+
later(CONSENT_SECONDS, at),
|
|
342
|
+
at.toISOString(),
|
|
343
|
+
]);
|
|
344
|
+
return row.id;
|
|
345
|
+
}
|
|
346
|
+
/** A consent of this person that nobody answered yet, or null. */
|
|
347
|
+
async function pending(input, db = main) {
|
|
348
|
+
if (!UUID.test(input.consentCode))
|
|
349
|
+
return null;
|
|
350
|
+
const [row] = await db.query(`select a.id::text as id, a.client_id, a.redirect_uri, a.expires_at, c.name, c.created_at as client_created_at
|
|
351
|
+
from ${s}.oauth_authorization a join ${s}.oauth_client c on c.client_id = a.client_id
|
|
352
|
+
where a.id = $1::uuid and a.user_id = $2 and a.code_hash is null`, [input.consentCode, input.userId]);
|
|
353
|
+
if (!row || redirectUriProblem(row.redirect_uri))
|
|
354
|
+
return null;
|
|
355
|
+
return {
|
|
356
|
+
id: String(row.id),
|
|
357
|
+
clientId: String(row.client_id),
|
|
358
|
+
clientName: row.name ?? null,
|
|
359
|
+
expired: date(row.expires_at) <= now(),
|
|
360
|
+
redirect: redirectTarget(String(row.redirect_uri)),
|
|
361
|
+
justRegistered: now().getTime() - date(row.client_created_at).getTime() < NEW_CLIENT_MS,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Turns the consent into a one-time code. Returns where the browser goes next, or null when the consent is
|
|
366
|
+
* gone, expired or answered. Pass the transaction that stores the app's own grant.
|
|
367
|
+
*/
|
|
368
|
+
async function approve(input, db = main) {
|
|
369
|
+
if (!(await pending(input, db)))
|
|
370
|
+
return null;
|
|
371
|
+
const code = randomToken();
|
|
372
|
+
const [row] = await db.query(`update ${s}.oauth_authorization set code_hash = $3, expires_at = $4::timestamptz
|
|
373
|
+
where id = $1::uuid and user_id = $2 and code_hash is null and expires_at > $5::timestamptz
|
|
374
|
+
returning redirect_uri, state`, [input.consentCode, input.userId, sha256(code), later(CODE_SECONDS), now().toISOString()]);
|
|
375
|
+
return row ? redirectWith(row.redirect_uri, { code, state: row.state }) : null;
|
|
376
|
+
}
|
|
377
|
+
/** Deletes the consent. Returns the client's redirect with `access_denied`, or null when there is no such consent. */
|
|
378
|
+
async function deny(input, db = main) {
|
|
379
|
+
if (!(await pending(input, db)))
|
|
380
|
+
return null;
|
|
381
|
+
const [row] = await db.query(`delete from ${s}.oauth_authorization where id = $1::uuid and user_id = $2 and code_hash is null returning redirect_uri, state`, [input.consentCode, input.userId]);
|
|
382
|
+
return row ? redirectWith(row.redirect_uri, { error: "access_denied", state: row.state }) : null;
|
|
383
|
+
}
|
|
384
|
+
// ---- tokens
|
|
385
|
+
async function issueTokens(tx, owner) {
|
|
386
|
+
const at = now();
|
|
387
|
+
const accessToken = randomToken();
|
|
388
|
+
const refreshToken = randomToken();
|
|
389
|
+
await tx.query(`insert into ${s}.oauth_token (access_token_hash, refresh_token_hash, client_id, user_id, scope, resource,
|
|
390
|
+
access_expires_at, refresh_expires_at, created_at)
|
|
391
|
+
values ($1, $2, $3, $4, $5, $6, $7::timestamptz, $8::timestamptz, $9::timestamptz)`, [
|
|
392
|
+
sha256(accessToken),
|
|
393
|
+
sha256(refreshToken),
|
|
394
|
+
owner.clientId,
|
|
395
|
+
owner.userId,
|
|
396
|
+
owner.scope,
|
|
397
|
+
owner.resource,
|
|
398
|
+
later(ACCESS_TOKEN_SECONDS, at),
|
|
399
|
+
later(REFRESH_TOKEN_SECONDS, at),
|
|
400
|
+
at.toISOString(),
|
|
401
|
+
]);
|
|
402
|
+
// A rotated row only matters for reuse detection while its refresh token could still be valid.
|
|
403
|
+
await tx.query(`delete from ${s}.oauth_token where client_id = $1 and user_id = $2
|
|
404
|
+
and coalesce(refresh_expires_at, access_expires_at) < $3::timestamptz`, [owner.clientId, owner.userId, at.toISOString()]);
|
|
405
|
+
return {
|
|
406
|
+
access_token: accessToken,
|
|
407
|
+
token_type: "Bearer",
|
|
408
|
+
expires_in: ACCESS_TOKEN_SECONDS,
|
|
409
|
+
refresh_token: refreshToken,
|
|
410
|
+
scope: owner.scope,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/** Deletes the tokens and open consents of one connection. */
|
|
414
|
+
async function revokeConnection(input, db = main) {
|
|
415
|
+
await db.query(`delete from ${s}.oauth_token where client_id = $1 and user_id = $2`, [input.clientId, input.userId]);
|
|
416
|
+
await db.query(`delete from ${s}.oauth_authorization where client_id = $1 and user_id = $2`, [input.clientId, input.userId]);
|
|
417
|
+
}
|
|
418
|
+
async function exchangeCode(clientId, body) {
|
|
419
|
+
const code = body.get("code");
|
|
420
|
+
const verifier = body.get("code_verifier") ?? "";
|
|
421
|
+
if (!code || !VERIFIER.test(verifier))
|
|
422
|
+
return failure("invalid_request", "code and a valid code_verifier are needed.");
|
|
423
|
+
if (!resourceOf(body.get("resource")))
|
|
424
|
+
return failure("invalid_target", "This server has no such resource.");
|
|
425
|
+
return main.transaction(async (tx) => {
|
|
426
|
+
// Deleting the row makes the code single-use, even for two requests at once.
|
|
427
|
+
const [row] = await tx.query(`delete from ${s}.oauth_authorization where code_hash = $1
|
|
428
|
+
returning client_id, user_id, redirect_uri, code_challenge, scope, resource, expires_at`, [sha256(code)]);
|
|
429
|
+
if (!row || row.client_id !== clientId || date(row.expires_at) <= now() || row.resource !== config.resource) {
|
|
430
|
+
return failure("invalid_grant", "The code is not valid.");
|
|
431
|
+
}
|
|
432
|
+
const redirectUri = body.get("redirect_uri");
|
|
433
|
+
if (redirectUri !== null && redirectUri !== row.redirect_uri)
|
|
434
|
+
return failure("invalid_grant", "redirect_uri does not match.");
|
|
435
|
+
if (!safeEqual(sha256Base64Url(verifier), String(row.code_challenge))) {
|
|
436
|
+
return failure("invalid_grant", "code_verifier does not match.");
|
|
437
|
+
}
|
|
438
|
+
const owner = { clientId, userId: String(row.user_id), scope: String(row.scope), resource: config.resource };
|
|
439
|
+
if (!(await config.isConnected(tx, owner)))
|
|
440
|
+
return failure("invalid_grant", "The connection was removed.");
|
|
441
|
+
return { ok: true, tokens: await issueTokens(tx, owner) };
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
const ownTokens = `(resource is null or resource = $2)`;
|
|
445
|
+
async function refresh(clientId, body) {
|
|
446
|
+
const token = body.get("refresh_token");
|
|
447
|
+
if (!token)
|
|
448
|
+
return failure("invalid_request", "refresh_token is needed.");
|
|
449
|
+
if (!resourceOf(body.get("resource")))
|
|
450
|
+
return failure("invalid_target", "This server has no such resource.");
|
|
451
|
+
const [row] = await main.query(`select id::text as id, client_id, user_id, scope, resource, refresh_expires_at, rotated_at
|
|
452
|
+
from ${s}.oauth_token where refresh_token_hash = $1 and ${ownTokens}`, [sha256(token), config.resource]);
|
|
453
|
+
if (!row || row.client_id !== clientId)
|
|
454
|
+
return failure("invalid_grant", "The refresh token is not valid.");
|
|
455
|
+
const owner = { clientId, userId: String(row.user_id), scope: String(row.scope), resource: config.resource };
|
|
456
|
+
if (row.rotated_at) {
|
|
457
|
+
// A used refresh token came back: someone may have copied it. End the whole connection's tokens.
|
|
458
|
+
await revokeConnection(owner);
|
|
459
|
+
return failure("invalid_grant", "The refresh token was already used.");
|
|
460
|
+
}
|
|
461
|
+
if (!row.refresh_expires_at || date(row.refresh_expires_at) <= now())
|
|
462
|
+
return failure("invalid_grant", "The refresh token expired.");
|
|
463
|
+
if (!(await config.isConnected(main, owner)))
|
|
464
|
+
return failure("invalid_grant", "The connection was removed.");
|
|
465
|
+
return main.transaction(async (tx) => {
|
|
466
|
+
const rotated = await tx.query(`update ${s}.oauth_token set rotated_at = $2::timestamptz where id = $1::uuid and rotated_at is null returning 1 as done`, [row.id, now().toISOString()]);
|
|
467
|
+
if (!rotated.length)
|
|
468
|
+
return failure("invalid_grant", "The refresh token was already used.");
|
|
469
|
+
return { ok: true, tokens: await issueTokens(tx, owner) };
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
async function exchange(headers, body) {
|
|
473
|
+
const client = await authenticateClient(headers, body);
|
|
474
|
+
if (!client)
|
|
475
|
+
return failure("invalid_client", "Unknown client.", 401);
|
|
476
|
+
const grant = body.get("grant_type");
|
|
477
|
+
if (grant === "authorization_code")
|
|
478
|
+
return exchangeCode(client.clientId, body);
|
|
479
|
+
if (grant === "refresh_token")
|
|
480
|
+
return refresh(client.clientId, body);
|
|
481
|
+
return failure("unsupported_grant_type", "Use authorization_code or refresh_token.");
|
|
482
|
+
}
|
|
483
|
+
/** The client and user of a live access token for this resource, or null. */
|
|
484
|
+
async function verifyAccessToken(token) {
|
|
485
|
+
if (!token || token.length > 200)
|
|
486
|
+
return null;
|
|
487
|
+
const [row] = await main.query(`select client_id, user_id, scope from ${s}.oauth_token
|
|
488
|
+
where access_token_hash = $1 and ${ownTokens} and access_expires_at > $3::timestamptz`, [sha256(token), config.resource, now().toISOString()]);
|
|
489
|
+
return row ? { clientId: String(row.client_id), userId: String(row.user_id), scope: String(row.scope) } : null;
|
|
490
|
+
}
|
|
491
|
+
// ---- HTTP
|
|
492
|
+
const headersOf = (cache = "no-store") => ({ ...config.headers, "cache-control": cache });
|
|
493
|
+
const json = (body, status = 200, cache) => Response.json(body, { status, headers: headersOf(cache) });
|
|
494
|
+
const errorResponse = (result) => json({ error: result.error, error_description: result.description }, result.status);
|
|
495
|
+
const tooMany = () => json({ error: "rate_limited", error_description: "Try again later." }, 429);
|
|
496
|
+
const redirect = (location) => new Response(null, { status: 302, headers: { location } });
|
|
497
|
+
const handlers = {
|
|
498
|
+
async register(request) {
|
|
499
|
+
if (limited && !takeRegistration(clientIp(request)))
|
|
500
|
+
return tooMany();
|
|
501
|
+
const result = await registerClient(await request.json().catch(() => null));
|
|
502
|
+
return result.ok ? json(result.client, 201) : errorResponse(result);
|
|
503
|
+
},
|
|
504
|
+
/** Checks the client first, then the sign-in. A signed-in person always lands on the consent page. */
|
|
505
|
+
async authorize(request) {
|
|
506
|
+
const url = new URL(request.url);
|
|
507
|
+
const check = await checkAuthorize(url.searchParams);
|
|
508
|
+
if (!check.ok && check.kind === "redirect")
|
|
509
|
+
return redirect(check.location);
|
|
510
|
+
if (!check.ok) {
|
|
511
|
+
return new Response(`${config.name} could not connect the agent. ${check.message}`, {
|
|
512
|
+
status: 400,
|
|
513
|
+
headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
const viewer = await config.viewer(request);
|
|
517
|
+
if (!viewer)
|
|
518
|
+
return redirect(config.signIn(`${config.url}${paths.authorize}${url.search}`));
|
|
519
|
+
const consentCode = await createAuthorization(check.request, viewer.id);
|
|
520
|
+
const separator = config.consentPage.includes("?") ? "&" : "?";
|
|
521
|
+
return redirect(`${config.consentPage}${separator}consent_code=${encodeURIComponent(consentCode)}`);
|
|
522
|
+
},
|
|
523
|
+
async token(request) {
|
|
524
|
+
if (limited && !takeTokenCall(clientIp(request)))
|
|
525
|
+
return tooMany();
|
|
526
|
+
const result = await exchange(request.headers, await formBody(request));
|
|
527
|
+
return result.ok ? json(result.tokens) : errorResponse(result);
|
|
528
|
+
},
|
|
529
|
+
/** Answers ok for unknown tokens too, so callers learn nothing. */
|
|
530
|
+
async revoke(request) {
|
|
531
|
+
if (limited && !takeTokenCall(clientIp(request)))
|
|
532
|
+
return tooMany();
|
|
533
|
+
const body = await formBody(request);
|
|
534
|
+
const client = await authenticateClient(request.headers, body);
|
|
535
|
+
if (!client)
|
|
536
|
+
return errorResponse(failure("invalid_client", "Unknown client.", 401));
|
|
537
|
+
const token = body.get("token");
|
|
538
|
+
if (token) {
|
|
539
|
+
await main.query(`delete from ${s}.oauth_token where client_id = $1 and (access_token_hash = $2 or refresh_token_hash = $2)`, [client.clientId, sha256(token)]);
|
|
540
|
+
}
|
|
541
|
+
return new Response(null, { status: 200, headers: headersOf() });
|
|
542
|
+
},
|
|
543
|
+
preflight: () => new Response(null, { status: 204, headers: config.headers }),
|
|
544
|
+
/** RFC 8414, for `/.well-known/oauth-authorization-server`. */
|
|
545
|
+
serverMetadata: () => json({
|
|
546
|
+
issuer: config.url,
|
|
547
|
+
authorization_endpoint: `${config.url}${paths.authorize}`,
|
|
548
|
+
token_endpoint: `${config.url}${paths.token}`,
|
|
549
|
+
registration_endpoint: `${config.url}${paths.register}`,
|
|
550
|
+
revocation_endpoint: `${config.url}${paths.revoke}`,
|
|
551
|
+
response_types_supported: ["code"],
|
|
552
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
553
|
+
code_challenge_methods_supported: ["S256"],
|
|
554
|
+
token_endpoint_auth_methods_supported: AUTH_METHODS,
|
|
555
|
+
revocation_endpoint_auth_methods_supported: AUTH_METHODS,
|
|
556
|
+
scopes_supported: scopes,
|
|
557
|
+
}, 200, "max-age=3600"),
|
|
558
|
+
/** RFC 9728, for `/.well-known/oauth-protected-resource`. */
|
|
559
|
+
resourceMetadata: () => json({
|
|
560
|
+
resource: config.resource,
|
|
561
|
+
resource_name: config.name,
|
|
562
|
+
authorization_servers: [config.url],
|
|
563
|
+
scopes_supported: scopes,
|
|
564
|
+
bearer_methods_supported: ["header"],
|
|
565
|
+
}, 200, "max-age=3600"),
|
|
566
|
+
};
|
|
567
|
+
return { handlers, pending, approve, deny, verifyAccessToken, revokeConnection };
|
|
568
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type Core, type RequestContext, type SessionWithUser } from "../core.js";
|
|
2
|
+
export type ApiToken = {
|
|
3
|
+
id: string;
|
|
4
|
+
name: string;
|
|
5
|
+
prefix: string;
|
|
6
|
+
scopes: string[];
|
|
7
|
+
workspaceId: string | null;
|
|
8
|
+
createdAt: Date;
|
|
9
|
+
lastUsedAt: Date | null;
|
|
10
|
+
expiresAt: Date | null;
|
|
11
|
+
};
|
|
12
|
+
/** Returns the token once. Only its hash is stored. */
|
|
13
|
+
export declare function create(core: Core, ctx: RequestContext, input: {
|
|
14
|
+
name: string;
|
|
15
|
+
scopes?: string[];
|
|
16
|
+
expiresInDays?: number;
|
|
17
|
+
workspaceId?: string;
|
|
18
|
+
password?: string;
|
|
19
|
+
}): Promise<{
|
|
20
|
+
ok: true;
|
|
21
|
+
token: string;
|
|
22
|
+
apiToken: ApiToken;
|
|
23
|
+
}>;
|
|
24
|
+
export declare function list(core: Core, ctx: RequestContext): Promise<ApiToken[]>;
|
|
25
|
+
export declare function revoke(core: Core, ctx: RequestContext, input: {
|
|
26
|
+
id: string;
|
|
27
|
+
}): Promise<{
|
|
28
|
+
ok: true;
|
|
29
|
+
}>;
|
|
30
|
+
/** Resolves `Authorization: Bearer <token>`. Registered on the core when the module is on. */
|
|
31
|
+
export declare function bearer(core: Core, ctx: RequestContext): Promise<SessionWithUser | null>;
|