@20baht/elysia-oauth-provider 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +655 -2
- package/dist/config.d.ts +37 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/core/bearer.d.ts +11 -0
- package/dist/core/bearer.d.ts.map +1 -0
- package/dist/core/pkce.d.ts +6 -0
- package/dist/core/pkce.d.ts.map +1 -0
- package/dist/core/provider.d.ts +109 -0
- package/dist/core/provider.d.ts.map +1 -0
- package/dist/core/rate-limit.d.ts +61 -0
- package/dist/core/rate-limit.d.ts.map +1 -0
- package/dist/core/redirect-uri.d.ts +19 -0
- package/dist/core/redirect-uri.d.ts.map +1 -0
- package/dist/core/resource.d.ts +19 -0
- package/dist/core/resource.d.ts.map +1 -0
- package/dist/core/scope.d.ts +7 -0
- package/dist/core/scope.d.ts.map +1 -0
- package/dist/crypto/hash.d.ts +10 -0
- package/dist/crypto/hash.d.ts.map +1 -0
- package/dist/crypto/jwt.d.ts +51 -0
- package/dist/crypto/jwt.d.ts.map +1 -0
- package/dist/crypto/props-encryption.d.ts +14 -0
- package/dist/crypto/props-encryption.d.ts.map +1 -0
- package/dist/crypto/random.d.ts +8 -0
- package/dist/crypto/random.d.ts.map +1 -0
- package/dist/endpoints/authorize.d.ts +4 -0
- package/dist/endpoints/authorize.d.ts.map +1 -0
- package/dist/endpoints/http.d.ts +27 -0
- package/dist/endpoints/http.d.ts.map +1 -0
- package/dist/endpoints/metadata.d.ts +9 -0
- package/dist/endpoints/metadata.d.ts.map +1 -0
- package/dist/endpoints/register.d.ts +4 -0
- package/dist/endpoints/register.d.ts.map +1 -0
- package/dist/endpoints/revoke.d.ts +4 -0
- package/dist/endpoints/revoke.d.ts.map +1 -0
- package/dist/endpoints/token.d.ts +4 -0
- package/dist/endpoints/token.d.ts.map +1 -0
- package/dist/errors.d.ts +42 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2376 -0
- package/dist/index.js.map +33 -0
- package/dist/plugin.d.ts +426 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/storage/conformance.d.ts +36 -0
- package/dist/storage/conformance.d.ts.map +1 -0
- package/dist/storage/conformance.js +163 -0
- package/dist/storage/conformance.js.map +10 -0
- package/dist/storage/keys.d.ts +33 -0
- package/dist/storage/keys.d.ts.map +1 -0
- package/dist/storage/memory.d.ts +35 -0
- package/dist/storage/memory.d.ts.map +1 -0
- package/dist/storage/redis.d.ts +83 -0
- package/dist/storage/redis.d.ts.map +1 -0
- package/dist/storage/redis.js +135 -0
- package/dist/storage/redis.js.map +10 -0
- package/dist/storage/types.d.ts +61 -0
- package/dist/storage/types.d.ts.map +1 -0
- package/dist/types.d.ts +329 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +67 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,2376 @@
|
|
|
1
|
+
// src/storage/redis.ts
|
|
2
|
+
var REDIS_SCRIPTS = {
|
|
3
|
+
consume: `local v = redis.call('GET', KEYS[1])
|
|
4
|
+
if v then redis.call('DEL', KEYS[1]) end
|
|
5
|
+
return v`,
|
|
6
|
+
compareAndSet: `local cur = redis.call('GET', KEYS[1])
|
|
7
|
+
if not cur then return 0 end
|
|
8
|
+
local ok, doc = pcall(cjson.decode, cur)
|
|
9
|
+
if not ok or type(doc) ~= 'table' or tostring(doc.version) ~= ARGV[1] then return 0 end
|
|
10
|
+
if ARGV[3] == '' then redis.call('SET', KEYS[1], ARGV[2]) else redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3]) end
|
|
11
|
+
return 1`,
|
|
12
|
+
compareAndDelete: `local cur = redis.call('GET', KEYS[1])
|
|
13
|
+
if not cur then return 0 end
|
|
14
|
+
local ok, doc = pcall(cjson.decode, cur)
|
|
15
|
+
if not ok or type(doc) ~= 'table' or tostring(doc.version) ~= ARGV[1] then return 0 end
|
|
16
|
+
redis.call('DEL', KEYS[1])
|
|
17
|
+
return 1`
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
class RedisStorage {
|
|
21
|
+
#client;
|
|
22
|
+
#prefix;
|
|
23
|
+
#scanCount;
|
|
24
|
+
#ownsClient;
|
|
25
|
+
constructor(client, options = {}) {
|
|
26
|
+
this.#client = client;
|
|
27
|
+
this.#prefix = options.keyPrefix ?? "";
|
|
28
|
+
this.#scanCount = options.scanCount ?? 500;
|
|
29
|
+
this.#ownsClient = options.ownsClient ?? false;
|
|
30
|
+
if (!client.eval && !client.send) {
|
|
31
|
+
throw new TypeError("RedisStorage: client must expose eval() or send() for EVAL");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
#eval(script, key, args) {
|
|
35
|
+
const c = this.#client;
|
|
36
|
+
if (c.eval)
|
|
37
|
+
return c.eval(script, 1, key, ...args);
|
|
38
|
+
return c.send("EVAL", [script, "1", key, ...args]);
|
|
39
|
+
}
|
|
40
|
+
async get(key) {
|
|
41
|
+
const raw = await this.#client.get(this.#prefix + key);
|
|
42
|
+
if (raw === null || raw === undefined)
|
|
43
|
+
return null;
|
|
44
|
+
return JSON.parse(raw);
|
|
45
|
+
}
|
|
46
|
+
async set(key, value, opts) {
|
|
47
|
+
const raw = JSON.stringify(value);
|
|
48
|
+
const ttl = opts?.ttlSeconds;
|
|
49
|
+
if (ttl === undefined)
|
|
50
|
+
await this.#client.set(this.#prefix + key, raw);
|
|
51
|
+
else
|
|
52
|
+
await this.#client.set(this.#prefix + key, raw, "EX", Math.max(1, Math.ceil(ttl)));
|
|
53
|
+
}
|
|
54
|
+
async delete(key) {
|
|
55
|
+
await this.#client.del(this.#prefix + key);
|
|
56
|
+
}
|
|
57
|
+
async consume(key) {
|
|
58
|
+
const raw = await this.#eval(REDIS_SCRIPTS.consume, this.#prefix + key, []);
|
|
59
|
+
if (typeof raw !== "string")
|
|
60
|
+
return null;
|
|
61
|
+
return JSON.parse(raw);
|
|
62
|
+
}
|
|
63
|
+
async compareAndSet(key, expectedVersion, value, opts) {
|
|
64
|
+
const ttl = opts?.ttlSeconds;
|
|
65
|
+
const result = await this.#eval(REDIS_SCRIPTS.compareAndSet, this.#prefix + key, [
|
|
66
|
+
String(expectedVersion),
|
|
67
|
+
JSON.stringify(value),
|
|
68
|
+
ttl === undefined ? "" : String(Math.max(1, Math.ceil(ttl)))
|
|
69
|
+
]);
|
|
70
|
+
return Number(result) === 1;
|
|
71
|
+
}
|
|
72
|
+
async compareAndDelete(key, expectedVersion) {
|
|
73
|
+
const result = await this.#eval(REDIS_SCRIPTS.compareAndDelete, this.#prefix + key, [
|
|
74
|
+
String(expectedVersion)
|
|
75
|
+
]);
|
|
76
|
+
return Number(result) === 1;
|
|
77
|
+
}
|
|
78
|
+
async list(prefix) {
|
|
79
|
+
const pattern = escapeGlob(this.#prefix + prefix) + "*";
|
|
80
|
+
const out = [];
|
|
81
|
+
let cursor = "0";
|
|
82
|
+
do {
|
|
83
|
+
const [next, keys] = await this.#client.scan(cursor, "MATCH", pattern, "COUNT", this.#scanCount);
|
|
84
|
+
for (const k of keys)
|
|
85
|
+
out.push(k.slice(this.#prefix.length));
|
|
86
|
+
cursor = next;
|
|
87
|
+
} while (cursor !== "0");
|
|
88
|
+
return [...new Set(out)];
|
|
89
|
+
}
|
|
90
|
+
async close() {
|
|
91
|
+
if (!this.#ownsClient)
|
|
92
|
+
return;
|
|
93
|
+
if (this.#client.quit)
|
|
94
|
+
await this.#client.quit();
|
|
95
|
+
else if (this.#client.close)
|
|
96
|
+
await this.#client.close();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function escapeGlob(s) {
|
|
100
|
+
return s.replace(/[\\*?[\]]/g, (c) => `\\${c}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
class RedisRateLimiter {
|
|
104
|
+
#client;
|
|
105
|
+
#prefix;
|
|
106
|
+
constructor(client, options = {}) {
|
|
107
|
+
this.#client = client;
|
|
108
|
+
this.#prefix = options.keyPrefix ?? "ratelimit:";
|
|
109
|
+
}
|
|
110
|
+
async hit(key, rule) {
|
|
111
|
+
const k = this.#prefix + key;
|
|
112
|
+
const count = await this.#client.incr(k);
|
|
113
|
+
if (count === 1)
|
|
114
|
+
await this.#client.expire(k, rule.windowSeconds);
|
|
115
|
+
let ttl = await this.#client.ttl(k);
|
|
116
|
+
if (ttl < 0) {
|
|
117
|
+
await this.#client.expire(k, rule.windowSeconds);
|
|
118
|
+
ttl = rule.windowSeconds;
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
allowed: count <= rule.max,
|
|
122
|
+
remaining: Math.max(0, rule.max - count),
|
|
123
|
+
retryAfterSeconds: Math.max(1, ttl)
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/plugin.ts
|
|
129
|
+
import { Elysia } from "elysia";
|
|
130
|
+
|
|
131
|
+
// src/storage/types.ts
|
|
132
|
+
var ATOMIC_METHODS = ["consume", "compareAndSet", "compareAndDelete"];
|
|
133
|
+
function assertStorageContract(storage) {
|
|
134
|
+
const candidate = storage;
|
|
135
|
+
const missing = ATOMIC_METHODS.filter((m) => typeof candidate[m] !== "function");
|
|
136
|
+
if (missing.length > 0) {
|
|
137
|
+
throw new TypeError(`oauthProvider: storage must implement ${missing.join(", ")} atomically (see the storage adapter docs)`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// src/core/rate-limit.ts
|
|
142
|
+
var DEFAULT_RATE_LIMITS = {
|
|
143
|
+
token: { max: 30, windowSeconds: 60 },
|
|
144
|
+
register: { max: 10, windowSeconds: 3600 },
|
|
145
|
+
authorize: { max: 60, windowSeconds: 60 },
|
|
146
|
+
revoke: { max: 30, windowSeconds: 60 }
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
class MemoryRateLimiter {
|
|
150
|
+
#buckets = new Map;
|
|
151
|
+
#now;
|
|
152
|
+
#ops = 0;
|
|
153
|
+
constructor(options = {}) {
|
|
154
|
+
this.#now = options.now ?? Date.now;
|
|
155
|
+
}
|
|
156
|
+
async hit(key, rule) {
|
|
157
|
+
const now = this.#now();
|
|
158
|
+
let b = this.#buckets.get(key);
|
|
159
|
+
if (!b || b.resetAt <= now) {
|
|
160
|
+
b = { count: 0, resetAt: now + rule.windowSeconds * 1000 };
|
|
161
|
+
this.#buckets.set(key, b);
|
|
162
|
+
}
|
|
163
|
+
b.count++;
|
|
164
|
+
if (++this.#ops % 1000 === 0)
|
|
165
|
+
this.sweep();
|
|
166
|
+
const retryAfterSeconds = Math.max(1, Math.ceil((b.resetAt - now) / 1000));
|
|
167
|
+
return {
|
|
168
|
+
allowed: b.count <= rule.max,
|
|
169
|
+
remaining: Math.max(0, rule.max - b.count),
|
|
170
|
+
retryAfterSeconds
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
sweep() {
|
|
174
|
+
const now = this.#now();
|
|
175
|
+
for (const [k, b] of this.#buckets)
|
|
176
|
+
if (b.resetAt <= now)
|
|
177
|
+
this.#buckets.delete(k);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function clientIpFrom(request, socketIp, trustProxy) {
|
|
181
|
+
if (typeof trustProxy === "string") {
|
|
182
|
+
const value = request.headers.get(trustProxy);
|
|
183
|
+
if (value)
|
|
184
|
+
return value;
|
|
185
|
+
} else if (trustProxy) {
|
|
186
|
+
const xff = request.headers.get("x-forwarded-for");
|
|
187
|
+
const first = xff?.split(",")[0]?.trim();
|
|
188
|
+
if (first)
|
|
189
|
+
return first;
|
|
190
|
+
}
|
|
191
|
+
return socketIp;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// src/config.ts
|
|
195
|
+
var DEFAULT_PATHS = {
|
|
196
|
+
authorize: "/authorize",
|
|
197
|
+
token: "/token",
|
|
198
|
+
register: "/register",
|
|
199
|
+
revoke: "/revoke",
|
|
200
|
+
jwks: "/.well-known/jwks.json"
|
|
201
|
+
};
|
|
202
|
+
var DAY = 24 * 60 * 60;
|
|
203
|
+
function resolveConfig(config) {
|
|
204
|
+
if (!config.issuer)
|
|
205
|
+
throw new TypeError("oauthProvider: `issuer` is required");
|
|
206
|
+
let issuerUrl;
|
|
207
|
+
try {
|
|
208
|
+
issuerUrl = new URL(config.issuer);
|
|
209
|
+
} catch {
|
|
210
|
+
throw new TypeError("oauthProvider: `issuer` must be an absolute URL");
|
|
211
|
+
}
|
|
212
|
+
if (issuerUrl.protocol !== "https:" && issuerUrl.protocol !== "http:") {
|
|
213
|
+
throw new TypeError("oauthProvider: `issuer` must be http(s)");
|
|
214
|
+
}
|
|
215
|
+
if (issuerUrl.search || issuerUrl.hash) {
|
|
216
|
+
throw new TypeError("oauthProvider: `issuer` must not contain a query or fragment");
|
|
217
|
+
}
|
|
218
|
+
const issuer = config.issuer.replace(/\/+$/, "");
|
|
219
|
+
if (!config.storage)
|
|
220
|
+
throw new TypeError("oauthProvider: `storage` is required");
|
|
221
|
+
assertStorageContract(config.storage);
|
|
222
|
+
if (typeof config.handleAuthorize !== "function") {
|
|
223
|
+
throw new TypeError("oauthProvider: `handleAuthorize` is required");
|
|
224
|
+
}
|
|
225
|
+
if (config.accessTokenClaims && (config.tokenFormat ?? "opaque") === "opaque") {
|
|
226
|
+
throw new TypeError("oauthProvider: `accessTokenClaims` requires a JWT `tokenFormat`");
|
|
227
|
+
}
|
|
228
|
+
const paths = { ...DEFAULT_PATHS, ...stripUndefined(config.paths ?? {}) };
|
|
229
|
+
for (const [name, p] of Object.entries(paths)) {
|
|
230
|
+
if (!p.startsWith("/"))
|
|
231
|
+
throw new TypeError(`oauthProvider: paths.${name} must start with '/'`);
|
|
232
|
+
}
|
|
233
|
+
const basePath = issuerUrl.pathname.replace(/\/+$/, "");
|
|
234
|
+
const abs = (p) => `${issuerUrl.origin}${basePath}${p}`;
|
|
235
|
+
const ttl = (name, value, def, min = 1) => {
|
|
236
|
+
const v = value ?? def;
|
|
237
|
+
if (!Number.isInteger(v) || v < min) {
|
|
238
|
+
throw new TypeError(`oauthProvider: ${name} must be an integer >= ${min}`);
|
|
239
|
+
}
|
|
240
|
+
return v;
|
|
241
|
+
};
|
|
242
|
+
const scopesSupported = config.scopesSupported;
|
|
243
|
+
if (!Array.isArray(scopesSupported) || scopesSupported.length === 0) {
|
|
244
|
+
throw new TypeError("oauthProvider: `scopesSupported` must list at least one scope");
|
|
245
|
+
}
|
|
246
|
+
for (const s of scopesSupported) {
|
|
247
|
+
if (!isValidScopeToken(s))
|
|
248
|
+
throw new TypeError(`oauthProvider: invalid scope token "${s}"`);
|
|
249
|
+
}
|
|
250
|
+
if (new Set(scopesSupported).size !== scopesSupported.length) {
|
|
251
|
+
throw new TypeError("oauthProvider: scopesSupported contains duplicates");
|
|
252
|
+
}
|
|
253
|
+
const resource = config.resource ?? config.resourceMetadata?.resource;
|
|
254
|
+
if (resource !== undefined)
|
|
255
|
+
validateResourceUri(resource);
|
|
256
|
+
const publicOrigin = config.publicOrigin === undefined ? undefined : parsePublicOrigin(config.publicOrigin);
|
|
257
|
+
const reg = config.clientRegistration ?? false;
|
|
258
|
+
const clientRegistration = reg === false ? { enabled: false, allowPublicClients: true, maxBodyBytes: 1024 * 1024 } : {
|
|
259
|
+
enabled: true,
|
|
260
|
+
allowPublicClients: (reg === true ? undefined : reg.allowPublicClients) ?? true,
|
|
261
|
+
maxBodyBytes: (reg === true ? undefined : reg.maxBodyBytes) ?? 1024 * 1024
|
|
262
|
+
};
|
|
263
|
+
const rateLimit = resolveRateLimit(config.rateLimit ?? true);
|
|
264
|
+
return {
|
|
265
|
+
issuer,
|
|
266
|
+
issuerUrl,
|
|
267
|
+
storage: config.storage,
|
|
268
|
+
handleAuthorize: config.handleAuthorize,
|
|
269
|
+
paths,
|
|
270
|
+
urls: {
|
|
271
|
+
authorize: abs(paths.authorize),
|
|
272
|
+
token: abs(paths.token),
|
|
273
|
+
register: abs(paths.register),
|
|
274
|
+
revoke: abs(paths.revoke),
|
|
275
|
+
jwks: abs(paths.jwks),
|
|
276
|
+
metadata: `${issuerUrl.origin}/.well-known/oauth-authorization-server${basePath}`,
|
|
277
|
+
protectedResource: `${issuerUrl.origin}/.well-known/oauth-protected-resource${basePath}`
|
|
278
|
+
},
|
|
279
|
+
resource,
|
|
280
|
+
publicOrigin,
|
|
281
|
+
resourceMetadata: config.resourceMetadata ?? {},
|
|
282
|
+
scopesSupported,
|
|
283
|
+
allowInsecureRedirectUris: config.allowInsecureRedirectUris ?? false,
|
|
284
|
+
accessTokenTTL: ttl("accessTokenTTL", config.accessTokenTTL, 3600),
|
|
285
|
+
refreshTokenTTL: ttl("refreshTokenTTL", config.refreshTokenTTL, 30 * DAY, 0),
|
|
286
|
+
refreshTokenReuseGraceSeconds: ttl("refreshTokenReuseGraceSeconds", config.refreshTokenReuseGraceSeconds, 30, 0),
|
|
287
|
+
authCodeTTL: ttl("authCodeTTL", config.authCodeTTL, 600),
|
|
288
|
+
authRequestTTL: ttl("authRequestTTL", config.authRequestTTL, 600),
|
|
289
|
+
clientRegistrationTTL: "clientRegistrationTTL" in config ? config.clientRegistrationTTL === undefined ? undefined : ttl("clientRegistrationTTL", config.clientRegistrationTTL, 90 * DAY) : 90 * DAY,
|
|
290
|
+
clientRegistration,
|
|
291
|
+
tokenFormat: config.tokenFormat ?? "opaque",
|
|
292
|
+
encryptProps: config.encryptProps ?? true,
|
|
293
|
+
cors: config.cors ?? true,
|
|
294
|
+
hooks: config.hooks ?? {},
|
|
295
|
+
rateLimit,
|
|
296
|
+
accessTokenClaims: config.accessTokenClaims
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function resolveRateLimit(input) {
|
|
300
|
+
if (!input)
|
|
301
|
+
return null;
|
|
302
|
+
const cfg = input === true ? {} : input;
|
|
303
|
+
const rule = (name) => {
|
|
304
|
+
const v = cfg[name];
|
|
305
|
+
if (v === false)
|
|
306
|
+
return null;
|
|
307
|
+
const r = v ?? DEFAULT_RATE_LIMITS[name];
|
|
308
|
+
if (!Number.isInteger(r.max) || r.max < 1 || !(r.windowSeconds > 0)) {
|
|
309
|
+
throw new TypeError(`oauthProvider: rateLimit.${name} needs integer max >= 1 and windowSeconds > 0`);
|
|
310
|
+
}
|
|
311
|
+
return r;
|
|
312
|
+
};
|
|
313
|
+
const trustProxy = cfg.trustProxy ?? false;
|
|
314
|
+
if (typeof trustProxy === "string" && trustProxy.trim() === "") {
|
|
315
|
+
throw new TypeError("oauthProvider: rateLimit.trustProxy header name must not be empty");
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
limiter: cfg.limiter ?? new MemoryRateLimiter,
|
|
319
|
+
rules: {
|
|
320
|
+
token: rule("token"),
|
|
321
|
+
register: rule("register"),
|
|
322
|
+
authorize: rule("authorize"),
|
|
323
|
+
revoke: rule("revoke")
|
|
324
|
+
},
|
|
325
|
+
keyFor: cfg.keyFor ?? null,
|
|
326
|
+
trustProxy
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
function parsePublicOrigin(input) {
|
|
330
|
+
let url;
|
|
331
|
+
try {
|
|
332
|
+
url = new URL(input);
|
|
333
|
+
} catch {
|
|
334
|
+
throw new TypeError("oauthProvider: `publicOrigin` must be an absolute URL");
|
|
335
|
+
}
|
|
336
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
337
|
+
throw new TypeError("oauthProvider: `publicOrigin` must be http(s)");
|
|
338
|
+
}
|
|
339
|
+
if (url.pathname !== "/" || url.search || url.hash) {
|
|
340
|
+
throw new TypeError("oauthProvider: `publicOrigin` must be an origin without path, query or fragment");
|
|
341
|
+
}
|
|
342
|
+
return url.origin;
|
|
343
|
+
}
|
|
344
|
+
function stripUndefined(o) {
|
|
345
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
346
|
+
}
|
|
347
|
+
function isValidScopeToken(s) {
|
|
348
|
+
return s.length > 0 && /^[\x21\x23-\x5B\x5D-\x7E]+$/.test(s);
|
|
349
|
+
}
|
|
350
|
+
function validateResourceUri(resource) {
|
|
351
|
+
let url;
|
|
352
|
+
try {
|
|
353
|
+
url = new URL(resource);
|
|
354
|
+
} catch {
|
|
355
|
+
throw new TypeError(`Invalid resource URI "${resource}": must be an absolute URI`);
|
|
356
|
+
}
|
|
357
|
+
if (url.hash)
|
|
358
|
+
throw new TypeError(`Invalid resource URI "${resource}": must not contain a fragment`);
|
|
359
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
360
|
+
throw new TypeError(`Invalid resource URI "${resource}": must be http(s)`);
|
|
361
|
+
}
|
|
362
|
+
return url;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// src/core/bearer.ts
|
|
366
|
+
function extractBearer(header) {
|
|
367
|
+
if (!header)
|
|
368
|
+
return null;
|
|
369
|
+
const m = /^Bearer\s+([A-Za-z0-9\-._~+/:]+=*)\s*$/i.exec(header);
|
|
370
|
+
return m ? m[1] : null;
|
|
371
|
+
}
|
|
372
|
+
function bearerChallenge(o) {
|
|
373
|
+
const parts = [`realm="OAuth"`, `resource_metadata="${o.resourceMetadataUrl}"`];
|
|
374
|
+
if (o.error)
|
|
375
|
+
parts.push(`error="${o.error}"`);
|
|
376
|
+
if (o.errorDescription) {
|
|
377
|
+
parts.push(`error_description="${o.errorDescription.replace(/"/g, "'")}"`);
|
|
378
|
+
}
|
|
379
|
+
if (o.scope && o.scope.length > 0)
|
|
380
|
+
parts.push(`scope="${o.scope.join(" ")}"`);
|
|
381
|
+
return `Bearer ${parts.join(", ")}`;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/crypto/hash.ts
|
|
385
|
+
var encoder = new TextEncoder;
|
|
386
|
+
async function sha256Hex(input) {
|
|
387
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(input));
|
|
388
|
+
return bytesToHex(new Uint8Array(digest));
|
|
389
|
+
}
|
|
390
|
+
async function sha256Base64Url(input) {
|
|
391
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(input));
|
|
392
|
+
return bytesToBase64Url(new Uint8Array(digest));
|
|
393
|
+
}
|
|
394
|
+
function bytesToHex(bytes) {
|
|
395
|
+
let out = "";
|
|
396
|
+
for (const b of bytes)
|
|
397
|
+
out += b.toString(16).padStart(2, "0");
|
|
398
|
+
return out;
|
|
399
|
+
}
|
|
400
|
+
function bytesToBase64Url(bytes) {
|
|
401
|
+
let bin = "";
|
|
402
|
+
for (const b of bytes)
|
|
403
|
+
bin += String.fromCharCode(b);
|
|
404
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
405
|
+
}
|
|
406
|
+
function base64UrlToBytes(str) {
|
|
407
|
+
const padded = str.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(str.length / 4) * 4, "=");
|
|
408
|
+
const bin = atob(padded);
|
|
409
|
+
const out = new Uint8Array(bin.length);
|
|
410
|
+
for (let i = 0;i < bin.length; i++)
|
|
411
|
+
out[i] = bin.charCodeAt(i);
|
|
412
|
+
return out;
|
|
413
|
+
}
|
|
414
|
+
function timingSafeEqual(a, b) {
|
|
415
|
+
const ab = encoder.encode(a);
|
|
416
|
+
const bb = encoder.encode(b);
|
|
417
|
+
let diff = ab.length ^ bb.length;
|
|
418
|
+
for (let i = 0;i < ab.length; i++)
|
|
419
|
+
diff |= ab[i] ^ (bb[i % (bb.length || 1)] ?? 0);
|
|
420
|
+
return diff === 0;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// src/crypto/jwt.ts
|
|
424
|
+
import {
|
|
425
|
+
SignJWT,
|
|
426
|
+
exportJWK,
|
|
427
|
+
importJWK,
|
|
428
|
+
importPKCS8,
|
|
429
|
+
importSPKI,
|
|
430
|
+
decodeProtectedHeader,
|
|
431
|
+
jwtVerify
|
|
432
|
+
} from "jose";
|
|
433
|
+
var ACCESS_TOKEN_REGISTERED_CLAIMS = [
|
|
434
|
+
"iss",
|
|
435
|
+
"sub",
|
|
436
|
+
"aud",
|
|
437
|
+
"exp",
|
|
438
|
+
"iat",
|
|
439
|
+
"jti",
|
|
440
|
+
"client_id",
|
|
441
|
+
"scope",
|
|
442
|
+
"grant_id"
|
|
443
|
+
];
|
|
444
|
+
var encoder2 = new TextEncoder;
|
|
445
|
+
async function importPrivate(alg, input) {
|
|
446
|
+
if (typeof input === "string")
|
|
447
|
+
return importPKCS8(input, alg);
|
|
448
|
+
if (input instanceof Uint8Array)
|
|
449
|
+
return input;
|
|
450
|
+
if (isJwk(input))
|
|
451
|
+
return importJWK(input, alg);
|
|
452
|
+
return input;
|
|
453
|
+
}
|
|
454
|
+
async function importPublic(alg, input) {
|
|
455
|
+
if (typeof input === "string")
|
|
456
|
+
return importSPKI(input, alg);
|
|
457
|
+
if (input instanceof Uint8Array)
|
|
458
|
+
return input;
|
|
459
|
+
if (isJwk(input))
|
|
460
|
+
return importJWK(input, alg);
|
|
461
|
+
return input;
|
|
462
|
+
}
|
|
463
|
+
function isJwk(v) {
|
|
464
|
+
return typeof v === "object" && v !== null && "kty" in v;
|
|
465
|
+
}
|
|
466
|
+
async function createJwtSigner(format) {
|
|
467
|
+
if (format.alg === "HS256") {
|
|
468
|
+
const secret = typeof format.secret === "string" ? encoder2.encode(format.secret) : format.secret;
|
|
469
|
+
if (secret.byteLength < 32) {
|
|
470
|
+
throw new TypeError("tokenFormat.secret must be at least 32 bytes for HS256");
|
|
471
|
+
}
|
|
472
|
+
return makeSigner("HS256", format.kid, secret, secret, null);
|
|
473
|
+
}
|
|
474
|
+
const privateKey = await importPrivate(format.alg, format.privateKey);
|
|
475
|
+
let publicKey;
|
|
476
|
+
if (format.publicKey)
|
|
477
|
+
publicKey = await importPublic(format.alg, format.publicKey);
|
|
478
|
+
else if (isJwk(format.privateKey)) {
|
|
479
|
+
const pub = { ...format.privateKey };
|
|
480
|
+
delete pub.d;
|
|
481
|
+
delete pub.p;
|
|
482
|
+
delete pub.q;
|
|
483
|
+
delete pub.dp;
|
|
484
|
+
delete pub.dq;
|
|
485
|
+
delete pub.qi;
|
|
486
|
+
publicKey = await importJWK(pub, format.alg);
|
|
487
|
+
} else if (typeof privateKey === "object" && "algorithm" in privateKey) {
|
|
488
|
+
const jwk = await exportJWK(privateKey);
|
|
489
|
+
delete jwk.d;
|
|
490
|
+
delete jwk.p;
|
|
491
|
+
delete jwk.q;
|
|
492
|
+
delete jwk.dp;
|
|
493
|
+
delete jwk.dq;
|
|
494
|
+
delete jwk.qi;
|
|
495
|
+
publicKey = await importJWK(jwk, format.alg);
|
|
496
|
+
} else {
|
|
497
|
+
throw new TypeError("tokenFormat.publicKey is required when privateKey is a PEM string");
|
|
498
|
+
}
|
|
499
|
+
const toJwk = async (key, kid) => {
|
|
500
|
+
const jwk = await exportJWK(key);
|
|
501
|
+
jwk.alg = format.alg;
|
|
502
|
+
jwk.use = "sig";
|
|
503
|
+
if (kid)
|
|
504
|
+
jwk.kid = kid;
|
|
505
|
+
return jwk;
|
|
506
|
+
};
|
|
507
|
+
const keys = [await toJwk(publicKey, format.kid)];
|
|
508
|
+
const additional = format.additionalPublicKeys ?? [];
|
|
509
|
+
if (additional.length === 0) {
|
|
510
|
+
return makeSigner(format.alg, format.kid, privateKey, publicKey, { keys });
|
|
511
|
+
}
|
|
512
|
+
if (!format.kid) {
|
|
513
|
+
throw new TypeError("tokenFormat.kid is required when additionalPublicKeys is used");
|
|
514
|
+
}
|
|
515
|
+
const byKid = new Map([[format.kid, publicKey]]);
|
|
516
|
+
for (const extra of additional) {
|
|
517
|
+
if (!extra.kid)
|
|
518
|
+
throw new TypeError("tokenFormat.additionalPublicKeys[].kid is required");
|
|
519
|
+
if (byKid.has(extra.kid)) {
|
|
520
|
+
throw new TypeError(`tokenFormat: duplicate kid "${extra.kid}"`);
|
|
521
|
+
}
|
|
522
|
+
const key = await importPublic(format.alg, extra.publicKey);
|
|
523
|
+
byKid.set(extra.kid, key);
|
|
524
|
+
keys.push(await toJwk(key, extra.kid));
|
|
525
|
+
}
|
|
526
|
+
return makeSigner(format.alg, format.kid, privateKey, byKid, { keys });
|
|
527
|
+
}
|
|
528
|
+
function makeSigner(alg, kid, privateKey, publicKey, jwks) {
|
|
529
|
+
return {
|
|
530
|
+
alg,
|
|
531
|
+
kid,
|
|
532
|
+
async sign(payload, { expiresAt, issuedAt, jti }) {
|
|
533
|
+
const header = { alg, typ: "at+jwt" };
|
|
534
|
+
if (kid)
|
|
535
|
+
header.kid = kid;
|
|
536
|
+
return new SignJWT(payload).setProtectedHeader(header).setIssuedAt(issuedAt).setExpirationTime(expiresAt).setJti(jti).sign(privateKey);
|
|
537
|
+
},
|
|
538
|
+
async verify(token, { issuer }) {
|
|
539
|
+
try {
|
|
540
|
+
let key;
|
|
541
|
+
if (publicKey instanceof Map) {
|
|
542
|
+
const tokenKid = decodeProtectedHeader(token).kid;
|
|
543
|
+
key = tokenKid === undefined ? undefined : publicKey.get(tokenKid);
|
|
544
|
+
if (!key)
|
|
545
|
+
return null;
|
|
546
|
+
} else
|
|
547
|
+
key = publicKey;
|
|
548
|
+
const { payload } = await jwtVerify(token, key, {
|
|
549
|
+
issuer,
|
|
550
|
+
algorithms: [alg],
|
|
551
|
+
typ: "at+jwt"
|
|
552
|
+
});
|
|
553
|
+
return payload;
|
|
554
|
+
} catch {
|
|
555
|
+
return null;
|
|
556
|
+
}
|
|
557
|
+
},
|
|
558
|
+
async jwks() {
|
|
559
|
+
return jwks;
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// src/crypto/props-encryption.ts
|
|
565
|
+
var encoder3 = new TextEncoder;
|
|
566
|
+
var decoder = new TextDecoder;
|
|
567
|
+
var ZERO_IV = new Uint8Array(12);
|
|
568
|
+
var WRAPPING_KEY_HMAC_KEY = encoder3.encode("elysia-oauth-provider:props-wrapping-key:v1");
|
|
569
|
+
async function encryptProps(props) {
|
|
570
|
+
const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, [
|
|
571
|
+
"encrypt",
|
|
572
|
+
"decrypt"
|
|
573
|
+
]);
|
|
574
|
+
const data = encoder3.encode(JSON.stringify(props ?? null));
|
|
575
|
+
const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv: ZERO_IV }, key, data);
|
|
576
|
+
return { ciphertext: bytesToBase64Url(new Uint8Array(ct)), key };
|
|
577
|
+
}
|
|
578
|
+
async function decryptProps(ciphertext, key) {
|
|
579
|
+
const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: ZERO_IV }, key, base64UrlToBytes(ciphertext));
|
|
580
|
+
return JSON.parse(decoder.decode(pt));
|
|
581
|
+
}
|
|
582
|
+
async function deriveWrappingKey(credential) {
|
|
583
|
+
const hmacKey = await crypto.subtle.importKey("raw", WRAPPING_KEY_HMAC_KEY, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
584
|
+
const raw = await crypto.subtle.sign("HMAC", hmacKey, encoder3.encode(credential));
|
|
585
|
+
return crypto.subtle.importKey("raw", raw, { name: "AES-KW" }, false, ["wrapKey", "unwrapKey"]);
|
|
586
|
+
}
|
|
587
|
+
async function wrapKeyWithCredential(key, credential) {
|
|
588
|
+
const wrappingKey = await deriveWrappingKey(credential);
|
|
589
|
+
const wrapped = await crypto.subtle.wrapKey("raw", key, wrappingKey, { name: "AES-KW" });
|
|
590
|
+
return bytesToBase64Url(new Uint8Array(wrapped));
|
|
591
|
+
}
|
|
592
|
+
async function unwrapKeyWithCredential(wrapped, credential) {
|
|
593
|
+
const wrappingKey = await deriveWrappingKey(credential);
|
|
594
|
+
return crypto.subtle.unwrapKey("raw", base64UrlToBytes(wrapped), wrappingKey, { name: "AES-KW" }, { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]);
|
|
595
|
+
}
|
|
596
|
+
var SEAL_KEY_HMAC_KEY = encoder3.encode("elysia-oauth-provider:credential-seal-key:v1");
|
|
597
|
+
async function deriveSealKey(credential) {
|
|
598
|
+
const hmacKey = await crypto.subtle.importKey("raw", SEAL_KEY_HMAC_KEY, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
599
|
+
const raw = await crypto.subtle.sign("HMAC", hmacKey, encoder3.encode(credential));
|
|
600
|
+
return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
601
|
+
}
|
|
602
|
+
async function sealWithCredential(credential, plaintext) {
|
|
603
|
+
const key = await deriveSealKey(credential);
|
|
604
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
605
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, encoder3.encode(plaintext)));
|
|
606
|
+
const out = new Uint8Array(iv.length + ct.length);
|
|
607
|
+
out.set(iv);
|
|
608
|
+
out.set(ct, iv.length);
|
|
609
|
+
return bytesToBase64Url(out);
|
|
610
|
+
}
|
|
611
|
+
async function openWithCredential(credential, sealed) {
|
|
612
|
+
const key = await deriveSealKey(credential);
|
|
613
|
+
const bytes = base64UrlToBytes(sealed);
|
|
614
|
+
const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, key, bytes.slice(12));
|
|
615
|
+
return decoder.decode(pt);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// src/crypto/random.ts
|
|
619
|
+
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
620
|
+
function randomString(length) {
|
|
621
|
+
const bytes = new Uint8Array(length);
|
|
622
|
+
crypto.getRandomValues(bytes);
|
|
623
|
+
let out = "";
|
|
624
|
+
for (let i = 0;i < length; i++)
|
|
625
|
+
out += ALPHABET.charAt(bytes[i] % 64);
|
|
626
|
+
return out;
|
|
627
|
+
}
|
|
628
|
+
var randomId = () => randomString(16);
|
|
629
|
+
var randomSecret = () => randomString(32);
|
|
630
|
+
|
|
631
|
+
// src/errors.ts
|
|
632
|
+
class OAuthError extends Error {
|
|
633
|
+
code;
|
|
634
|
+
status;
|
|
635
|
+
headers;
|
|
636
|
+
constructor(code, description, options = {}) {
|
|
637
|
+
super(description, options.cause === undefined ? undefined : { cause: options.cause });
|
|
638
|
+
this.name = "OAuthError";
|
|
639
|
+
this.code = code;
|
|
640
|
+
this.status = options.status ?? defaultStatus(code);
|
|
641
|
+
this.headers = options.headers ?? {};
|
|
642
|
+
}
|
|
643
|
+
toJSON() {
|
|
644
|
+
return { error: this.code, error_description: this.message };
|
|
645
|
+
}
|
|
646
|
+
toResponse(extraHeaders = {}) {
|
|
647
|
+
return Response.json(this.toJSON(), {
|
|
648
|
+
status: this.status,
|
|
649
|
+
headers: {
|
|
650
|
+
"Cache-Control": "no-store",
|
|
651
|
+
Pragma: "no-cache",
|
|
652
|
+
...extraHeaders,
|
|
653
|
+
...this.headers
|
|
654
|
+
}
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
function defaultStatus(code) {
|
|
659
|
+
switch (code) {
|
|
660
|
+
case "invalid_client":
|
|
661
|
+
case "invalid_token":
|
|
662
|
+
return 401;
|
|
663
|
+
case "insufficient_scope":
|
|
664
|
+
return 403;
|
|
665
|
+
case "server_error":
|
|
666
|
+
return 500;
|
|
667
|
+
case "temporarily_unavailable":
|
|
668
|
+
return 503;
|
|
669
|
+
default:
|
|
670
|
+
return 400;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
class AuthorizationError extends Error {
|
|
675
|
+
code;
|
|
676
|
+
redirectUri;
|
|
677
|
+
state;
|
|
678
|
+
issuer;
|
|
679
|
+
constructor(code, description, options = {}) {
|
|
680
|
+
super(description);
|
|
681
|
+
this.name = "AuthorizationError";
|
|
682
|
+
this.code = code;
|
|
683
|
+
this.redirectUri = options.redirectUri;
|
|
684
|
+
this.state = options.state;
|
|
685
|
+
this.issuer = options.issuer;
|
|
686
|
+
}
|
|
687
|
+
toRedirectUrl() {
|
|
688
|
+
if (!this.redirectUri)
|
|
689
|
+
return null;
|
|
690
|
+
const url = new URL(this.redirectUri);
|
|
691
|
+
url.searchParams.set("error", this.code);
|
|
692
|
+
url.searchParams.set("error_description", this.message);
|
|
693
|
+
if (this.state !== undefined)
|
|
694
|
+
url.searchParams.set("state", this.state);
|
|
695
|
+
if (this.issuer)
|
|
696
|
+
url.searchParams.set("iss", this.issuer);
|
|
697
|
+
return url.toString();
|
|
698
|
+
}
|
|
699
|
+
toResponse() {
|
|
700
|
+
const redirectTo = this.toRedirectUrl();
|
|
701
|
+
if (redirectTo) {
|
|
702
|
+
return new Response(null, {
|
|
703
|
+
status: 302,
|
|
704
|
+
headers: { Location: redirectTo, "Cache-Control": "no-store" }
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
return Response.json({ error: this.code, error_description: this.message }, { status: 400, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// src/storage/keys.ts
|
|
712
|
+
var KEY_PREFIX = {
|
|
713
|
+
client: "client:",
|
|
714
|
+
authRequest: "authreq:",
|
|
715
|
+
grant: "grant:",
|
|
716
|
+
token: "token:",
|
|
717
|
+
refresh: "refresh:",
|
|
718
|
+
authCode: "authcode:"
|
|
719
|
+
};
|
|
720
|
+
var keys = {
|
|
721
|
+
client: (clientId) => `${KEY_PREFIX.client}${clientId}`,
|
|
722
|
+
authRequest: (id) => `${KEY_PREFIX.authRequest}${id}`,
|
|
723
|
+
grant: (userId, grantId) => `${KEY_PREFIX.grant}${userId}:${grantId}`,
|
|
724
|
+
grantPrefixForUser: (userId) => `${KEY_PREFIX.grant}${userId}:`,
|
|
725
|
+
token: (userId, grantId, tokenHash) => `${KEY_PREFIX.token}${userId}:${grantId}:${tokenHash}`,
|
|
726
|
+
tokenPrefixForGrant: (userId, grantId) => `${KEY_PREFIX.token}${userId}:${grantId}:`,
|
|
727
|
+
refresh: (refreshHash) => `${KEY_PREFIX.refresh}${refreshHash}`,
|
|
728
|
+
authCode: (codeHash) => `${KEY_PREFIX.authCode}${codeHash}`
|
|
729
|
+
};
|
|
730
|
+
|
|
731
|
+
// src/core/pkce.ts
|
|
732
|
+
function isValidCodeVerifier(v) {
|
|
733
|
+
return /^[A-Za-z0-9\-._~]{43,128}$/.test(v);
|
|
734
|
+
}
|
|
735
|
+
function isValidCodeChallenge(c) {
|
|
736
|
+
return /^[A-Za-z0-9\-_]{43}$/.test(c);
|
|
737
|
+
}
|
|
738
|
+
async function verifyPkce(verifier, challenge) {
|
|
739
|
+
if (!isValidCodeVerifier(verifier))
|
|
740
|
+
return false;
|
|
741
|
+
return timingSafeEqual(await sha256Base64Url(verifier), challenge);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// src/core/redirect-uri.ts
|
|
745
|
+
var DANGEROUS_SCHEMES = new Set([
|
|
746
|
+
"javascript:",
|
|
747
|
+
"data:",
|
|
748
|
+
"vbscript:",
|
|
749
|
+
"file:",
|
|
750
|
+
"blob:",
|
|
751
|
+
"mailto:"
|
|
752
|
+
]);
|
|
753
|
+
function validateRedirectUriSyntax(uri, policy = { allowInsecure: false }) {
|
|
754
|
+
if (typeof uri !== "string" || uri.length === 0)
|
|
755
|
+
return "redirect_uri must be a non-empty string";
|
|
756
|
+
if (/[\x00-\x1f\x7f\s]/.test(uri))
|
|
757
|
+
return "redirect_uri must not contain whitespace or control characters";
|
|
758
|
+
if (uri.includes("#"))
|
|
759
|
+
return "redirect_uri must not contain a fragment";
|
|
760
|
+
let url;
|
|
761
|
+
try {
|
|
762
|
+
url = new URL(uri);
|
|
763
|
+
} catch {
|
|
764
|
+
return "redirect_uri must be an absolute URI";
|
|
765
|
+
}
|
|
766
|
+
if (DANGEROUS_SCHEMES.has(url.protocol))
|
|
767
|
+
return `redirect_uri scheme "${url.protocol}" is not allowed`;
|
|
768
|
+
if (policy.allowInsecure)
|
|
769
|
+
return null;
|
|
770
|
+
if (url.protocol === "https:")
|
|
771
|
+
return null;
|
|
772
|
+
if (url.protocol === "http:") {
|
|
773
|
+
return isLoopbackHost(url.hostname) ? null : 'redirect_uri with scheme "http:" must use a loopback host (localhost, 127.0.0.1, [::1])';
|
|
774
|
+
}
|
|
775
|
+
if (url.protocol.includes("."))
|
|
776
|
+
return null;
|
|
777
|
+
return `redirect_uri scheme "${url.protocol}" is not allowed: use https:, a loopback http: URI, or a reverse-DNS private-use scheme`;
|
|
778
|
+
}
|
|
779
|
+
function isLoopbackIPv4(host) {
|
|
780
|
+
const m = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
781
|
+
return m ? m.slice(1).every((octet) => Number(octet) <= 255) : false;
|
|
782
|
+
}
|
|
783
|
+
function isLoopbackHost(host) {
|
|
784
|
+
return host === "localhost" || host === "[::1]" || isLoopbackIPv4(host);
|
|
785
|
+
}
|
|
786
|
+
function redirectUriMatches(registered, requested) {
|
|
787
|
+
if (registered === requested)
|
|
788
|
+
return true;
|
|
789
|
+
let a;
|
|
790
|
+
let b;
|
|
791
|
+
try {
|
|
792
|
+
a = new URL(registered);
|
|
793
|
+
b = new URL(requested);
|
|
794
|
+
} catch {
|
|
795
|
+
return false;
|
|
796
|
+
}
|
|
797
|
+
if (a.protocol !== "http:" || b.protocol !== "http:")
|
|
798
|
+
return false;
|
|
799
|
+
if (!isLoopbackHost(a.hostname) || !isLoopbackHost(b.hostname))
|
|
800
|
+
return false;
|
|
801
|
+
return a.hostname === b.hostname && a.pathname === b.pathname && a.search === b.search && a.username === b.username && a.password === b.password;
|
|
802
|
+
}
|
|
803
|
+
function isRegisteredRedirectUri(redirectUris, requested) {
|
|
804
|
+
return redirectUris.some((r) => redirectUriMatches(r, requested));
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// src/core/resource.ts
|
|
808
|
+
function normalizeResource(resource) {
|
|
809
|
+
const url = new URL(resource);
|
|
810
|
+
url.hash = "";
|
|
811
|
+
return url.toString();
|
|
812
|
+
}
|
|
813
|
+
function resourcesEqual(a, b) {
|
|
814
|
+
try {
|
|
815
|
+
return normalizeResource(a) === normalizeResource(b);
|
|
816
|
+
} catch {
|
|
817
|
+
return false;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
function audienceCoversUrl(audience, requestUrl) {
|
|
821
|
+
let a;
|
|
822
|
+
let r;
|
|
823
|
+
try {
|
|
824
|
+
a = new URL(audience);
|
|
825
|
+
r = new URL(requestUrl);
|
|
826
|
+
} catch {
|
|
827
|
+
return false;
|
|
828
|
+
}
|
|
829
|
+
if (a.origin !== r.origin)
|
|
830
|
+
return false;
|
|
831
|
+
if (a.search && a.search !== r.search)
|
|
832
|
+
return false;
|
|
833
|
+
const ap = a.pathname.replace(/\/+$/, "");
|
|
834
|
+
const rp = r.pathname.replace(/\/+$/, "");
|
|
835
|
+
return ap === "" || rp === ap || rp.startsWith(ap + "/");
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// src/core/scope.ts
|
|
839
|
+
function parseScope(scope) {
|
|
840
|
+
if (!scope)
|
|
841
|
+
return [];
|
|
842
|
+
const out = [];
|
|
843
|
+
for (const s of scope.split(" ")) {
|
|
844
|
+
if (s === "")
|
|
845
|
+
continue;
|
|
846
|
+
if (!isValidScopeToken(s))
|
|
847
|
+
return null;
|
|
848
|
+
if (!out.includes(s))
|
|
849
|
+
out.push(s);
|
|
850
|
+
}
|
|
851
|
+
return out;
|
|
852
|
+
}
|
|
853
|
+
var formatScope = (scopes) => scopes.join(" ");
|
|
854
|
+
function isSubset(subset, superset) {
|
|
855
|
+
return subset.every((s) => superset.includes(s));
|
|
856
|
+
}
|
|
857
|
+
function downscope(requested, granted) {
|
|
858
|
+
if (!requested || requested.length === 0)
|
|
859
|
+
return [...granted];
|
|
860
|
+
if (!isSubset(requested, granted))
|
|
861
|
+
return null;
|
|
862
|
+
return [...requested];
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// src/core/provider.ts
|
|
866
|
+
var OPAQUE_USER_ID = /^[A-Za-z0-9\-._~+/]+$/;
|
|
867
|
+
var nowSeconds = () => Math.floor(Date.now() / 1000);
|
|
868
|
+
var MAX_COMMIT_ATTEMPTS = 8;
|
|
869
|
+
var AUTH_METHODS = [
|
|
870
|
+
"client_secret_basic",
|
|
871
|
+
"client_secret_post",
|
|
872
|
+
"none"
|
|
873
|
+
];
|
|
874
|
+
|
|
875
|
+
class OAuthProviderCore {
|
|
876
|
+
config;
|
|
877
|
+
#signer = null;
|
|
878
|
+
constructor(config) {
|
|
879
|
+
this.config = config;
|
|
880
|
+
if (config.tokenFormat !== "opaque")
|
|
881
|
+
this.#signer = createJwtSigner(config.tokenFormat);
|
|
882
|
+
}
|
|
883
|
+
get storage() {
|
|
884
|
+
return this.config.storage;
|
|
885
|
+
}
|
|
886
|
+
get jwtSigner() {
|
|
887
|
+
return this.#signer;
|
|
888
|
+
}
|
|
889
|
+
async createClient(input) {
|
|
890
|
+
const method = input.tokenEndpointAuthMethod ?? "client_secret_basic";
|
|
891
|
+
const grantTypes = input.grantTypes ?? ["authorization_code", "refresh_token"];
|
|
892
|
+
const responseTypes = input.responseTypes ?? ["code"];
|
|
893
|
+
this.#validateClientFields({
|
|
894
|
+
redirectUris: input.redirectUris ?? [],
|
|
895
|
+
grantTypes,
|
|
896
|
+
responseTypes,
|
|
897
|
+
scope: input.scope,
|
|
898
|
+
tokenEndpointAuthMethod: method,
|
|
899
|
+
dynamicallyRegistered: input.dynamicallyRegistered ?? false
|
|
900
|
+
});
|
|
901
|
+
const clientId = input.clientId ?? randomId();
|
|
902
|
+
if (await this.storage.get(keys.client(clientId))) {
|
|
903
|
+
throw new OAuthError("invalid_client_metadata", "client_id already exists");
|
|
904
|
+
}
|
|
905
|
+
const secret = method === "none" ? undefined : randomSecret();
|
|
906
|
+
const stored = {
|
|
907
|
+
clientId,
|
|
908
|
+
clientSecretHash: secret ? await sha256Hex(secret) : undefined,
|
|
909
|
+
redirectUris: [...input.redirectUris],
|
|
910
|
+
clientName: input.clientName,
|
|
911
|
+
clientUri: input.clientUri,
|
|
912
|
+
logoUri: input.logoUri,
|
|
913
|
+
policyUri: input.policyUri,
|
|
914
|
+
tosUri: input.tosUri,
|
|
915
|
+
jwksUri: input.jwksUri,
|
|
916
|
+
contacts: input.contacts,
|
|
917
|
+
grantTypes,
|
|
918
|
+
responseTypes,
|
|
919
|
+
scope: input.scope,
|
|
920
|
+
tokenEndpointAuthMethod: method,
|
|
921
|
+
registrationDate: nowSeconds(),
|
|
922
|
+
dynamicallyRegistered: input.dynamicallyRegistered ?? false,
|
|
923
|
+
metadata: input.metadata
|
|
924
|
+
};
|
|
925
|
+
await this.storage.set(keys.client(clientId), stripUndefined2(stored), {
|
|
926
|
+
ttlSeconds: stored.dynamicallyRegistered ? this.config.clientRegistrationTTL : undefined
|
|
927
|
+
});
|
|
928
|
+
const info = toPublicClient(stored);
|
|
929
|
+
if (secret)
|
|
930
|
+
info.clientSecret = secret;
|
|
931
|
+
return info;
|
|
932
|
+
}
|
|
933
|
+
async getStoredClient(clientId) {
|
|
934
|
+
if (!clientId)
|
|
935
|
+
return null;
|
|
936
|
+
return this.storage.get(keys.client(clientId));
|
|
937
|
+
}
|
|
938
|
+
async lookupClient(clientId) {
|
|
939
|
+
const stored = await this.getStoredClient(clientId);
|
|
940
|
+
return stored ? toPublicClient(stored) : null;
|
|
941
|
+
}
|
|
942
|
+
async updateClient(clientId, updates) {
|
|
943
|
+
const stored = await this.getStoredClient(clientId);
|
|
944
|
+
if (!stored)
|
|
945
|
+
return null;
|
|
946
|
+
const { dynamicallyRegistered: _ignored, ...rest } = updates;
|
|
947
|
+
const next = { ...stored, ...stripUndefined2(rest) };
|
|
948
|
+
this.#validateClientFields({
|
|
949
|
+
redirectUris: rest.redirectUris,
|
|
950
|
+
grantTypes: next.grantTypes,
|
|
951
|
+
responseTypes: next.responseTypes,
|
|
952
|
+
scope: rest.scope,
|
|
953
|
+
tokenEndpointAuthMethod: rest.tokenEndpointAuthMethod,
|
|
954
|
+
dynamicallyRegistered: stored.dynamicallyRegistered
|
|
955
|
+
});
|
|
956
|
+
let secret;
|
|
957
|
+
if (next.tokenEndpointAuthMethod === "none")
|
|
958
|
+
delete next.clientSecretHash;
|
|
959
|
+
else if (!next.clientSecretHash) {
|
|
960
|
+
secret = randomSecret();
|
|
961
|
+
next.clientSecretHash = await sha256Hex(secret);
|
|
962
|
+
}
|
|
963
|
+
await this.storage.set(keys.client(clientId), stripUndefined2(next), {
|
|
964
|
+
ttlSeconds: next.dynamicallyRegistered ? this.config.clientRegistrationTTL : undefined
|
|
965
|
+
});
|
|
966
|
+
const info = toPublicClient(next);
|
|
967
|
+
if (secret)
|
|
968
|
+
info.clientSecret = secret;
|
|
969
|
+
return info;
|
|
970
|
+
}
|
|
971
|
+
#validateClientFields(f) {
|
|
972
|
+
if (f.redirectUris !== undefined) {
|
|
973
|
+
if (!Array.isArray(f.redirectUris) || f.redirectUris.length === 0) {
|
|
974
|
+
throw new OAuthError("invalid_redirect_uri", "At least one redirect_uri is required");
|
|
975
|
+
}
|
|
976
|
+
for (const uri of f.redirectUris) {
|
|
977
|
+
const err = validateRedirectUriSyntax(uri, {
|
|
978
|
+
allowInsecure: this.config.allowInsecureRedirectUris
|
|
979
|
+
});
|
|
980
|
+
if (err)
|
|
981
|
+
throw new OAuthError("invalid_redirect_uri", err);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
const method = f.tokenEndpointAuthMethod;
|
|
985
|
+
if (method !== undefined) {
|
|
986
|
+
if (!AUTH_METHODS.includes(method)) {
|
|
987
|
+
throw new OAuthError("invalid_client_metadata", `Unsupported token_endpoint_auth_method "${method}"`);
|
|
988
|
+
}
|
|
989
|
+
if (method === "none" && f.dynamicallyRegistered && !this.config.clientRegistration.allowPublicClients) {
|
|
990
|
+
throw new OAuthError("invalid_client_metadata", "Public clients are not allowed to register");
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
for (const g of f.grantTypes) {
|
|
994
|
+
if (g !== "authorization_code" && g !== "refresh_token") {
|
|
995
|
+
throw new OAuthError("invalid_client_metadata", `Unsupported grant_type "${g}"`);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
for (const r of f.responseTypes) {
|
|
999
|
+
if (r !== "code") {
|
|
1000
|
+
throw new OAuthError("invalid_client_metadata", `Unsupported response_type "${r}"`);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
if (f.grantTypes.includes("authorization_code") && !f.responseTypes.includes("code")) {
|
|
1004
|
+
throw new OAuthError("invalid_client_metadata", "grant_type authorization_code requires response_type code");
|
|
1005
|
+
}
|
|
1006
|
+
if (f.scope !== undefined) {
|
|
1007
|
+
const scopes = parseScope(f.scope);
|
|
1008
|
+
if (!scopes)
|
|
1009
|
+
throw new OAuthError("invalid_client_metadata", "Invalid scope");
|
|
1010
|
+
if (!isSubset(scopes, this.config.scopesSupported)) {
|
|
1011
|
+
throw new OAuthError("invalid_client_metadata", "Requested scope is not supported");
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
async deleteClient(clientId) {
|
|
1016
|
+
for (const grant of await this.listClientGrants(clientId)) {
|
|
1017
|
+
await this.revokeGrant(grant.id, grant.userId);
|
|
1018
|
+
}
|
|
1019
|
+
await this.storage.delete(keys.client(clientId));
|
|
1020
|
+
}
|
|
1021
|
+
async listClients() {
|
|
1022
|
+
const out = [];
|
|
1023
|
+
for (const key of await this.storage.list(KEY_PREFIX.client)) {
|
|
1024
|
+
const c = await this.storage.get(key);
|
|
1025
|
+
if (c)
|
|
1026
|
+
out.push(toPublicClient(c));
|
|
1027
|
+
}
|
|
1028
|
+
return out;
|
|
1029
|
+
}
|
|
1030
|
+
async authenticateClient(creds) {
|
|
1031
|
+
const stored = await this.getStoredClient(creds.clientId);
|
|
1032
|
+
if (!stored) {
|
|
1033
|
+
if (creds.method === "none" || creds.clientSecret === undefined) {
|
|
1034
|
+
throw invalidClient("Client authentication required", "client_secret_basic");
|
|
1035
|
+
}
|
|
1036
|
+
throw invalidClient("Invalid client credentials", creds.method);
|
|
1037
|
+
}
|
|
1038
|
+
const registered = stored.tokenEndpointAuthMethod;
|
|
1039
|
+
if (registered === "none") {
|
|
1040
|
+
if (creds.method !== "none" || creds.clientSecret !== undefined) {
|
|
1041
|
+
throw invalidClient("Client is registered as a public client and must not send a secret", creds.method);
|
|
1042
|
+
}
|
|
1043
|
+
return stored;
|
|
1044
|
+
}
|
|
1045
|
+
if (creds.method === "none" || creds.clientSecret === undefined) {
|
|
1046
|
+
throw invalidClient("Client authentication required", "client_secret_basic");
|
|
1047
|
+
}
|
|
1048
|
+
if (!stored.clientSecretHash)
|
|
1049
|
+
throw invalidClient("Client has no secret", creds.method);
|
|
1050
|
+
const presented = await sha256Hex(creds.clientSecret);
|
|
1051
|
+
if (!timingSafeEqual(presented, stored.clientSecretHash)) {
|
|
1052
|
+
throw invalidClient("Invalid client credentials", creds.method);
|
|
1053
|
+
}
|
|
1054
|
+
return stored;
|
|
1055
|
+
}
|
|
1056
|
+
async parseAuthRequest(url) {
|
|
1057
|
+
const u = typeof url === "string" ? new URL(url) : url;
|
|
1058
|
+
const q = u.searchParams;
|
|
1059
|
+
const single = (name) => {
|
|
1060
|
+
const all = q.getAll(name);
|
|
1061
|
+
if (all.length > 1) {
|
|
1062
|
+
throw new AuthorizationError("invalid_request", `Parameter "${name}" must not be repeated`);
|
|
1063
|
+
}
|
|
1064
|
+
return all[0];
|
|
1065
|
+
};
|
|
1066
|
+
const clientId = single("client_id");
|
|
1067
|
+
if (!clientId)
|
|
1068
|
+
throw new AuthorizationError("invalid_request", "Missing client_id");
|
|
1069
|
+
const stored = await this.getStoredClient(clientId);
|
|
1070
|
+
if (!stored)
|
|
1071
|
+
throw new AuthorizationError("invalid_request", "Unknown client_id");
|
|
1072
|
+
const redirectUri = single("redirect_uri");
|
|
1073
|
+
if (!redirectUri)
|
|
1074
|
+
throw new AuthorizationError("invalid_request", "Missing redirect_uri");
|
|
1075
|
+
const syntaxErr = validateRedirectUriSyntax(redirectUri, {
|
|
1076
|
+
allowInsecure: this.config.allowInsecureRedirectUris
|
|
1077
|
+
});
|
|
1078
|
+
if (syntaxErr)
|
|
1079
|
+
throw new AuthorizationError("invalid_request", syntaxErr);
|
|
1080
|
+
if (!isRegisteredRedirectUri(stored.redirectUris, redirectUri)) {
|
|
1081
|
+
throw new AuthorizationError("invalid_request", "redirect_uri does not match a registered redirect URI");
|
|
1082
|
+
}
|
|
1083
|
+
const state = single("state");
|
|
1084
|
+
const redir = { redirectUri, state, issuer: this.config.issuer };
|
|
1085
|
+
const fail = (code, msg) => new AuthorizationError(code, msg, redir);
|
|
1086
|
+
const responseType = single("response_type");
|
|
1087
|
+
if (!responseType)
|
|
1088
|
+
throw fail("invalid_request", "Missing response_type");
|
|
1089
|
+
if (responseType !== "code") {
|
|
1090
|
+
throw fail("unsupported_response_type", "Only response_type=code is supported");
|
|
1091
|
+
}
|
|
1092
|
+
if (!stored.responseTypes.includes("code")) {
|
|
1093
|
+
throw fail("unauthorized_client", "Client may not use response_type=code");
|
|
1094
|
+
}
|
|
1095
|
+
const scopes = parseScope(single("scope"));
|
|
1096
|
+
if (!scopes)
|
|
1097
|
+
throw fail("invalid_scope", "Malformed scope");
|
|
1098
|
+
if (!isSubset(scopes, this.config.scopesSupported)) {
|
|
1099
|
+
throw fail("invalid_scope", "Requested scope is not supported");
|
|
1100
|
+
}
|
|
1101
|
+
if (stored.scope !== undefined) {
|
|
1102
|
+
const allowed = parseScope(stored.scope) ?? [];
|
|
1103
|
+
if (!isSubset(scopes, allowed)) {
|
|
1104
|
+
throw fail("invalid_scope", "Requested scope exceeds the client registration");
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
const codeChallenge = single("code_challenge");
|
|
1108
|
+
const codeChallengeMethod = single("code_challenge_method");
|
|
1109
|
+
if (!codeChallenge)
|
|
1110
|
+
throw fail("invalid_request", "code_challenge is required (PKCE)");
|
|
1111
|
+
if (codeChallengeMethod !== undefined && codeChallengeMethod !== "S256") {
|
|
1112
|
+
throw fail("invalid_request", "Only code_challenge_method=S256 is supported");
|
|
1113
|
+
}
|
|
1114
|
+
if (!isValidCodeChallenge(codeChallenge))
|
|
1115
|
+
throw fail("invalid_request", "Malformed code_challenge");
|
|
1116
|
+
const resources = [];
|
|
1117
|
+
for (const r of q.getAll("resource")) {
|
|
1118
|
+
try {
|
|
1119
|
+
validateResourceUri(r);
|
|
1120
|
+
} catch (e) {
|
|
1121
|
+
throw fail("invalid_target", e.message);
|
|
1122
|
+
}
|
|
1123
|
+
resources.push(normalizeResource(r));
|
|
1124
|
+
}
|
|
1125
|
+
if (this.config.resource) {
|
|
1126
|
+
for (const r of resources) {
|
|
1127
|
+
if (!resourcesEqual(r, this.config.resource)) {
|
|
1128
|
+
throw fail("invalid_target", `This authorization server only issues tokens for ${this.config.resource}`);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
} else if (resources.length > 1) {
|
|
1132
|
+
throw fail("invalid_target", "Only a single resource parameter is supported");
|
|
1133
|
+
}
|
|
1134
|
+
return {
|
|
1135
|
+
authRequest: {
|
|
1136
|
+
responseType: "code",
|
|
1137
|
+
clientId,
|
|
1138
|
+
redirectUri,
|
|
1139
|
+
scopes,
|
|
1140
|
+
state,
|
|
1141
|
+
codeChallenge,
|
|
1142
|
+
codeChallengeMethod: "S256",
|
|
1143
|
+
resources
|
|
1144
|
+
},
|
|
1145
|
+
client: toPublicClient(stored)
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
async stashAuthRequest(authRequest) {
|
|
1149
|
+
const pending = {
|
|
1150
|
+
...authRequest,
|
|
1151
|
+
id: randomString(32),
|
|
1152
|
+
createdAt: nowSeconds()
|
|
1153
|
+
};
|
|
1154
|
+
await this.storage.set(keys.authRequest(pending.id), stripUndefined2(pending), {
|
|
1155
|
+
ttlSeconds: this.config.authRequestTTL
|
|
1156
|
+
});
|
|
1157
|
+
return pending;
|
|
1158
|
+
}
|
|
1159
|
+
async getAuthRequest(id) {
|
|
1160
|
+
if (!id)
|
|
1161
|
+
return null;
|
|
1162
|
+
return this.storage.get(keys.authRequest(id));
|
|
1163
|
+
}
|
|
1164
|
+
async#resolveAuthRequest(o) {
|
|
1165
|
+
if (o.authRequestId) {
|
|
1166
|
+
const pending = await this.getAuthRequest(o.authRequestId);
|
|
1167
|
+
if (!pending) {
|
|
1168
|
+
throw new OAuthError("invalid_request", "Unknown or expired authorization request");
|
|
1169
|
+
}
|
|
1170
|
+
return { authRequest: pending, pendingId: pending.id };
|
|
1171
|
+
}
|
|
1172
|
+
if (o.authRequest)
|
|
1173
|
+
return { authRequest: o.authRequest };
|
|
1174
|
+
throw new TypeError("authRequestId or authRequest is required");
|
|
1175
|
+
}
|
|
1176
|
+
async completeAuthorization(o) {
|
|
1177
|
+
const { authRequest, pendingId } = await this.#resolveAuthRequest(o);
|
|
1178
|
+
if (typeof o.userId !== "string" || o.userId.length === 0) {
|
|
1179
|
+
throw new TypeError("userId must be a non-empty string");
|
|
1180
|
+
}
|
|
1181
|
+
if (o.userId.includes(":"))
|
|
1182
|
+
throw new TypeError('userId must not contain ":"');
|
|
1183
|
+
if (this.config.tokenFormat === "opaque" && !OPAQUE_USER_ID.test(o.userId)) {
|
|
1184
|
+
throw new TypeError('userId may only contain letters, digits and "-._~+/" when tokenFormat is "opaque"');
|
|
1185
|
+
}
|
|
1186
|
+
const stored = await this.getStoredClient(authRequest.clientId);
|
|
1187
|
+
if (!stored)
|
|
1188
|
+
throw new OAuthError("invalid_request", "Unknown client_id");
|
|
1189
|
+
if (!isRegisteredRedirectUri(stored.redirectUris, authRequest.redirectUri)) {
|
|
1190
|
+
throw new OAuthError("invalid_request", "redirect_uri is no longer registered for this client");
|
|
1191
|
+
}
|
|
1192
|
+
if (!isValidCodeChallenge(authRequest.codeChallenge)) {
|
|
1193
|
+
throw new OAuthError("invalid_request", "Malformed code_challenge");
|
|
1194
|
+
}
|
|
1195
|
+
const scopes = [...new Set(o.scopes)];
|
|
1196
|
+
if (!isSubset(scopes, this.config.scopesSupported)) {
|
|
1197
|
+
throw new OAuthError("invalid_scope", "Granted scope is not in scopesSupported");
|
|
1198
|
+
}
|
|
1199
|
+
if (authRequest.scopes.length > 0 && !isSubset(scopes, authRequest.scopes)) {
|
|
1200
|
+
throw new OAuthError("invalid_scope", "Granted scope exceeds the requested scope");
|
|
1201
|
+
}
|
|
1202
|
+
let resource = this.config.resource ?? authRequest.resources[0];
|
|
1203
|
+
if (o.resource !== undefined) {
|
|
1204
|
+
const requested = normalizeResource(validateResourceUri(o.resource).toString());
|
|
1205
|
+
if (this.config.resource && !resourcesEqual(requested, this.config.resource)) {
|
|
1206
|
+
throw new OAuthError("invalid_target", `This authorization server only issues tokens for ${this.config.resource}`);
|
|
1207
|
+
}
|
|
1208
|
+
resource = requested;
|
|
1209
|
+
}
|
|
1210
|
+
const grantId = randomId();
|
|
1211
|
+
const now = nowSeconds();
|
|
1212
|
+
const code = `${o.userId}:${grantId}:${randomSecret()}`;
|
|
1213
|
+
const { props, propsEncrypted, key } = await this.#sealProps(o.props);
|
|
1214
|
+
const grant = {
|
|
1215
|
+
version: 0,
|
|
1216
|
+
id: grantId,
|
|
1217
|
+
clientId: authRequest.clientId,
|
|
1218
|
+
userId: o.userId,
|
|
1219
|
+
scopes,
|
|
1220
|
+
props,
|
|
1221
|
+
propsEncrypted,
|
|
1222
|
+
metadata: o.metadata,
|
|
1223
|
+
createdAt: now,
|
|
1224
|
+
resource: resource ? normalizeResource(resource) : undefined,
|
|
1225
|
+
redirectUri: authRequest.redirectUri,
|
|
1226
|
+
authCodeHash: await sha256Hex(code),
|
|
1227
|
+
authCodeWrappedKey: key ? await wrapKeyWithCredential(key, code) : undefined,
|
|
1228
|
+
codeChallenge: authRequest.codeChallenge,
|
|
1229
|
+
codeChallengeMethod: "S256"
|
|
1230
|
+
};
|
|
1231
|
+
const existing = [];
|
|
1232
|
+
if (o.revokeExistingGrants !== false) {
|
|
1233
|
+
for (const k of await this.storage.list(keys.grantPrefixForUser(o.userId))) {
|
|
1234
|
+
const g = await this.storage.get(k);
|
|
1235
|
+
if (g?.clientId === grant.clientId && g.id !== grantId)
|
|
1236
|
+
existing.push(g);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
await this.storage.set(keys.grant(o.userId, grantId), stripUndefined2(grant), {
|
|
1240
|
+
ttlSeconds: this.config.authCodeTTL
|
|
1241
|
+
});
|
|
1242
|
+
await this.storage.set(keys.authCode(await sha256Hex(code)), { userId: o.userId, grantId }, { ttlSeconds: this.config.authCodeTTL });
|
|
1243
|
+
if (pendingId)
|
|
1244
|
+
await this.storage.delete(keys.authRequest(pendingId));
|
|
1245
|
+
await Promise.allSettled(existing.map((g) => this.revokeGrant(g.id, g.userId)));
|
|
1246
|
+
const url = new URL(authRequest.redirectUri);
|
|
1247
|
+
url.searchParams.set("code", code);
|
|
1248
|
+
if (authRequest.state !== undefined)
|
|
1249
|
+
url.searchParams.set("state", authRequest.state);
|
|
1250
|
+
url.searchParams.set("iss", this.config.issuer);
|
|
1251
|
+
return { redirectTo: url.toString() };
|
|
1252
|
+
}
|
|
1253
|
+
async rejectAuthorization(o) {
|
|
1254
|
+
const { authRequest, pendingId } = await this.#resolveAuthRequest(o);
|
|
1255
|
+
if (pendingId)
|
|
1256
|
+
await this.storage.delete(keys.authRequest(pendingId));
|
|
1257
|
+
const err = new AuthorizationError(o.error ?? "access_denied", o.description ?? "The user denied the request", {
|
|
1258
|
+
redirectUri: authRequest.redirectUri,
|
|
1259
|
+
state: authRequest.state,
|
|
1260
|
+
issuer: this.config.issuer
|
|
1261
|
+
});
|
|
1262
|
+
return { redirectTo: err.toRedirectUrl() };
|
|
1263
|
+
}
|
|
1264
|
+
async exchangeAuthorizationCode(o) {
|
|
1265
|
+
const parts = o.code.split(":");
|
|
1266
|
+
if (parts.length !== 3)
|
|
1267
|
+
throw new OAuthError("invalid_grant", "Invalid authorization code");
|
|
1268
|
+
const [userId, grantId] = parts;
|
|
1269
|
+
const grant = await this.#getGrant(userId, grantId);
|
|
1270
|
+
if (!grant?.authCodeHash) {
|
|
1271
|
+
throw new OAuthError("invalid_grant", "Invalid authorization code");
|
|
1272
|
+
}
|
|
1273
|
+
const codeHash = await sha256Hex(o.code);
|
|
1274
|
+
if (!timingSafeEqual(codeHash, grant.authCodeHash)) {
|
|
1275
|
+
throw new OAuthError("invalid_grant", "Invalid authorization code");
|
|
1276
|
+
}
|
|
1277
|
+
if (grant.clientId !== o.client.clientId) {
|
|
1278
|
+
throw new OAuthError("invalid_grant", "Authorization code was issued to another client");
|
|
1279
|
+
}
|
|
1280
|
+
if (!grant.codeChallenge) {
|
|
1281
|
+
await this.revokeGrant(grantId, userId);
|
|
1282
|
+
throw new OAuthError("invalid_grant", "Authorization code has already been used");
|
|
1283
|
+
}
|
|
1284
|
+
if (!o.client.grantTypes.includes("authorization_code")) {
|
|
1285
|
+
throw new OAuthError("unauthorized_client", "Client may not use the authorization_code grant");
|
|
1286
|
+
}
|
|
1287
|
+
if (o.redirectUri !== undefined && o.redirectUri !== grant.redirectUri) {
|
|
1288
|
+
throw new OAuthError("invalid_grant", "redirect_uri does not match the authorization request");
|
|
1289
|
+
}
|
|
1290
|
+
if (!o.codeVerifier)
|
|
1291
|
+
throw new OAuthError("invalid_request", "code_verifier is required");
|
|
1292
|
+
if (!await verifyPkce(o.codeVerifier, grant.codeChallenge)) {
|
|
1293
|
+
throw new OAuthError("invalid_grant", "PKCE verification failed");
|
|
1294
|
+
}
|
|
1295
|
+
const resource = this.#resolveTokenResource(grant, o.resource);
|
|
1296
|
+
const requested = parseScope(o.requestedScope);
|
|
1297
|
+
if (requested === null)
|
|
1298
|
+
throw new OAuthError("invalid_scope", "Malformed scope");
|
|
1299
|
+
const scopes = downscope(requested, grant.scopes);
|
|
1300
|
+
if (!scopes)
|
|
1301
|
+
throw new OAuthError("invalid_scope", "Requested scope exceeds the granted scope");
|
|
1302
|
+
if (await this.storage.consume(keys.authCode(codeHash)) === null) {
|
|
1303
|
+
await this.revokeGrant(grantId, userId);
|
|
1304
|
+
throw new OAuthError("invalid_grant", "Authorization code has already been used");
|
|
1305
|
+
}
|
|
1306
|
+
const key = grant.authCodeWrappedKey ? await unwrapKeyWithCredential(grant.authCodeWrappedKey, o.code) : undefined;
|
|
1307
|
+
const props = await this.#openProps(grant.props, grant.propsEncrypted, key);
|
|
1308
|
+
const now = nowSeconds();
|
|
1309
|
+
const refresh = await this.#mintRefreshToken(grant, key, now);
|
|
1310
|
+
delete grant.authCodeWrappedKey;
|
|
1311
|
+
delete grant.codeChallenge;
|
|
1312
|
+
delete grant.codeChallengeMethod;
|
|
1313
|
+
const access = await this.#issueAccessToken({ grant, key, scopes, resource, props, now });
|
|
1314
|
+
if (!await this.#commitGrant(grant, now)) {
|
|
1315
|
+
await this.#discardMinted(grant, access.hash);
|
|
1316
|
+
throw new OAuthError("invalid_grant", "Authorization code has already been used");
|
|
1317
|
+
}
|
|
1318
|
+
await this.#notifyTokenIssued({
|
|
1319
|
+
grantType: "authorization_code",
|
|
1320
|
+
clientId: grant.clientId,
|
|
1321
|
+
userId: grant.userId,
|
|
1322
|
+
grantId: grant.id,
|
|
1323
|
+
scopes,
|
|
1324
|
+
props
|
|
1325
|
+
});
|
|
1326
|
+
return this.#tokenResponse(access, refresh?.token, scopes, resource);
|
|
1327
|
+
}
|
|
1328
|
+
async refreshAccessToken(o) {
|
|
1329
|
+
const presentedHash = await sha256Hex(o.refreshToken);
|
|
1330
|
+
const pointer = await this.storage.get(keys.refresh(presentedHash));
|
|
1331
|
+
if (!pointer)
|
|
1332
|
+
throw new OAuthError("invalid_grant", "Invalid refresh token");
|
|
1333
|
+
for (let attempt = 0;attempt < MAX_COMMIT_ATTEMPTS; attempt++) {
|
|
1334
|
+
const grant = await this.#getGrant(pointer.userId, pointer.grantId);
|
|
1335
|
+
if (!grant)
|
|
1336
|
+
throw new OAuthError("invalid_grant", "Invalid refresh token");
|
|
1337
|
+
if (grant.clientId !== o.client.clientId) {
|
|
1338
|
+
throw new OAuthError("invalid_grant", "Refresh token was issued to another client");
|
|
1339
|
+
}
|
|
1340
|
+
if (!o.client.grantTypes.includes("refresh_token")) {
|
|
1341
|
+
throw new OAuthError("unauthorized_client", "Client may not use the refresh_token grant");
|
|
1342
|
+
}
|
|
1343
|
+
const now = nowSeconds();
|
|
1344
|
+
if (grant.refreshTokenHash && timingSafeEqual(presentedHash, grant.refreshTokenHash)) {
|
|
1345
|
+
const committed = await this.#rotateRefreshToken(grant, o, presentedHash, now);
|
|
1346
|
+
if (committed)
|
|
1347
|
+
return committed;
|
|
1348
|
+
continue;
|
|
1349
|
+
}
|
|
1350
|
+
if (grant.previousRefreshTokenHash && timingSafeEqual(presentedHash, grant.previousRefreshTokenHash)) {
|
|
1351
|
+
const rotatedAt = grant.previousRefreshTokenRotatedAt;
|
|
1352
|
+
const inGrace = rotatedAt !== undefined && now < rotatedAt + this.config.refreshTokenReuseGraceSeconds;
|
|
1353
|
+
if (!inGrace || !grant.previousRefreshResponse) {
|
|
1354
|
+
await this.revokeGrant(grant.id, grant.userId);
|
|
1355
|
+
throw new OAuthError("invalid_grant", "Refresh token has already been used");
|
|
1356
|
+
}
|
|
1357
|
+
return this.#replayCachedResponse(grant.previousRefreshResponse, o.refreshToken, now);
|
|
1358
|
+
}
|
|
1359
|
+
await this.revokeGrant(grant.id, grant.userId);
|
|
1360
|
+
throw new OAuthError("invalid_grant", "Refresh token has already been used");
|
|
1361
|
+
}
|
|
1362
|
+
throw new OAuthError("server_error", "Refresh token rotation did not settle");
|
|
1363
|
+
}
|
|
1364
|
+
async#rotateRefreshToken(grant, o, presentedHash, now) {
|
|
1365
|
+
if (grant.expiresAt !== undefined && grant.expiresAt <= now) {
|
|
1366
|
+
throw new OAuthError("invalid_grant", "Refresh token has expired");
|
|
1367
|
+
}
|
|
1368
|
+
const requested = parseScope(o.requestedScope);
|
|
1369
|
+
if (requested === null)
|
|
1370
|
+
throw new OAuthError("invalid_scope", "Malformed scope");
|
|
1371
|
+
const scopes = downscope(requested, grant.scopes);
|
|
1372
|
+
if (!scopes)
|
|
1373
|
+
throw new OAuthError("invalid_scope", "Requested scope exceeds the granted scope");
|
|
1374
|
+
const resource = this.#resolveTokenResource(grant, o.resource);
|
|
1375
|
+
const wrappedKey = grant.refreshTokenWrappedKey;
|
|
1376
|
+
const key = wrappedKey ? await unwrapKeyWithCredential(wrappedKey, o.refreshToken) : undefined;
|
|
1377
|
+
const props = await this.#openProps(grant.props, grant.propsEncrypted, key);
|
|
1378
|
+
grant.previousRefreshTokenHash = presentedHash;
|
|
1379
|
+
grant.previousRefreshTokenRotatedAt = now;
|
|
1380
|
+
const refresh = await this.#mintRefreshToken(grant, key, now, true);
|
|
1381
|
+
const access = await this.#issueAccessToken({ grant, key, scopes, resource, props, now });
|
|
1382
|
+
const response = this.#tokenResponse(access, refresh?.token, scopes, resource);
|
|
1383
|
+
const cached = {
|
|
1384
|
+
response,
|
|
1385
|
+
accessTokenExpiresAt: now + access.expiresIn
|
|
1386
|
+
};
|
|
1387
|
+
grant.previousRefreshResponse = await sealWithCredential(o.refreshToken, JSON.stringify(cached));
|
|
1388
|
+
if (!await this.#commitGrant(grant, now)) {
|
|
1389
|
+
await this.#discardMinted(grant, access.hash);
|
|
1390
|
+
return null;
|
|
1391
|
+
}
|
|
1392
|
+
await this.#notifyTokenIssued({
|
|
1393
|
+
grantType: "refresh_token",
|
|
1394
|
+
clientId: grant.clientId,
|
|
1395
|
+
userId: grant.userId,
|
|
1396
|
+
grantId: grant.id,
|
|
1397
|
+
scopes,
|
|
1398
|
+
props
|
|
1399
|
+
});
|
|
1400
|
+
return response;
|
|
1401
|
+
}
|
|
1402
|
+
async#replayCachedResponse(sealed, refreshToken, now) {
|
|
1403
|
+
const cached = JSON.parse(await openWithCredential(refreshToken, sealed));
|
|
1404
|
+
if (cached.accessTokenExpiresAt <= now) {
|
|
1405
|
+
throw new OAuthError("invalid_grant", "Refresh token has already been used");
|
|
1406
|
+
}
|
|
1407
|
+
return { ...cached.response, expires_in: cached.accessTokenExpiresAt - now };
|
|
1408
|
+
}
|
|
1409
|
+
#resolveTokenResource(grant, requested) {
|
|
1410
|
+
if (requested === undefined)
|
|
1411
|
+
return grant.resource;
|
|
1412
|
+
let normalized;
|
|
1413
|
+
try {
|
|
1414
|
+
normalized = normalizeResource(validateResourceUri(requested).toString());
|
|
1415
|
+
} catch (e) {
|
|
1416
|
+
throw new OAuthError("invalid_target", e.message);
|
|
1417
|
+
}
|
|
1418
|
+
if (this.config.resource && !resourcesEqual(normalized, this.config.resource)) {
|
|
1419
|
+
throw new OAuthError("invalid_target", `This authorization server only issues tokens for ${this.config.resource}`);
|
|
1420
|
+
}
|
|
1421
|
+
if (grant.resource && !resourcesEqual(normalized, grant.resource)) {
|
|
1422
|
+
throw new OAuthError("invalid_target", "resource does not match the authorized resource");
|
|
1423
|
+
}
|
|
1424
|
+
if (!grant.resource && !this.config.resource) {
|
|
1425
|
+
throw new OAuthError("invalid_target", "The authorization was not bound to a resource");
|
|
1426
|
+
}
|
|
1427
|
+
return normalized;
|
|
1428
|
+
}
|
|
1429
|
+
async#mintRefreshToken(grant, key, now, keepExpiry = false) {
|
|
1430
|
+
if (this.config.refreshTokenTTL === 0)
|
|
1431
|
+
return null;
|
|
1432
|
+
const token = randomString(48);
|
|
1433
|
+
const hash = await sha256Hex(token);
|
|
1434
|
+
grant.refreshTokenHash = hash;
|
|
1435
|
+
grant.refreshTokenWrappedKey = key ? await wrapKeyWithCredential(key, token) : undefined;
|
|
1436
|
+
if (!keepExpiry || grant.expiresAt === undefined) {
|
|
1437
|
+
grant.expiresAt = now + this.config.refreshTokenTTL;
|
|
1438
|
+
}
|
|
1439
|
+
const ttl = Math.max(1, grant.expiresAt - now);
|
|
1440
|
+
await this.storage.set(keys.refresh(hash), { userId: grant.userId, grantId: grant.id }, { ttlSeconds: ttl });
|
|
1441
|
+
return { token };
|
|
1442
|
+
}
|
|
1443
|
+
async#notifyTokenIssued(input) {
|
|
1444
|
+
try {
|
|
1445
|
+
await this.config.hooks.onTokenIssued?.(input);
|
|
1446
|
+
} catch (e) {
|
|
1447
|
+
this.config.hooks.onError?.({
|
|
1448
|
+
code: "server_error",
|
|
1449
|
+
description: "onTokenIssued hook failed",
|
|
1450
|
+
status: 500
|
|
1451
|
+
});
|
|
1452
|
+
console.error("[elysia-oauth-provider] onTokenIssued hook failed", e);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
async#getGrant(userId, grantId) {
|
|
1456
|
+
const grant = await this.storage.get(keys.grant(userId, grantId));
|
|
1457
|
+
if (!grant || !Number.isInteger(grant.version))
|
|
1458
|
+
return null;
|
|
1459
|
+
return grant;
|
|
1460
|
+
}
|
|
1461
|
+
async#commitGrant(grant, now) {
|
|
1462
|
+
const ttl = grant.expiresAt !== undefined ? Math.max(1, grant.expiresAt - now) : this.config.accessTokenTTL;
|
|
1463
|
+
const next = stripUndefined2({ ...grant, version: grant.version + 1 });
|
|
1464
|
+
const ok = await this.storage.compareAndSet(keys.grant(grant.userId, grant.id), grant.version, next, { ttlSeconds: ttl });
|
|
1465
|
+
if (ok)
|
|
1466
|
+
grant.version = next.version;
|
|
1467
|
+
return ok;
|
|
1468
|
+
}
|
|
1469
|
+
async#discardMinted(grant, accessTokenHash) {
|
|
1470
|
+
await this.storage.delete(keys.token(grant.userId, grant.id, accessTokenHash));
|
|
1471
|
+
if (grant.refreshTokenHash)
|
|
1472
|
+
await this.storage.delete(keys.refresh(grant.refreshTokenHash));
|
|
1473
|
+
}
|
|
1474
|
+
async#issueAccessToken(o) {
|
|
1475
|
+
let ttl = this.config.accessTokenTTL;
|
|
1476
|
+
if (o.grant.expiresAt !== undefined) {
|
|
1477
|
+
ttl = Math.max(1, Math.min(ttl, o.grant.expiresAt - o.now));
|
|
1478
|
+
}
|
|
1479
|
+
const expiresAt = o.now + ttl;
|
|
1480
|
+
let token;
|
|
1481
|
+
if (this.#signer) {
|
|
1482
|
+
const signer = await this.#signer;
|
|
1483
|
+
const extra = await this.config.accessTokenClaims?.({
|
|
1484
|
+
userId: o.grant.userId,
|
|
1485
|
+
clientId: o.grant.clientId,
|
|
1486
|
+
grantId: o.grant.id,
|
|
1487
|
+
scopes: o.scopes,
|
|
1488
|
+
resource: o.resource,
|
|
1489
|
+
props: o.props
|
|
1490
|
+
});
|
|
1491
|
+
const clash = Object.keys(extra ?? {}).filter((c) => ACCESS_TOKEN_REGISTERED_CLAIMS.includes(c));
|
|
1492
|
+
if (clash.length > 0) {
|
|
1493
|
+
throw new TypeError(`accessTokenClaims may not set registered claims: ${clash.join(", ")}`);
|
|
1494
|
+
}
|
|
1495
|
+
token = await signer.sign({
|
|
1496
|
+
...extra,
|
|
1497
|
+
iss: this.config.issuer,
|
|
1498
|
+
sub: o.grant.userId,
|
|
1499
|
+
aud: o.resource ?? this.config.issuer,
|
|
1500
|
+
client_id: o.grant.clientId,
|
|
1501
|
+
scope: formatScope(o.scopes),
|
|
1502
|
+
grant_id: o.grant.id
|
|
1503
|
+
}, { issuedAt: o.now, expiresAt, jti: randomId() });
|
|
1504
|
+
} else {
|
|
1505
|
+
token = `${o.grant.userId}:${o.grant.id}:${randomSecret()}`;
|
|
1506
|
+
}
|
|
1507
|
+
const hash = await sha256Hex(token);
|
|
1508
|
+
const record = {
|
|
1509
|
+
id: hash,
|
|
1510
|
+
grantId: o.grant.id,
|
|
1511
|
+
userId: o.grant.userId,
|
|
1512
|
+
clientId: o.grant.clientId,
|
|
1513
|
+
scopes: o.scopes,
|
|
1514
|
+
createdAt: o.now,
|
|
1515
|
+
expiresAt,
|
|
1516
|
+
audience: o.resource,
|
|
1517
|
+
wrappedKey: o.key ? await wrapKeyWithCredential(o.key, token) : undefined,
|
|
1518
|
+
props: o.grant.props,
|
|
1519
|
+
propsEncrypted: o.grant.propsEncrypted
|
|
1520
|
+
};
|
|
1521
|
+
await this.storage.set(keys.token(o.grant.userId, o.grant.id, hash), stripUndefined2(record), {
|
|
1522
|
+
ttlSeconds: ttl
|
|
1523
|
+
});
|
|
1524
|
+
return { token, hash, expiresIn: ttl };
|
|
1525
|
+
}
|
|
1526
|
+
#tokenResponse(access, refreshToken, scopes, resource) {
|
|
1527
|
+
const res = {
|
|
1528
|
+
access_token: access.token,
|
|
1529
|
+
token_type: "Bearer",
|
|
1530
|
+
expires_in: access.expiresIn,
|
|
1531
|
+
scope: formatScope(scopes)
|
|
1532
|
+
};
|
|
1533
|
+
if (refreshToken)
|
|
1534
|
+
res.refresh_token = refreshToken;
|
|
1535
|
+
if (resource)
|
|
1536
|
+
res.resource = resource;
|
|
1537
|
+
return res;
|
|
1538
|
+
}
|
|
1539
|
+
async#locateAccessToken(token) {
|
|
1540
|
+
let userId;
|
|
1541
|
+
let grantId;
|
|
1542
|
+
if (this.#signer) {
|
|
1543
|
+
const payload = await (await this.#signer).verify(token, { issuer: this.config.issuer });
|
|
1544
|
+
if (!payload || typeof payload.sub !== "string" || typeof payload.grant_id !== "string") {
|
|
1545
|
+
return null;
|
|
1546
|
+
}
|
|
1547
|
+
userId = payload.sub;
|
|
1548
|
+
grantId = payload.grant_id;
|
|
1549
|
+
} else {
|
|
1550
|
+
const parts = token.split(":");
|
|
1551
|
+
if (parts.length !== 3)
|
|
1552
|
+
return null;
|
|
1553
|
+
[userId, grantId] = parts;
|
|
1554
|
+
}
|
|
1555
|
+
const hash = await sha256Hex(token);
|
|
1556
|
+
const record = await this.storage.get(keys.token(userId, grantId, hash));
|
|
1557
|
+
if (!record || !timingSafeEqual(record.id, hash))
|
|
1558
|
+
return null;
|
|
1559
|
+
return record;
|
|
1560
|
+
}
|
|
1561
|
+
async verifyAccessToken(token, requestUrl) {
|
|
1562
|
+
const record = await this.#locateAccessToken(token);
|
|
1563
|
+
if (!record)
|
|
1564
|
+
return null;
|
|
1565
|
+
if (record.expiresAt <= nowSeconds())
|
|
1566
|
+
return null;
|
|
1567
|
+
if (requestUrl && record.audience && !audienceCoversUrl(record.audience, requestUrl)) {
|
|
1568
|
+
throw new OAuthError("invalid_token", "Token audience does not cover this resource");
|
|
1569
|
+
}
|
|
1570
|
+
const key = record.wrappedKey ? await unwrapKeyWithCredential(record.wrappedKey, token) : undefined;
|
|
1571
|
+
const props = await this.#openProps(record.props, record.propsEncrypted, key);
|
|
1572
|
+
return {
|
|
1573
|
+
userId: record.userId,
|
|
1574
|
+
clientId: record.clientId,
|
|
1575
|
+
grantId: record.grantId,
|
|
1576
|
+
scopes: record.scopes,
|
|
1577
|
+
props,
|
|
1578
|
+
expiresAt: record.expiresAt,
|
|
1579
|
+
createdAt: record.createdAt,
|
|
1580
|
+
audience: record.audience,
|
|
1581
|
+
token
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
async revokeToken(o) {
|
|
1585
|
+
const tryAccess = async () => {
|
|
1586
|
+
const record = await this.#locateAccessToken(o.token);
|
|
1587
|
+
if (record?.clientId !== o.client.clientId)
|
|
1588
|
+
return false;
|
|
1589
|
+
await this.storage.delete(keys.token(record.userId, record.grantId, record.id));
|
|
1590
|
+
return true;
|
|
1591
|
+
};
|
|
1592
|
+
const tryRefresh = async () => {
|
|
1593
|
+
const hash = await sha256Hex(o.token);
|
|
1594
|
+
const pointer = await this.storage.get(keys.refresh(hash));
|
|
1595
|
+
if (!pointer)
|
|
1596
|
+
return false;
|
|
1597
|
+
const grant = await this.storage.get(keys.grant(pointer.userId, pointer.grantId));
|
|
1598
|
+
if (grant?.clientId !== o.client.clientId)
|
|
1599
|
+
return false;
|
|
1600
|
+
await this.revokeGrant(grant.id, grant.userId);
|
|
1601
|
+
return true;
|
|
1602
|
+
};
|
|
1603
|
+
if (o.tokenTypeHint === "refresh_token") {
|
|
1604
|
+
if (!await tryRefresh())
|
|
1605
|
+
await tryAccess();
|
|
1606
|
+
} else if (!await tryAccess())
|
|
1607
|
+
await tryRefresh();
|
|
1608
|
+
}
|
|
1609
|
+
async revokeGrant(grantId, userId) {
|
|
1610
|
+
const grantKey = keys.grant(userId, grantId);
|
|
1611
|
+
for (let attempt = 0;attempt < MAX_COMMIT_ATTEMPTS; attempt++) {
|
|
1612
|
+
const grant = await this.storage.get(grantKey);
|
|
1613
|
+
for (const k of await this.storage.list(keys.tokenPrefixForGrant(userId, grantId))) {
|
|
1614
|
+
await this.storage.delete(k);
|
|
1615
|
+
}
|
|
1616
|
+
if (!grant)
|
|
1617
|
+
return;
|
|
1618
|
+
if (grant.refreshTokenHash)
|
|
1619
|
+
await this.storage.delete(keys.refresh(grant.refreshTokenHash));
|
|
1620
|
+
if (grant.previousRefreshTokenHash) {
|
|
1621
|
+
await this.storage.delete(keys.refresh(grant.previousRefreshTokenHash));
|
|
1622
|
+
}
|
|
1623
|
+
if (!Number.isInteger(grant.version)) {
|
|
1624
|
+
await this.storage.delete(grantKey);
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1627
|
+
if (await this.storage.compareAndDelete(grantKey, grant.version))
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
throw new OAuthError("server_error", "Grant revocation did not settle");
|
|
1631
|
+
}
|
|
1632
|
+
async listUserGrants(userId) {
|
|
1633
|
+
return this.#summarizeGrants(await this.storage.list(keys.grantPrefixForUser(userId)));
|
|
1634
|
+
}
|
|
1635
|
+
async listGrants() {
|
|
1636
|
+
return this.#summarizeGrants(await this.storage.list(KEY_PREFIX.grant));
|
|
1637
|
+
}
|
|
1638
|
+
async listClientGrants(clientId) {
|
|
1639
|
+
return (await this.listGrants()).filter((g) => g.clientId === clientId);
|
|
1640
|
+
}
|
|
1641
|
+
async#summarizeGrants(grantKeys) {
|
|
1642
|
+
const out = [];
|
|
1643
|
+
for (const k of grantKeys) {
|
|
1644
|
+
const g = await this.storage.get(k);
|
|
1645
|
+
if (!g)
|
|
1646
|
+
continue;
|
|
1647
|
+
out.push({
|
|
1648
|
+
id: g.id,
|
|
1649
|
+
clientId: g.clientId,
|
|
1650
|
+
userId: g.userId,
|
|
1651
|
+
scopes: g.scopes,
|
|
1652
|
+
metadata: g.metadata,
|
|
1653
|
+
createdAt: g.createdAt,
|
|
1654
|
+
expiresAt: g.expiresAt,
|
|
1655
|
+
resource: g.resource
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
return out;
|
|
1659
|
+
}
|
|
1660
|
+
async#sealProps(props) {
|
|
1661
|
+
if (!this.config.encryptProps) {
|
|
1662
|
+
return { props: JSON.stringify(props ?? null), propsEncrypted: false, key: undefined };
|
|
1663
|
+
}
|
|
1664
|
+
const { ciphertext, key } = await encryptProps(props);
|
|
1665
|
+
return { props: ciphertext, propsEncrypted: true, key };
|
|
1666
|
+
}
|
|
1667
|
+
async#openProps(sealed, encrypted, key) {
|
|
1668
|
+
if (!encrypted)
|
|
1669
|
+
return JSON.parse(sealed);
|
|
1670
|
+
if (!key)
|
|
1671
|
+
throw new OAuthError("server_error", "Missing props key");
|
|
1672
|
+
return decryptProps(sealed, key);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
function invalidClient(description, method) {
|
|
1676
|
+
const headers = {};
|
|
1677
|
+
if (method === "client_secret_basic")
|
|
1678
|
+
headers["WWW-Authenticate"] = 'Basic realm="OAuth"';
|
|
1679
|
+
return new OAuthError("invalid_client", description, { status: 401, headers });
|
|
1680
|
+
}
|
|
1681
|
+
function toPublicClient(stored) {
|
|
1682
|
+
const { clientSecretHash: _hash, ...rest } = stored;
|
|
1683
|
+
return { ...rest };
|
|
1684
|
+
}
|
|
1685
|
+
function stripUndefined2(o) {
|
|
1686
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
// src/endpoints/authorize.ts
|
|
1690
|
+
async function handleAuthorize(core, request) {
|
|
1691
|
+
const url = new URL(request.url);
|
|
1692
|
+
const { authRequest, client } = await core.parseAuthRequest(url);
|
|
1693
|
+
const pending = await core.stashAuthRequest(authRequest);
|
|
1694
|
+
try {
|
|
1695
|
+
await core.config.hooks.onAuthorize?.({ authRequest: pending, client, request });
|
|
1696
|
+
} catch (e) {
|
|
1697
|
+
if (e instanceof AuthorizationError)
|
|
1698
|
+
throw e;
|
|
1699
|
+
console.error("[elysia-oauth-provider] onAuthorize hook failed", e);
|
|
1700
|
+
throw new AuthorizationError("access_denied", "Authorization rejected", {
|
|
1701
|
+
redirectUri: authRequest.redirectUri,
|
|
1702
|
+
state: authRequest.state,
|
|
1703
|
+
issuer: core.config.issuer
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
return core.config.handleAuthorize({
|
|
1707
|
+
authRequest: pending,
|
|
1708
|
+
authRequestId: pending.id,
|
|
1709
|
+
client,
|
|
1710
|
+
request
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
// src/endpoints/http.ts
|
|
1715
|
+
var NO_STORE = { "Cache-Control": "no-store", Pragma: "no-cache" };
|
|
1716
|
+
function corsHeaders(request) {
|
|
1717
|
+
const origin = request.headers.get("Origin");
|
|
1718
|
+
if (!origin)
|
|
1719
|
+
return {};
|
|
1720
|
+
return {
|
|
1721
|
+
"Access-Control-Allow-Origin": origin,
|
|
1722
|
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
1723
|
+
"Access-Control-Allow-Headers": "Authorization, Content-Type, Mcp-Protocol-Version, *",
|
|
1724
|
+
"Access-Control-Expose-Headers": "WWW-Authenticate, Retry-After",
|
|
1725
|
+
"Access-Control-Max-Age": "86400",
|
|
1726
|
+
Vary: "Origin"
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
function json(body, init = {}) {
|
|
1730
|
+
return Response.json(body, { status: init.status ?? 200, headers: init.headers });
|
|
1731
|
+
}
|
|
1732
|
+
function methodNotAllowed(allow) {
|
|
1733
|
+
return json({ error: "invalid_request", error_description: `Method not allowed. Use ${allow}.` }, { status: 405, headers: { Allow: allow, ...NO_STORE } });
|
|
1734
|
+
}
|
|
1735
|
+
async function readBodyText(request, maxBytes) {
|
|
1736
|
+
const tooLarge = () => new OAuthError("invalid_request", "Request body too large", { status: 413 });
|
|
1737
|
+
if (!request.body)
|
|
1738
|
+
return "";
|
|
1739
|
+
const reader = request.body.getReader();
|
|
1740
|
+
const chunks = [];
|
|
1741
|
+
let total = 0;
|
|
1742
|
+
for (;; ) {
|
|
1743
|
+
const { done, value } = await reader.read();
|
|
1744
|
+
if (done)
|
|
1745
|
+
break;
|
|
1746
|
+
total += value.byteLength;
|
|
1747
|
+
if (total > maxBytes) {
|
|
1748
|
+
await reader.cancel().catch(() => {
|
|
1749
|
+
return;
|
|
1750
|
+
});
|
|
1751
|
+
throw tooLarge();
|
|
1752
|
+
}
|
|
1753
|
+
chunks.push(value);
|
|
1754
|
+
}
|
|
1755
|
+
const bytes = new Uint8Array(total);
|
|
1756
|
+
let offset = 0;
|
|
1757
|
+
for (const c of chunks) {
|
|
1758
|
+
bytes.set(c, offset);
|
|
1759
|
+
offset += c.byteLength;
|
|
1760
|
+
}
|
|
1761
|
+
return new TextDecoder().decode(bytes);
|
|
1762
|
+
}
|
|
1763
|
+
async function parseFormBody(request, repeatable = ["resource"]) {
|
|
1764
|
+
const ct = request.headers.get("Content-Type") ?? "";
|
|
1765
|
+
const mediaType = ct.split(";")[0].trim().toLowerCase();
|
|
1766
|
+
if (mediaType !== "application/x-www-form-urlencoded") {
|
|
1767
|
+
throw new OAuthError("invalid_request", "Content-Type must be application/x-www-form-urlencoded");
|
|
1768
|
+
}
|
|
1769
|
+
let params;
|
|
1770
|
+
try {
|
|
1771
|
+
params = new URLSearchParams(await request.text());
|
|
1772
|
+
} catch {
|
|
1773
|
+
throw new OAuthError("invalid_request", "Malformed request body");
|
|
1774
|
+
}
|
|
1775
|
+
const seen = new Set;
|
|
1776
|
+
for (const key of params.keys()) {
|
|
1777
|
+
if (seen.has(key) && !repeatable.includes(key)) {
|
|
1778
|
+
throw new OAuthError("invalid_request", `Parameter "${key}" must not be repeated`);
|
|
1779
|
+
}
|
|
1780
|
+
seen.add(key);
|
|
1781
|
+
}
|
|
1782
|
+
return {
|
|
1783
|
+
get: (name) => params.get(name) ?? undefined,
|
|
1784
|
+
getAll: (name) => params.getAll(name)
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
function extractClientCredentials(request, form) {
|
|
1788
|
+
const authz = request.headers.get("Authorization");
|
|
1789
|
+
const bodyId = form.get("client_id");
|
|
1790
|
+
const bodySecret = form.get("client_secret");
|
|
1791
|
+
if (authz && /^basic\s/i.test(authz)) {
|
|
1792
|
+
if (bodySecret !== undefined) {
|
|
1793
|
+
throw new OAuthError("invalid_request", "Multiple client authentication methods used");
|
|
1794
|
+
}
|
|
1795
|
+
let decoded;
|
|
1796
|
+
try {
|
|
1797
|
+
decoded = atob(authz.slice(6).trim());
|
|
1798
|
+
} catch {
|
|
1799
|
+
throw new OAuthError("invalid_client", "Malformed Authorization header", {
|
|
1800
|
+
status: 401,
|
|
1801
|
+
headers: { "WWW-Authenticate": 'Basic realm="OAuth"' }
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
const idx = decoded.indexOf(":");
|
|
1805
|
+
if (idx < 0) {
|
|
1806
|
+
throw new OAuthError("invalid_client", "Malformed Authorization header", {
|
|
1807
|
+
status: 401,
|
|
1808
|
+
headers: { "WWW-Authenticate": 'Basic realm="OAuth"' }
|
|
1809
|
+
});
|
|
1810
|
+
}
|
|
1811
|
+
const clientId = safeDecode(decoded.slice(0, idx));
|
|
1812
|
+
const clientSecret = safeDecode(decoded.slice(idx + 1));
|
|
1813
|
+
if (bodyId !== undefined && bodyId !== clientId) {
|
|
1814
|
+
throw new OAuthError("invalid_request", "client_id in body does not match Authorization header");
|
|
1815
|
+
}
|
|
1816
|
+
return { clientId, clientSecret, method: "client_secret_basic" };
|
|
1817
|
+
}
|
|
1818
|
+
if (!bodyId)
|
|
1819
|
+
throw new OAuthError("invalid_client", "Missing client_id", { status: 401 });
|
|
1820
|
+
if (bodySecret !== undefined)
|
|
1821
|
+
return { clientId: bodyId, clientSecret: bodySecret, method: "client_secret_post" };
|
|
1822
|
+
return { clientId: bodyId, method: "none" };
|
|
1823
|
+
}
|
|
1824
|
+
function safeDecode(s) {
|
|
1825
|
+
try {
|
|
1826
|
+
return decodeURIComponent(s);
|
|
1827
|
+
} catch {
|
|
1828
|
+
return s;
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
// src/endpoints/metadata.ts
|
|
1833
|
+
function authorizationServerMetadata(core) {
|
|
1834
|
+
const { config } = core;
|
|
1835
|
+
const doc = {
|
|
1836
|
+
issuer: config.issuer,
|
|
1837
|
+
authorization_endpoint: config.urls.authorize,
|
|
1838
|
+
token_endpoint: config.urls.token,
|
|
1839
|
+
revocation_endpoint: config.urls.revoke,
|
|
1840
|
+
response_types_supported: ["code"],
|
|
1841
|
+
response_modes_supported: ["query"],
|
|
1842
|
+
grant_types_supported: config.refreshTokenTTL === 0 ? ["authorization_code"] : ["authorization_code", "refresh_token"],
|
|
1843
|
+
token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
|
|
1844
|
+
revocation_endpoint_auth_methods_supported: [
|
|
1845
|
+
"client_secret_basic",
|
|
1846
|
+
"client_secret_post",
|
|
1847
|
+
"none"
|
|
1848
|
+
],
|
|
1849
|
+
code_challenge_methods_supported: ["S256"],
|
|
1850
|
+
authorization_response_iss_parameter_supported: true
|
|
1851
|
+
};
|
|
1852
|
+
if (config.clientRegistration.enabled)
|
|
1853
|
+
doc.registration_endpoint = config.urls.register;
|
|
1854
|
+
if (config.scopesSupported)
|
|
1855
|
+
doc.scopes_supported = config.scopesSupported;
|
|
1856
|
+
if (config.tokenFormat !== "opaque")
|
|
1857
|
+
doc.jwks_uri = config.urls.jwks;
|
|
1858
|
+
return doc;
|
|
1859
|
+
}
|
|
1860
|
+
function protectedResourceMetadata(core, suffix) {
|
|
1861
|
+
const { config } = core;
|
|
1862
|
+
const rm = config.resourceMetadata;
|
|
1863
|
+
const resource = config.resource ?? `${config.issuerUrl.origin}${suffix}`;
|
|
1864
|
+
const doc = {
|
|
1865
|
+
resource,
|
|
1866
|
+
authorization_servers: rm.authorizationServers ?? [config.issuer],
|
|
1867
|
+
bearer_methods_supported: ["header"]
|
|
1868
|
+
};
|
|
1869
|
+
const scopes = (rm.scopesSupported ?? config.scopesSupported)?.filter((s) => s !== "offline_access");
|
|
1870
|
+
if (scopes && scopes.length > 0)
|
|
1871
|
+
doc.scopes_supported = [...new Set(scopes)];
|
|
1872
|
+
if (rm.resourceName)
|
|
1873
|
+
doc.resource_name = rm.resourceName;
|
|
1874
|
+
if (rm.resourceDocumentation)
|
|
1875
|
+
doc.resource_documentation = rm.resourceDocumentation;
|
|
1876
|
+
return doc;
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
// src/endpoints/register.ts
|
|
1880
|
+
async function handleRegister(core, request) {
|
|
1881
|
+
const { config } = core;
|
|
1882
|
+
const len = Number(request.headers.get("Content-Length") ?? "0");
|
|
1883
|
+
if (len > config.clientRegistration.maxBodyBytes) {
|
|
1884
|
+
throw new OAuthError("invalid_request", "Request body too large", { status: 413 });
|
|
1885
|
+
}
|
|
1886
|
+
const text = await readBodyText(request, config.clientRegistration.maxBodyBytes);
|
|
1887
|
+
let raw;
|
|
1888
|
+
try {
|
|
1889
|
+
raw = JSON.parse(text);
|
|
1890
|
+
} catch {
|
|
1891
|
+
throw new OAuthError("invalid_request", "Request body must be valid JSON");
|
|
1892
|
+
}
|
|
1893
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
1894
|
+
throw new OAuthError("invalid_client_metadata", "Client metadata must be a JSON object");
|
|
1895
|
+
}
|
|
1896
|
+
const m = raw;
|
|
1897
|
+
const str = (k) => {
|
|
1898
|
+
const v = m[k];
|
|
1899
|
+
if (v === undefined)
|
|
1900
|
+
return;
|
|
1901
|
+
if (typeof v !== "string")
|
|
1902
|
+
throw new OAuthError("invalid_client_metadata", `${k} must be a string`);
|
|
1903
|
+
return v;
|
|
1904
|
+
};
|
|
1905
|
+
const strArr = (k) => {
|
|
1906
|
+
const v = m[k];
|
|
1907
|
+
if (v === undefined)
|
|
1908
|
+
return;
|
|
1909
|
+
if (!Array.isArray(v) || !v.every((x) => typeof x === "string")) {
|
|
1910
|
+
throw new OAuthError("invalid_client_metadata", `${k} must be an array of strings`);
|
|
1911
|
+
}
|
|
1912
|
+
return v;
|
|
1913
|
+
};
|
|
1914
|
+
const httpUrl = (k) => {
|
|
1915
|
+
const v = str(k);
|
|
1916
|
+
if (v === undefined)
|
|
1917
|
+
return;
|
|
1918
|
+
let u;
|
|
1919
|
+
try {
|
|
1920
|
+
u = new URL(v);
|
|
1921
|
+
} catch {
|
|
1922
|
+
throw new OAuthError("invalid_client_metadata", `${k} must be an absolute URL`);
|
|
1923
|
+
}
|
|
1924
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") {
|
|
1925
|
+
throw new OAuthError("invalid_client_metadata", `${k} must be an http(s) URL`);
|
|
1926
|
+
}
|
|
1927
|
+
return v;
|
|
1928
|
+
};
|
|
1929
|
+
const redirectUris = strArr("redirect_uris");
|
|
1930
|
+
if (!redirectUris || redirectUris.length === 0) {
|
|
1931
|
+
throw new OAuthError("invalid_redirect_uri", "redirect_uris is required");
|
|
1932
|
+
}
|
|
1933
|
+
let method = str("token_endpoint_auth_method");
|
|
1934
|
+
const methodChoices = strArr("token_endpoint_auth_methods_supported");
|
|
1935
|
+
if (method === undefined && methodChoices) {
|
|
1936
|
+
method = AUTH_METHODS.find((am) => methodChoices.includes(am));
|
|
1937
|
+
if (!method)
|
|
1938
|
+
throw new OAuthError("invalid_client_metadata", "No supported token_endpoint_auth_method");
|
|
1939
|
+
}
|
|
1940
|
+
if (method !== undefined && !AUTH_METHODS.includes(method)) {
|
|
1941
|
+
throw new OAuthError("invalid_client_metadata", `Unsupported token_endpoint_auth_method "${method}"`);
|
|
1942
|
+
}
|
|
1943
|
+
let hookResult;
|
|
1944
|
+
try {
|
|
1945
|
+
hookResult = await config.hooks.onClientRegister?.({ metadata: m, request });
|
|
1946
|
+
} catch (e) {
|
|
1947
|
+
if (e instanceof OAuthError)
|
|
1948
|
+
throw e;
|
|
1949
|
+
throw new OAuthError("server_error", "Client registration failed", { cause: e });
|
|
1950
|
+
}
|
|
1951
|
+
if (hookResult && "error" in hookResult) {
|
|
1952
|
+
throw new OAuthError(hookResult.error, hookResult.description ?? "Registration rejected", {
|
|
1953
|
+
status: hookResult.status
|
|
1954
|
+
});
|
|
1955
|
+
}
|
|
1956
|
+
const input = {
|
|
1957
|
+
redirectUris,
|
|
1958
|
+
clientName: str("client_name"),
|
|
1959
|
+
clientUri: httpUrl("client_uri"),
|
|
1960
|
+
logoUri: httpUrl("logo_uri"),
|
|
1961
|
+
policyUri: httpUrl("policy_uri"),
|
|
1962
|
+
tosUri: httpUrl("tos_uri"),
|
|
1963
|
+
jwksUri: httpUrl("jwks_uri"),
|
|
1964
|
+
contacts: strArr("contacts"),
|
|
1965
|
+
grantTypes: strArr("grant_types"),
|
|
1966
|
+
responseTypes: strArr("response_types"),
|
|
1967
|
+
scope: hookResult?.scope ?? str("scope"),
|
|
1968
|
+
tokenEndpointAuthMethod: method,
|
|
1969
|
+
metadata: hookResult?.metadata,
|
|
1970
|
+
dynamicallyRegistered: true
|
|
1971
|
+
};
|
|
1972
|
+
const client = await core.createClient(input);
|
|
1973
|
+
return json(toRegistrationResponse(client, config.clientRegistrationTTL), {
|
|
1974
|
+
status: 201,
|
|
1975
|
+
headers: NO_STORE
|
|
1976
|
+
});
|
|
1977
|
+
}
|
|
1978
|
+
function toRegistrationResponse(client, ttl) {
|
|
1979
|
+
const out = {
|
|
1980
|
+
client_id: client.clientId,
|
|
1981
|
+
client_id_issued_at: client.registrationDate,
|
|
1982
|
+
redirect_uris: client.redirectUris,
|
|
1983
|
+
grant_types: client.grantTypes,
|
|
1984
|
+
response_types: client.responseTypes,
|
|
1985
|
+
token_endpoint_auth_method: client.tokenEndpointAuthMethod
|
|
1986
|
+
};
|
|
1987
|
+
if (client.clientSecret) {
|
|
1988
|
+
out.client_secret = client.clientSecret;
|
|
1989
|
+
out.client_secret_expires_at = ttl === undefined ? 0 : client.registrationDate + ttl;
|
|
1990
|
+
}
|
|
1991
|
+
if (client.clientName)
|
|
1992
|
+
out.client_name = client.clientName;
|
|
1993
|
+
if (client.clientUri)
|
|
1994
|
+
out.client_uri = client.clientUri;
|
|
1995
|
+
if (client.logoUri)
|
|
1996
|
+
out.logo_uri = client.logoUri;
|
|
1997
|
+
if (client.policyUri)
|
|
1998
|
+
out.policy_uri = client.policyUri;
|
|
1999
|
+
if (client.tosUri)
|
|
2000
|
+
out.tos_uri = client.tosUri;
|
|
2001
|
+
if (client.jwksUri)
|
|
2002
|
+
out.jwks_uri = client.jwksUri;
|
|
2003
|
+
if (client.contacts)
|
|
2004
|
+
out.contacts = client.contacts;
|
|
2005
|
+
if (client.scope !== undefined)
|
|
2006
|
+
out.scope = client.scope;
|
|
2007
|
+
return out;
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
// src/endpoints/revoke.ts
|
|
2011
|
+
async function handleRevoke(core, request) {
|
|
2012
|
+
const form = await parseFormBody(request);
|
|
2013
|
+
const creds = extractClientCredentials(request, form);
|
|
2014
|
+
const client = await core.authenticateClient(creds);
|
|
2015
|
+
const token = form.get("token");
|
|
2016
|
+
if (!token)
|
|
2017
|
+
throw new OAuthError("invalid_request", "Missing token");
|
|
2018
|
+
const hint = form.get("token_type_hint");
|
|
2019
|
+
if (hint !== undefined && hint !== "access_token" && hint !== "refresh_token") {
|
|
2020
|
+
throw new OAuthError("unsupported_token_type", `Unsupported token_type_hint "${hint}"`);
|
|
2021
|
+
}
|
|
2022
|
+
await core.revokeToken({ client, token, tokenTypeHint: hint });
|
|
2023
|
+
return new Response(null, { status: 200, headers: NO_STORE });
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
// src/endpoints/token.ts
|
|
2027
|
+
async function handleToken(core, request) {
|
|
2028
|
+
const form = await parseFormBody(request);
|
|
2029
|
+
const grantType = form.get("grant_type");
|
|
2030
|
+
const creds = extractClientCredentials(request, form);
|
|
2031
|
+
const client = await core.authenticateClient(creds);
|
|
2032
|
+
const resources = form.getAll("resource");
|
|
2033
|
+
if (resources.length > 1)
|
|
2034
|
+
throw new OAuthError("invalid_target", "Only a single resource parameter is supported");
|
|
2035
|
+
const resource = resources[0];
|
|
2036
|
+
switch (grantType) {
|
|
2037
|
+
case "authorization_code": {
|
|
2038
|
+
const code = form.get("code");
|
|
2039
|
+
if (!code)
|
|
2040
|
+
throw new OAuthError("invalid_request", "Missing code");
|
|
2041
|
+
const res = await core.exchangeAuthorizationCode({
|
|
2042
|
+
client,
|
|
2043
|
+
code,
|
|
2044
|
+
codeVerifier: form.get("code_verifier"),
|
|
2045
|
+
redirectUri: form.get("redirect_uri"),
|
|
2046
|
+
resource,
|
|
2047
|
+
requestedScope: form.get("scope")
|
|
2048
|
+
});
|
|
2049
|
+
return json(res, { headers: NO_STORE });
|
|
2050
|
+
}
|
|
2051
|
+
case "refresh_token": {
|
|
2052
|
+
const refreshToken = form.get("refresh_token");
|
|
2053
|
+
if (!refreshToken)
|
|
2054
|
+
throw new OAuthError("invalid_request", "Missing refresh_token");
|
|
2055
|
+
const res = await core.refreshAccessToken({
|
|
2056
|
+
client,
|
|
2057
|
+
refreshToken,
|
|
2058
|
+
requestedScope: form.get("scope"),
|
|
2059
|
+
resource
|
|
2060
|
+
});
|
|
2061
|
+
return json(res, { headers: NO_STORE });
|
|
2062
|
+
}
|
|
2063
|
+
case undefined:
|
|
2064
|
+
throw new OAuthError("invalid_request", "Missing grant_type");
|
|
2065
|
+
default:
|
|
2066
|
+
throw new OAuthError("unsupported_grant_type", `Unsupported grant_type "${grantType}"`);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
// src/plugin.ts
|
|
2071
|
+
function createHelpers(core) {
|
|
2072
|
+
return {
|
|
2073
|
+
core,
|
|
2074
|
+
parseAuthRequest: (url) => core.parseAuthRequest(url instanceof Request ? url.url : url),
|
|
2075
|
+
getAuthRequest: (id) => core.getAuthRequest(id),
|
|
2076
|
+
completeAuthorization: (o) => core.completeAuthorization(o),
|
|
2077
|
+
rejectAuthorization: (o) => core.rejectAuthorization(o),
|
|
2078
|
+
verifyAccessToken: (t, u) => core.verifyAccessToken(t, u),
|
|
2079
|
+
createClient: (i) => core.createClient(i),
|
|
2080
|
+
lookupClient: (id) => core.lookupClient(id),
|
|
2081
|
+
updateClient: (id, u) => core.updateClient(id, u),
|
|
2082
|
+
deleteClient: (id) => core.deleteClient(id),
|
|
2083
|
+
listClients: () => core.listClients(),
|
|
2084
|
+
listUserGrants: (u) => core.listUserGrants(u),
|
|
2085
|
+
listGrants: () => core.listGrants(),
|
|
2086
|
+
listClientGrants: (id) => core.listClientGrants(id),
|
|
2087
|
+
revokeGrant: (g, u) => core.revokeGrant(g, u)
|
|
2088
|
+
};
|
|
2089
|
+
}
|
|
2090
|
+
function oauthProvider(userConfig) {
|
|
2091
|
+
const config = resolveConfig(userConfig);
|
|
2092
|
+
const core = new OAuthProviderCore(config);
|
|
2093
|
+
const helpers = createHelpers(core);
|
|
2094
|
+
const basePath = config.issuerUrl.pathname.replace(/\/+$/, "");
|
|
2095
|
+
const p = (path) => `${basePath}${path}`;
|
|
2096
|
+
const cors = (req) => config.cors ? corsHeaders(req) : {};
|
|
2097
|
+
const withHeaders = (res, headers) => {
|
|
2098
|
+
for (const [k, v] of Object.entries(headers))
|
|
2099
|
+
if (!res.headers.has(k))
|
|
2100
|
+
res.headers.set(k, v);
|
|
2101
|
+
return res;
|
|
2102
|
+
};
|
|
2103
|
+
const rateLimited = async (endpoint, request, socketIp) => {
|
|
2104
|
+
const rl = config.rateLimit;
|
|
2105
|
+
const rule = rl?.rules[endpoint];
|
|
2106
|
+
if (!rl || !rule)
|
|
2107
|
+
return null;
|
|
2108
|
+
const ip = clientIpFrom(request, socketIp, rl.trustProxy);
|
|
2109
|
+
const key = rl.keyFor ? await rl.keyFor({ endpoint, request, ip }) : `${endpoint}:${ip ?? "unknown"}`;
|
|
2110
|
+
if (key === null)
|
|
2111
|
+
return null;
|
|
2112
|
+
const decision = await rl.limiter.hit(key, rule);
|
|
2113
|
+
if (decision.allowed)
|
|
2114
|
+
return null;
|
|
2115
|
+
config.hooks.onRateLimited?.({
|
|
2116
|
+
endpoint,
|
|
2117
|
+
key,
|
|
2118
|
+
retryAfterSeconds: decision.retryAfterSeconds,
|
|
2119
|
+
request
|
|
2120
|
+
});
|
|
2121
|
+
return new OAuthError("temporarily_unavailable", "Too many requests", {
|
|
2122
|
+
status: 429,
|
|
2123
|
+
headers: { "Retry-After": String(decision.retryAfterSeconds) }
|
|
2124
|
+
}).toResponse();
|
|
2125
|
+
};
|
|
2126
|
+
const run = async (request, fn, limit) => {
|
|
2127
|
+
const extra = cors(request);
|
|
2128
|
+
try {
|
|
2129
|
+
if (limit) {
|
|
2130
|
+
const blocked = await rateLimited(limit.endpoint, request, limit.ip);
|
|
2131
|
+
if (blocked)
|
|
2132
|
+
return withHeaders(blocked, extra);
|
|
2133
|
+
}
|
|
2134
|
+
return withHeaders(await fn(), extra);
|
|
2135
|
+
} catch (e) {
|
|
2136
|
+
if (e instanceof OAuthError) {
|
|
2137
|
+
config.hooks.onError?.({ code: e.code, description: e.message, status: e.status, request });
|
|
2138
|
+
return withHeaders(e.toResponse(), extra);
|
|
2139
|
+
}
|
|
2140
|
+
if (e instanceof AuthorizationError) {
|
|
2141
|
+
config.hooks.onError?.({
|
|
2142
|
+
code: e.code,
|
|
2143
|
+
description: e.message,
|
|
2144
|
+
status: e.redirectUri ? 302 : 400,
|
|
2145
|
+
request
|
|
2146
|
+
});
|
|
2147
|
+
return withHeaders(e.toResponse(), extra);
|
|
2148
|
+
}
|
|
2149
|
+
config.hooks.onError?.({
|
|
2150
|
+
code: "server_error",
|
|
2151
|
+
description: "Unexpected error",
|
|
2152
|
+
status: 500,
|
|
2153
|
+
request
|
|
2154
|
+
});
|
|
2155
|
+
console.error("[elysia-oauth-provider]", e);
|
|
2156
|
+
return withHeaders(new OAuthError("server_error", "Internal server error").toResponse(), extra);
|
|
2157
|
+
}
|
|
2158
|
+
};
|
|
2159
|
+
const hidden = { detail: { hide: true } };
|
|
2160
|
+
const rawBody = { ...hidden, parse: () => true };
|
|
2161
|
+
const preflight = (request) => new Response(null, { status: 204, headers: cors(request) });
|
|
2162
|
+
const publicUrlOf = (request) => {
|
|
2163
|
+
if (!config.publicOrigin)
|
|
2164
|
+
return request.url;
|
|
2165
|
+
const u = new URL(request.url);
|
|
2166
|
+
return `${config.publicOrigin}${u.pathname}${u.search}`;
|
|
2167
|
+
};
|
|
2168
|
+
const resourceMetadataUrlFor = (requestUrl) => {
|
|
2169
|
+
const path = config.resource ? new URL(config.resource).pathname.replace(/\/$/, "") : new URL(requestUrl).pathname;
|
|
2170
|
+
const origin = config.publicOrigin ?? config.issuerUrl.origin;
|
|
2171
|
+
return `${origin}/.well-known/oauth-protected-resource${path === "/" ? "" : path}`;
|
|
2172
|
+
};
|
|
2173
|
+
const app = new Elysia({ name: "@20baht/elysia-oauth-provider", seed: config.issuer }).decorate("oauthProvider", helpers).get("/.well-known/oauth-authorization-server", ({ request }) => run(request, async () => json(authorizationServerMetadata(core))), hidden).options("/.well-known/oauth-authorization-server", ({ request }) => preflight(request), hidden).get("/.well-known/oauth-protected-resource", ({ request }) => run(request, async () => json(protectedResourceMetadata(core, ""))), hidden).options("/.well-known/oauth-protected-resource", ({ request }) => preflight(request), hidden).get("/.well-known/oauth-protected-resource/*", ({ request, params }) => run(request, async () => json(protectedResourceMetadata(core, `/${params["*"]}`))), hidden).options("/.well-known/oauth-protected-resource/*", ({ request }) => preflight(request), hidden).get(p(config.paths.authorize), ({ request, server }) => run(request, () => handleAuthorize(core, request), {
|
|
2174
|
+
endpoint: "authorize",
|
|
2175
|
+
ip: server?.requestIP(request)?.address ?? null
|
|
2176
|
+
}), hidden).post(p(config.paths.token), ({ request, server }) => run(request, () => handleToken(core, request), {
|
|
2177
|
+
endpoint: "token",
|
|
2178
|
+
ip: server?.requestIP(request)?.address ?? null
|
|
2179
|
+
}), rawBody).get(p(config.paths.token), () => methodNotAllowed("POST"), hidden).options(p(config.paths.token), ({ request }) => preflight(request), hidden).post(p(config.paths.revoke), ({ request, server }) => run(request, () => handleRevoke(core, request), {
|
|
2180
|
+
endpoint: "revoke",
|
|
2181
|
+
ip: server?.requestIP(request)?.address ?? null
|
|
2182
|
+
}), rawBody).get(p(config.paths.revoke), () => methodNotAllowed("POST"), hidden).options(p(config.paths.revoke), ({ request }) => preflight(request), hidden);
|
|
2183
|
+
if (basePath !== "") {
|
|
2184
|
+
app.get(`/.well-known/oauth-authorization-server${basePath}`, ({ request }) => run(request, async () => json(authorizationServerMetadata(core))), hidden);
|
|
2185
|
+
}
|
|
2186
|
+
if (config.clientRegistration.enabled) {
|
|
2187
|
+
app.post(p(config.paths.register), ({ request, server }) => run(request, () => handleRegister(core, request), {
|
|
2188
|
+
endpoint: "register",
|
|
2189
|
+
ip: server?.requestIP(request)?.address ?? null
|
|
2190
|
+
}), rawBody).get(p(config.paths.register), () => methodNotAllowed("POST"), hidden).options(p(config.paths.register), ({ request }) => preflight(request), hidden);
|
|
2191
|
+
}
|
|
2192
|
+
if (core.jwtSigner) {
|
|
2193
|
+
app.get(p(config.paths.jwks), ({ request }) => run(request, async () => {
|
|
2194
|
+
const jwks = await (await core.jwtSigner).jwks();
|
|
2195
|
+
return json(jwks ?? { keys: [] }, {
|
|
2196
|
+
headers: { "Cache-Control": "public, max-age=300" }
|
|
2197
|
+
});
|
|
2198
|
+
}), hidden);
|
|
2199
|
+
}
|
|
2200
|
+
return app.macro({
|
|
2201
|
+
oauth: (options) => ({
|
|
2202
|
+
resolve: async ({ request, set, status }) => {
|
|
2203
|
+
const required = options === true ? [] : options.scopes ?? [];
|
|
2204
|
+
Object.assign(set.headers, cors(request));
|
|
2205
|
+
const requestUrl = publicUrlOf(request);
|
|
2206
|
+
const resourceMetadataUrl = resourceMetadataUrlFor(requestUrl);
|
|
2207
|
+
const scopeHint = config.resourceMetadata.scopesSupported ?? config.scopesSupported;
|
|
2208
|
+
const fail = (code, challenge, body) => {
|
|
2209
|
+
set.headers["WWW-Authenticate"] = challenge;
|
|
2210
|
+
Object.assign(set.headers, NO_STORE);
|
|
2211
|
+
return status(code, body ?? "");
|
|
2212
|
+
};
|
|
2213
|
+
const token = extractBearer(request.headers.get("Authorization"));
|
|
2214
|
+
if (!token)
|
|
2215
|
+
return fail(401, bearerChallenge({ resourceMetadataUrl, scope: scopeHint }));
|
|
2216
|
+
let info;
|
|
2217
|
+
try {
|
|
2218
|
+
info = await core.verifyAccessToken(token, requestUrl);
|
|
2219
|
+
} catch (e) {
|
|
2220
|
+
const description = e instanceof OAuthError ? e.message : "Invalid token";
|
|
2221
|
+
return fail(401, bearerChallenge({
|
|
2222
|
+
resourceMetadataUrl,
|
|
2223
|
+
error: "invalid_token",
|
|
2224
|
+
errorDescription: description,
|
|
2225
|
+
scope: scopeHint
|
|
2226
|
+
}), { error: "invalid_token", error_description: description });
|
|
2227
|
+
}
|
|
2228
|
+
if (!info) {
|
|
2229
|
+
return fail(401, bearerChallenge({ resourceMetadataUrl, error: "invalid_token", scope: scopeHint }), { error: "invalid_token", error_description: "The access token is invalid or expired" });
|
|
2230
|
+
}
|
|
2231
|
+
if (!isSubset(required, info.scopes)) {
|
|
2232
|
+
return fail(403, bearerChallenge({ resourceMetadataUrl, error: "insufficient_scope", scope: required }), {
|
|
2233
|
+
error: "insufficient_scope",
|
|
2234
|
+
error_description: `Requires scope: ${required.join(" ")}`
|
|
2235
|
+
});
|
|
2236
|
+
}
|
|
2237
|
+
const oauth = {
|
|
2238
|
+
userId: info.userId,
|
|
2239
|
+
clientId: info.clientId,
|
|
2240
|
+
grantId: info.grantId,
|
|
2241
|
+
scopes: info.scopes,
|
|
2242
|
+
props: info.props,
|
|
2243
|
+
expiresAt: info.expiresAt,
|
|
2244
|
+
audience: info.audience,
|
|
2245
|
+
token
|
|
2246
|
+
};
|
|
2247
|
+
return { oauth };
|
|
2248
|
+
}
|
|
2249
|
+
})
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
// src/storage/memory.ts
|
|
2253
|
+
class MemoryStorage {
|
|
2254
|
+
#map = new Map;
|
|
2255
|
+
#now;
|
|
2256
|
+
#timer;
|
|
2257
|
+
constructor(options = {}) {
|
|
2258
|
+
this.#now = options.now ?? Date.now;
|
|
2259
|
+
const interval = options.sweepIntervalMs ?? 60000;
|
|
2260
|
+
if (interval > 0) {
|
|
2261
|
+
this.#timer = setInterval(() => {
|
|
2262
|
+
this.sweep();
|
|
2263
|
+
}, interval);
|
|
2264
|
+
if (typeof this.#timer === "object" && "unref" in this.#timer)
|
|
2265
|
+
this.#timer.unref();
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
async get(key) {
|
|
2269
|
+
const entry = this.#map.get(key);
|
|
2270
|
+
if (!entry)
|
|
2271
|
+
return null;
|
|
2272
|
+
if (this.#isExpired(entry)) {
|
|
2273
|
+
this.#map.delete(key);
|
|
2274
|
+
return null;
|
|
2275
|
+
}
|
|
2276
|
+
return structuredClone(entry.value);
|
|
2277
|
+
}
|
|
2278
|
+
async set(key, value, opts) {
|
|
2279
|
+
const ttl = opts?.ttlSeconds;
|
|
2280
|
+
const expiresAt = ttl === undefined ? undefined : this.#now() + ttl * 1000;
|
|
2281
|
+
this.#map.set(key, { value: structuredClone(value), expiresAt });
|
|
2282
|
+
}
|
|
2283
|
+
async consume(key) {
|
|
2284
|
+
const entry = this.#map.get(key);
|
|
2285
|
+
this.#map.delete(key);
|
|
2286
|
+
if (!entry || this.#isExpired(entry))
|
|
2287
|
+
return null;
|
|
2288
|
+
return entry.value;
|
|
2289
|
+
}
|
|
2290
|
+
async compareAndSet(key, expectedVersion, value, opts) {
|
|
2291
|
+
if (!this.#holdsVersion(key, expectedVersion))
|
|
2292
|
+
return false;
|
|
2293
|
+
await this.set(key, value, opts);
|
|
2294
|
+
return true;
|
|
2295
|
+
}
|
|
2296
|
+
async compareAndDelete(key, expectedVersion) {
|
|
2297
|
+
if (!this.#holdsVersion(key, expectedVersion))
|
|
2298
|
+
return false;
|
|
2299
|
+
this.#map.delete(key);
|
|
2300
|
+
return true;
|
|
2301
|
+
}
|
|
2302
|
+
#holdsVersion(key, expectedVersion) {
|
|
2303
|
+
const entry = this.#map.get(key);
|
|
2304
|
+
if (!entry || this.#isExpired(entry))
|
|
2305
|
+
return false;
|
|
2306
|
+
return entry.value.version === expectedVersion;
|
|
2307
|
+
}
|
|
2308
|
+
async delete(key) {
|
|
2309
|
+
this.#map.delete(key);
|
|
2310
|
+
}
|
|
2311
|
+
async list(prefix) {
|
|
2312
|
+
const out = [];
|
|
2313
|
+
for (const [key, entry] of this.#map) {
|
|
2314
|
+
if (!key.startsWith(prefix))
|
|
2315
|
+
continue;
|
|
2316
|
+
if (this.#isExpired(entry)) {
|
|
2317
|
+
this.#map.delete(key);
|
|
2318
|
+
continue;
|
|
2319
|
+
}
|
|
2320
|
+
out.push(key);
|
|
2321
|
+
}
|
|
2322
|
+
return out;
|
|
2323
|
+
}
|
|
2324
|
+
sweep() {
|
|
2325
|
+
for (const [key, entry] of this.#map)
|
|
2326
|
+
if (this.#isExpired(entry))
|
|
2327
|
+
this.#map.delete(key);
|
|
2328
|
+
}
|
|
2329
|
+
get size() {
|
|
2330
|
+
return this.#map.size;
|
|
2331
|
+
}
|
|
2332
|
+
close() {
|
|
2333
|
+
if (this.#timer)
|
|
2334
|
+
clearInterval(this.#timer);
|
|
2335
|
+
this.#timer = undefined;
|
|
2336
|
+
}
|
|
2337
|
+
#isExpired(entry) {
|
|
2338
|
+
return entry.expiresAt !== undefined && entry.expiresAt <= this.#now();
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
export {
|
|
2342
|
+
verifyPkce,
|
|
2343
|
+
validateResourceUri,
|
|
2344
|
+
validateRedirectUriSyntax,
|
|
2345
|
+
keys as storageKeys,
|
|
2346
|
+
resourcesEqual,
|
|
2347
|
+
resolveConfig,
|
|
2348
|
+
redirectUriMatches,
|
|
2349
|
+
oauthProvider,
|
|
2350
|
+
normalizeResource,
|
|
2351
|
+
isValidScopeToken,
|
|
2352
|
+
isValidCodeVerifier,
|
|
2353
|
+
isValidCodeChallenge,
|
|
2354
|
+
extractBearer,
|
|
2355
|
+
escapeGlob,
|
|
2356
|
+
createJwtSigner,
|
|
2357
|
+
clientIpFrom,
|
|
2358
|
+
bearerChallenge,
|
|
2359
|
+
audienceCoversUrl,
|
|
2360
|
+
assertStorageContract,
|
|
2361
|
+
RedisStorage,
|
|
2362
|
+
RedisRateLimiter,
|
|
2363
|
+
REDIS_SCRIPTS,
|
|
2364
|
+
OAuthProviderCore,
|
|
2365
|
+
OAuthError,
|
|
2366
|
+
MemoryStorage,
|
|
2367
|
+
MemoryRateLimiter,
|
|
2368
|
+
KEY_PREFIX,
|
|
2369
|
+
DEFAULT_RATE_LIMITS,
|
|
2370
|
+
DEFAULT_PATHS,
|
|
2371
|
+
AuthorizationError,
|
|
2372
|
+
ACCESS_TOKEN_REGISTERED_CLAIMS
|
|
2373
|
+
};
|
|
2374
|
+
|
|
2375
|
+
//# debugId=0B68AA0C3773EF1664756E2164756E21
|
|
2376
|
+
//# sourceMappingURL=index.js.map
|