emulate 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,788 @@
1
+ import {
2
+ SignJWT,
3
+ exportJWK,
4
+ generateKeyPair
5
+ } from "./chunk-D6EKRYGP.js";
6
+ import "./chunk-TEPNEZ63.js";
7
+
8
+ // ../@emulators/microsoft/dist/index.js
9
+ import { randomUUID } from "crypto";
10
+ import { createHash, randomBytes } from "crypto";
11
+ import { readFileSync } from "fs";
12
+ import { fileURLToPath } from "url";
13
+ import { dirname, join } from "path";
14
+ import { timingSafeEqual } from "crypto";
15
+ function getMicrosoftStore(store) {
16
+ return {
17
+ users: store.collection("microsoft.users", ["oid", "email"]),
18
+ oauthClients: store.collection("microsoft.oauth_clients", ["client_id"])
19
+ };
20
+ }
21
+ var DEFAULT_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad";
22
+ function generateOid() {
23
+ return randomUUID();
24
+ }
25
+ function createErrorHandler(documentationUrl) {
26
+ return async (c, next) => {
27
+ if (documentationUrl) {
28
+ c.set("docsUrl", documentationUrl);
29
+ }
30
+ await next();
31
+ };
32
+ }
33
+ var errorHandler = createErrorHandler();
34
+ var isDebug = typeof process !== "undefined" && (process.env.DEBUG === "1" || process.env.DEBUG === "true" || process.env.EMULATE_DEBUG === "1");
35
+ function debug(label, ...args) {
36
+ if (isDebug) {
37
+ console.log(`[${label}]`, ...args);
38
+ }
39
+ }
40
+ var __dirname = dirname(fileURLToPath(import.meta.url));
41
+ var FONTS = {
42
+ "geist-sans.woff2": readFileSync(join(__dirname, "fonts", "geist-sans.woff2")),
43
+ "GeistPixel-Square.woff2": readFileSync(join(__dirname, "fonts", "GeistPixel-Square.woff2"))
44
+ };
45
+ function escapeHtml(s) {
46
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
47
+ }
48
+ function escapeAttr(s) {
49
+ return escapeHtml(s).replace(/'/g, "&#39;");
50
+ }
51
+ var CSS = `
52
+ @font-face{
53
+ font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;
54
+ src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');
55
+ }
56
+ @font-face{
57
+ font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;
58
+ src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');
59
+ }
60
+ *{box-sizing:border-box;margin:0;padding:0}
61
+ body{
62
+ font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;
63
+ background:#000;color:#33ff00;min-height:100vh;
64
+ -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;
65
+ }
66
+ .emu-bar{
67
+ border-bottom:1px solid #0a3300;padding:10px 20px;
68
+ display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;
69
+ }
70
+ .emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}
71
+ .emu-bar-links{margin-left:auto;display:flex;gap:16px;}
72
+ .emu-bar-links a{
73
+ color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;
74
+ }
75
+ .emu-bar-links a:hover{color:#33ff00;}
76
+ .emu-bar-links a .full{display:inline;}
77
+ .emu-bar-links a .short{display:none;}
78
+ @media(max-width:600px){
79
+ .emu-bar-links a .full{display:none;}
80
+ .emu-bar-links a .short{display:inline;}
81
+ }
82
+
83
+ .content{
84
+ display:flex;align-items:center;justify-content:center;
85
+ min-height:calc(100vh - 42px);padding:24px 16px;
86
+ }
87
+ .content-inner{width:100%;max-width:420px;}
88
+ .card-title{
89
+ font-family:'Geist Pixel',monospace;
90
+ font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;
91
+ }
92
+ .card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}
93
+ .powered-by{
94
+ position:fixed;bottom:0;left:0;right:0;
95
+ text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;
96
+ font-family:'Geist Pixel',monospace;
97
+ }
98
+ .powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}
99
+ .powered-by a:hover{color:#33ff00;}
100
+
101
+ .error-title{
102
+ font-family:'Geist Pixel',monospace;
103
+ color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;
104
+ }
105
+ .error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}
106
+ .error-card{text-align:center;}
107
+
108
+ .user-form{margin-bottom:8px;}
109
+ .user-form:last-of-type{margin-bottom:0;}
110
+ .user-btn{
111
+ width:100%;display:flex;align-items:center;gap:12px;
112
+ padding:10px 12px;border:1px solid #0a3300;border-radius:8px;
113
+ background:#000;color:inherit;cursor:pointer;text-align:left;
114
+ font:inherit;transition:border-color .15s;
115
+ }
116
+ .user-btn:hover{border-color:#33ff00;}
117
+ .avatar{
118
+ width:36px;height:36px;border-radius:50%;
119
+ background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;
120
+ display:flex;align-items:center;justify-content:center;flex-shrink:0;
121
+ font-family:'Geist Pixel',monospace;
122
+ }
123
+ .user-text{min-width:0;}
124
+ .user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}
125
+ .user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}
126
+ .user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}
127
+
128
+ .settings-layout{
129
+ max-width:920px;margin:0 auto;padding:28px 20px;
130
+ display:flex;gap:28px;
131
+ }
132
+ .settings-sidebar{width:200px;flex-shrink:0;}
133
+ .settings-sidebar a{
134
+ display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;
135
+ text-decoration:none;font-size:.8125rem;transition:color .15s;
136
+ }
137
+ .settings-sidebar a:hover{color:#33ff00;}
138
+ .settings-sidebar a.active{color:#33ff00;font-weight:600;}
139
+ .settings-main{flex:1;min-width:0;}
140
+
141
+ .s-card{
142
+ padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;
143
+ }
144
+ .s-card:last-child{border-bottom:none;}
145
+ .s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}
146
+ .s-icon{
147
+ width:42px;height:42px;border-radius:8px;
148
+ background:#0a3300;display:flex;align-items:center;justify-content:center;
149
+ font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;
150
+ font-family:'Geist Pixel',monospace;
151
+ }
152
+ .s-title{
153
+ font-family:'Geist Pixel',monospace;
154
+ font-size:1.25rem;font-weight:600;color:#33ff00;
155
+ }
156
+ .s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}
157
+ .section-heading{
158
+ font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;
159
+ display:flex;align-items:center;justify-content:space-between;
160
+ }
161
+ .perm-list{list-style:none;}
162
+ .perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}
163
+ .check{color:#33ff00;}
164
+ .org-row{
165
+ display:flex;align-items:center;gap:8px;padding:7px 0;
166
+ border-bottom:1px solid #0a3300;font-size:.8125rem;
167
+ }
168
+ .org-row:last-child{border-bottom:none;}
169
+ .org-icon{
170
+ width:22px;height:22px;border-radius:4px;background:#0a3300;
171
+ display:flex;align-items:center;justify-content:center;
172
+ font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;
173
+ font-family:'Geist Pixel',monospace;
174
+ }
175
+ .org-name{font-weight:600;color:#33ff00;}
176
+ .badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}
177
+ .badge-granted{background:#0a3300;color:#33ff00;}
178
+ .badge-denied{background:#1a0a0a;color:#ff4444;}
179
+ .badge-requested{background:#0a3300;color:#1a8c00;}
180
+ .btn-revoke{
181
+ display:inline-block;padding:5px 14px;border-radius:6px;
182
+ border:1px solid #0a3300;background:transparent;color:#ff4444;
183
+ font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;
184
+ }
185
+ .btn-revoke:hover{border-color:#ff4444;}
186
+ .info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}
187
+ .app-link{
188
+ display:flex;align-items:center;gap:12px;padding:12px;
189
+ border:1px solid #0a3300;border-radius:8px;background:#000;
190
+ text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;
191
+ }
192
+ .app-link:hover{border-color:#33ff00;}
193
+ .app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}
194
+ .app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}
195
+ .empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}
196
+ `;
197
+ var POWERED_BY = `<div class="powered-by">Powered by <a href="https://emulate.dev" target="_blank" rel="noopener">emulate</a></div>`;
198
+ function emuBar(service) {
199
+ const title = service ? `${escapeHtml(service)} Emulator` : "Emulator";
200
+ return `<div class="emu-bar">
201
+ <span class="emu-bar-title">${title}</span>
202
+ <nav class="emu-bar-links">
203
+ <a href="https://github.com/vercel-labs/emulate/issues" target="_blank" rel="noopener"><span class="full">Report Issue</span><span class="short">Report</span></a>
204
+ <a href="https://github.com/vercel-labs/emulate" target="_blank" rel="noopener"><span class="full">Source Code</span><span class="short">Source</span></a>
205
+ <a href="https://emulate.dev" target="_blank" rel="noopener"><span class="full">Learn More</span><span class="short">Learn</span></a>
206
+ </nav>
207
+ </div>`;
208
+ }
209
+ function head(title) {
210
+ return `<!DOCTYPE html>
211
+ <html lang="en">
212
+ <head>
213
+ <meta charset="utf-8"/>
214
+ <meta name="viewport" content="width=device-width,initial-scale=1"/>
215
+ <title>${escapeHtml(title)} | emulate</title>
216
+ <style>${CSS}</style>
217
+ </head>`;
218
+ }
219
+ function renderCardPage(title, subtitle, body, service) {
220
+ return `${head(title)}
221
+ <body>
222
+ ${emuBar(service)}
223
+ <div class="content">
224
+ <div class="content-inner">
225
+ <div class="card-title">${escapeHtml(title)}</div>
226
+ <div class="card-subtitle">${subtitle}</div>
227
+ ${body}
228
+ </div>
229
+ </div>
230
+ ${POWERED_BY}
231
+ </body></html>`;
232
+ }
233
+ function renderErrorPage(title, message, service) {
234
+ return `${head(title)}
235
+ <body>
236
+ ${emuBar(service)}
237
+ <div class="content">
238
+ <div class="content-inner error-card">
239
+ <div class="error-title">${escapeHtml(title)}</div>
240
+ <div class="error-msg">${escapeHtml(message)}</div>
241
+ </div>
242
+ </div>
243
+ ${POWERED_BY}
244
+ </body></html>`;
245
+ }
246
+ function renderUserButton(opts) {
247
+ const hiddens = Object.entries(opts.hiddenFields).map(([k, v]) => `<input type="hidden" name="${escapeAttr(k)}" value="${escapeAttr(v)}"/>`).join("");
248
+ const nameLine = opts.name ? `<div class="user-meta">${escapeHtml(opts.name)}</div>` : "";
249
+ const emailLine = opts.email ? `<div class="user-email">${escapeHtml(opts.email)}</div>` : "";
250
+ return `<form class="user-form" method="post" action="${escapeAttr(opts.formAction)}">
251
+ ${hiddens}
252
+ <button type="submit" class="user-btn">
253
+ <span class="avatar">${escapeHtml(opts.letter)}</span>
254
+ <span class="user-text">
255
+ <span class="user-login">${escapeHtml(opts.login)}</span>
256
+ ${nameLine}${emailLine}
257
+ </span>
258
+ </button>
259
+ </form>`;
260
+ }
261
+ function normalizeUri(uri) {
262
+ try {
263
+ const u = new URL(uri);
264
+ return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
265
+ } catch {
266
+ return uri.replace(/\/+$/, "").split("?")[0];
267
+ }
268
+ }
269
+ function matchesRedirectUri(incoming, registered) {
270
+ const normalized = normalizeUri(incoming);
271
+ return registered.some((r) => normalizeUri(r) === normalized);
272
+ }
273
+ function constantTimeSecretEqual(a, b) {
274
+ const bufA = Buffer.from(a, "utf-8");
275
+ const bufB = Buffer.from(b, "utf-8");
276
+ if (bufA.length !== bufB.length) return false;
277
+ return timingSafeEqual(bufA, bufB);
278
+ }
279
+ function bodyStr(v) {
280
+ if (typeof v === "string") return v;
281
+ if (Array.isArray(v) && typeof v[0] === "string") return v[0];
282
+ return "";
283
+ }
284
+ var keyPairPromise = generateKeyPair("RS256");
285
+ var KID = "emulate-microsoft-1";
286
+ var PENDING_CODE_TTL_MS = 10 * 60 * 1e3;
287
+ function getPendingCodes(store) {
288
+ let map = store.getData("microsoft.oauth.pendingCodes");
289
+ if (!map) {
290
+ map = /* @__PURE__ */ new Map();
291
+ store.setData("microsoft.oauth.pendingCodes", map);
292
+ }
293
+ return map;
294
+ }
295
+ function getRefreshTokens(store) {
296
+ let map = store.getData("microsoft.oauth.refreshTokens");
297
+ if (!map) {
298
+ map = /* @__PURE__ */ new Map();
299
+ store.setData("microsoft.oauth.refreshTokens", map);
300
+ }
301
+ return map;
302
+ }
303
+ function isPendingCodeExpired(p) {
304
+ return Date.now() - p.created_at > PENDING_CODE_TTL_MS;
305
+ }
306
+ var SERVICE_LABEL = "Microsoft";
307
+ async function createIdToken(user, clientId, nonce, baseUrl) {
308
+ const { privateKey } = await keyPairPromise;
309
+ const now = Math.floor(Date.now() / 1e3);
310
+ const builder = new SignJWT({
311
+ sub: user.oid,
312
+ email: user.email,
313
+ name: user.name,
314
+ given_name: user.given_name,
315
+ family_name: user.family_name,
316
+ preferred_username: user.preferred_username,
317
+ oid: user.oid,
318
+ tid: user.tenant_id,
319
+ ver: "2.0",
320
+ ...nonce ? { nonce } : {}
321
+ }).setProtectedHeader({ alg: "RS256", kid: KID, typ: "JWT" }).setIssuer(`${baseUrl}/${user.tenant_id}/v2.0`).setAudience(clientId).setIssuedAt(now).setExpirationTime("1h");
322
+ return builder.sign(privateKey);
323
+ }
324
+ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
325
+ const ms = getMicrosoftStore(store);
326
+ const oidcConfig = (tenantId) => ({
327
+ issuer: `${baseUrl}/${tenantId}/v2.0`,
328
+ authorization_endpoint: `${baseUrl}/oauth2/v2.0/authorize`,
329
+ token_endpoint: `${baseUrl}/oauth2/v2.0/token`,
330
+ userinfo_endpoint: `${baseUrl}/oidc/userinfo`,
331
+ end_session_endpoint: `${baseUrl}/oauth2/v2.0/logout`,
332
+ jwks_uri: `${baseUrl}/discovery/v2.0/keys`,
333
+ response_types_supported: ["code"],
334
+ response_modes_supported: ["query", "fragment", "form_post"],
335
+ subject_types_supported: ["pairwise"],
336
+ id_token_signing_alg_values_supported: ["RS256"],
337
+ scopes_supported: ["openid", "email", "profile", "offline_access", "User.Read", ".default"],
338
+ grant_types_supported: ["authorization_code", "refresh_token", "client_credentials"],
339
+ token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic"],
340
+ claims_supported: [
341
+ "sub",
342
+ "iss",
343
+ "aud",
344
+ "exp",
345
+ "iat",
346
+ "nonce",
347
+ "name",
348
+ "email",
349
+ "given_name",
350
+ "family_name",
351
+ "preferred_username",
352
+ "oid",
353
+ "tid",
354
+ "ver"
355
+ ],
356
+ code_challenge_methods_supported: ["plain", "S256"]
357
+ });
358
+ app.get("/.well-known/openid-configuration", (c) => {
359
+ return c.json(oidcConfig(DEFAULT_TENANT_ID));
360
+ });
361
+ app.get("/:tenant/v2.0/.well-known/openid-configuration", (c) => {
362
+ const tenant = c.req.param("tenant");
363
+ return c.json(oidcConfig(tenant === "common" || tenant === "organizations" || tenant === "consumers" ? DEFAULT_TENANT_ID : tenant));
364
+ });
365
+ app.get("/discovery/v2.0/keys", async (c) => {
366
+ const { publicKey } = await keyPairPromise;
367
+ const jwk = await exportJWK(publicKey);
368
+ return c.json({
369
+ keys: [{
370
+ ...jwk,
371
+ kid: KID,
372
+ use: "sig",
373
+ alg: "RS256"
374
+ }]
375
+ });
376
+ });
377
+ app.get("/oauth2/v2.0/authorize", (c) => {
378
+ const client_id = c.req.query("client_id") ?? "";
379
+ const redirect_uri = c.req.query("redirect_uri") ?? "";
380
+ const scope = c.req.query("scope") ?? "";
381
+ const state = c.req.query("state") ?? "";
382
+ const nonce = c.req.query("nonce") ?? "";
383
+ const response_mode = c.req.query("response_mode") ?? "query";
384
+ const code_challenge = c.req.query("code_challenge") ?? "";
385
+ const code_challenge_method = c.req.query("code_challenge_method") ?? "";
386
+ const clientsConfigured = ms.oauthClients.all().length > 0;
387
+ let clientName = "";
388
+ if (clientsConfigured) {
389
+ const client = ms.oauthClients.findOneBy("client_id", client_id);
390
+ if (!client) {
391
+ return c.html(
392
+ renderErrorPage("Application not found", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),
393
+ 400
394
+ );
395
+ }
396
+ if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {
397
+ return c.html(
398
+ renderErrorPage("Redirect URI mismatch", "The redirect_uri is not registered for this application.", SERVICE_LABEL),
399
+ 400
400
+ );
401
+ }
402
+ clientName = client.name;
403
+ }
404
+ const subtitleText = clientName ? `Sign in to <strong>${escapeHtml(clientName)}</strong> with your Microsoft account.` : "Choose a seeded user to continue.";
405
+ const users = ms.users.all();
406
+ const userButtons = users.map((user) => {
407
+ return renderUserButton({
408
+ letter: (user.email[0] ?? "?").toUpperCase(),
409
+ login: user.email,
410
+ name: user.name,
411
+ email: user.email,
412
+ formAction: "/oauth2/v2.0/authorize/callback",
413
+ hiddenFields: {
414
+ email: user.email,
415
+ redirect_uri,
416
+ scope,
417
+ state,
418
+ nonce,
419
+ client_id,
420
+ response_mode,
421
+ code_challenge,
422
+ code_challenge_method
423
+ }
424
+ });
425
+ }).join("\n");
426
+ const body = users.length === 0 ? '<p class="empty">No users in the emulator store.</p>' : userButtons;
427
+ return c.html(renderCardPage("Sign in with Microsoft", subtitleText, body, SERVICE_LABEL));
428
+ });
429
+ app.post("/oauth2/v2.0/authorize/callback", async (c) => {
430
+ const body = await c.req.parseBody();
431
+ const email = bodyStr(body.email);
432
+ const redirect_uri = bodyStr(body.redirect_uri);
433
+ const scope = bodyStr(body.scope);
434
+ const state = bodyStr(body.state);
435
+ const client_id = bodyStr(body.client_id);
436
+ const nonce = bodyStr(body.nonce);
437
+ const response_mode = bodyStr(body.response_mode) || "query";
438
+ const code_challenge = bodyStr(body.code_challenge);
439
+ const code_challenge_method = bodyStr(body.code_challenge_method);
440
+ const clientsConfigured = ms.oauthClients.all().length > 0;
441
+ if (clientsConfigured) {
442
+ const client = ms.oauthClients.findOneBy("client_id", client_id);
443
+ if (!client) {
444
+ return c.html(
445
+ renderErrorPage("Application not found", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),
446
+ 400
447
+ );
448
+ }
449
+ if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {
450
+ return c.html(
451
+ renderErrorPage("Redirect URI mismatch", "The redirect_uri is not registered for this application.", SERVICE_LABEL),
452
+ 400
453
+ );
454
+ }
455
+ }
456
+ const code = randomBytes(20).toString("hex");
457
+ getPendingCodes(store).set(code, {
458
+ email,
459
+ scope,
460
+ redirectUri: redirect_uri,
461
+ clientId: client_id,
462
+ nonce: nonce || null,
463
+ codeChallenge: code_challenge || null,
464
+ codeChallengeMethod: code_challenge_method || null,
465
+ created_at: Date.now()
466
+ });
467
+ debug("microsoft.oauth", `[Microsoft callback] code=${code.slice(0, 8)}... email=${email}`);
468
+ if (response_mode === "form_post") {
469
+ const html = `<!DOCTYPE html>
470
+ <html>
471
+ <head><title>Submit</title></head>
472
+ <body onload="document.forms[0].submit()">
473
+ <form method="POST" action="${escapeAttr(redirect_uri)}">
474
+ <input type="hidden" name="code" value="${escapeAttr(code)}" />
475
+ <input type="hidden" name="state" value="${escapeAttr(state)}" />
476
+ </form>
477
+ </body>
478
+ </html>`;
479
+ return c.html(html);
480
+ }
481
+ const url = new URL(redirect_uri);
482
+ url.searchParams.set("code", code);
483
+ if (state) url.searchParams.set("state", state);
484
+ return c.redirect(url.toString(), 302);
485
+ });
486
+ app.post("/oauth2/v2.0/token", async (c) => {
487
+ const contentType = c.req.header("Content-Type") ?? "";
488
+ const rawText = await c.req.text();
489
+ let body;
490
+ if (contentType.includes("application/json")) {
491
+ try {
492
+ body = JSON.parse(rawText);
493
+ } catch {
494
+ body = {};
495
+ }
496
+ } else {
497
+ body = Object.fromEntries(new URLSearchParams(rawText));
498
+ }
499
+ const grant_type = typeof body.grant_type === "string" ? body.grant_type : "";
500
+ const code = typeof body.code === "string" ? body.code : "";
501
+ let client_id = typeof body.client_id === "string" ? body.client_id : "";
502
+ let client_secret = typeof body.client_secret === "string" ? body.client_secret : "";
503
+ const refresh_token = typeof body.refresh_token === "string" ? body.refresh_token : "";
504
+ const redirect_uri = typeof body.redirect_uri === "string" ? body.redirect_uri : "";
505
+ const code_verifier = typeof body.code_verifier === "string" ? body.code_verifier : void 0;
506
+ const scope = typeof body.scope === "string" ? body.scope : "";
507
+ const authHeader = c.req.header("Authorization") ?? "";
508
+ if (authHeader.startsWith("Basic ")) {
509
+ const decoded = Buffer.from(authHeader.slice(6), "base64").toString();
510
+ const sep = decoded.indexOf(":");
511
+ if (sep !== -1) {
512
+ const headerId = decodeURIComponent(decoded.slice(0, sep));
513
+ const headerSecret = decodeURIComponent(decoded.slice(sep + 1));
514
+ if (!client_id) client_id = headerId;
515
+ if (!client_secret) client_secret = headerSecret;
516
+ }
517
+ }
518
+ if (grant_type === "authorization_code") {
519
+ const clientsConfigured = ms.oauthClients.all().length > 0;
520
+ if (clientsConfigured) {
521
+ const client = ms.oauthClients.findOneBy("client_id", client_id);
522
+ if (!client) {
523
+ return c.json({ error: "invalid_client", error_description: "The client_id is incorrect." }, 401);
524
+ }
525
+ if (!constantTimeSecretEqual(client_secret, client.client_secret)) {
526
+ return c.json({ error: "invalid_client", error_description: "The client_secret is incorrect." }, 401);
527
+ }
528
+ }
529
+ const pendingMap = getPendingCodes(store);
530
+ const pending = pendingMap.get(code);
531
+ if (!pending) {
532
+ return c.json({ error: "invalid_grant", error_description: "The code is incorrect or expired." }, 400);
533
+ }
534
+ if (isPendingCodeExpired(pending)) {
535
+ pendingMap.delete(code);
536
+ return c.json({ error: "invalid_grant", error_description: "The code is incorrect or expired." }, 400);
537
+ }
538
+ if (pending.redirectUri && redirect_uri && pending.redirectUri !== redirect_uri) {
539
+ pendingMap.delete(code);
540
+ return c.json({ error: "invalid_grant", error_description: "The redirect_uri does not match the one used in the authorization request." }, 400);
541
+ }
542
+ if (pending.codeChallenge !== null) {
543
+ if (code_verifier === void 0) {
544
+ return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
545
+ }
546
+ const method = (pending.codeChallengeMethod ?? "plain").toLowerCase();
547
+ if (method === "s256") {
548
+ const expected = createHash("sha256").update(code_verifier).digest("base64url");
549
+ if (expected !== pending.codeChallenge) {
550
+ return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
551
+ }
552
+ } else if (method === "plain") {
553
+ if (code_verifier !== pending.codeChallenge) {
554
+ return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
555
+ }
556
+ } else {
557
+ return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
558
+ }
559
+ }
560
+ pendingMap.delete(code);
561
+ const user = ms.users.findOneBy("email", pending.email);
562
+ if (!user) {
563
+ return c.json({ error: "invalid_grant", error_description: "User not found." }, 400);
564
+ }
565
+ const accessToken = "microsoft_" + randomBytes(20).toString("base64url");
566
+ const refreshToken = "r_microsoft_" + randomBytes(20).toString("base64url");
567
+ const scopes = pending.scope ? pending.scope.split(/\s+/).filter(Boolean) : [];
568
+ if (tokenMap) {
569
+ tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });
570
+ }
571
+ getRefreshTokens(store).set(refreshToken, {
572
+ email: user.email,
573
+ clientId: pending.clientId,
574
+ scope: pending.scope,
575
+ nonce: pending.nonce
576
+ });
577
+ const idToken = await createIdToken(user, pending.clientId, pending.nonce, baseUrl);
578
+ debug("microsoft.oauth", `[Microsoft token] issued token for ${user.email}`);
579
+ return c.json({
580
+ access_token: accessToken,
581
+ token_type: "Bearer",
582
+ expires_in: 3600,
583
+ scope: pending.scope || "openid email profile",
584
+ refresh_token: refreshToken,
585
+ id_token: idToken
586
+ });
587
+ }
588
+ if (grant_type === "refresh_token") {
589
+ const refreshMap = getRefreshTokens(store);
590
+ const stored = refreshMap.get(refresh_token);
591
+ if (!stored) {
592
+ return c.json({ error: "invalid_grant", error_description: "The refresh_token is invalid." }, 400);
593
+ }
594
+ const user = ms.users.findOneBy("email", stored.email);
595
+ if (!user) {
596
+ return c.json({ error: "invalid_grant", error_description: "User not found." }, 400);
597
+ }
598
+ const accessToken = "microsoft_" + randomBytes(20).toString("base64url");
599
+ const newRefreshToken = "r_microsoft_" + randomBytes(20).toString("base64url");
600
+ const scopes = stored.scope ? stored.scope.split(/\s+/).filter(Boolean) : [];
601
+ if (tokenMap) {
602
+ tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });
603
+ }
604
+ refreshMap.delete(refresh_token);
605
+ refreshMap.set(newRefreshToken, {
606
+ email: stored.email,
607
+ clientId: stored.clientId,
608
+ scope: stored.scope,
609
+ nonce: stored.nonce
610
+ });
611
+ const idToken = await createIdToken(user, stored.clientId || client_id, stored.nonce, baseUrl);
612
+ debug("microsoft.oauth", `[Microsoft refresh] issued new token for ${user.email}`);
613
+ return c.json({
614
+ access_token: accessToken,
615
+ token_type: "Bearer",
616
+ expires_in: 3600,
617
+ scope: stored.scope || "openid email profile",
618
+ refresh_token: newRefreshToken,
619
+ id_token: idToken
620
+ });
621
+ }
622
+ if (grant_type === "client_credentials") {
623
+ const clientsConfigured = ms.oauthClients.all().length > 0;
624
+ if (clientsConfigured) {
625
+ const client = ms.oauthClients.findOneBy("client_id", client_id);
626
+ if (!client) {
627
+ return c.json({ error: "invalid_client", error_description: "The client_id is incorrect." }, 401);
628
+ }
629
+ if (!constantTimeSecretEqual(client_secret, client.client_secret)) {
630
+ return c.json({ error: "invalid_client", error_description: "The client_secret is incorrect." }, 401);
631
+ }
632
+ }
633
+ const accessToken = "microsoft_" + randomBytes(20).toString("base64url");
634
+ const scopes = scope ? scope.split(/\s+/).filter(Boolean) : [".default"];
635
+ if (tokenMap) {
636
+ tokenMap.set(accessToken, { login: client_id, id: 0, scopes });
637
+ }
638
+ debug("microsoft.oauth", `[Microsoft client_credentials] issued token for ${client_id}`);
639
+ return c.json({
640
+ access_token: accessToken,
641
+ token_type: "Bearer",
642
+ expires_in: 3600,
643
+ scope: scope || ".default"
644
+ });
645
+ }
646
+ return c.json({ error: "unsupported_grant_type", error_description: "Only authorization_code, refresh_token, and client_credentials are supported." }, 400);
647
+ });
648
+ app.get("/oidc/userinfo", (c) => {
649
+ const authUser = c.get("authUser");
650
+ if (!authUser) {
651
+ return c.json({ error: "invalid_token", error_description: "Authentication required." }, 401);
652
+ }
653
+ const user = ms.users.findOneBy("email", authUser.login);
654
+ if (!user) {
655
+ return c.json({ error: "invalid_token", error_description: "User not found." }, 401);
656
+ }
657
+ return c.json({
658
+ sub: user.oid,
659
+ email: user.email,
660
+ name: user.name,
661
+ given_name: user.given_name,
662
+ family_name: user.family_name,
663
+ preferred_username: user.preferred_username
664
+ });
665
+ });
666
+ app.get("/v1.0/me", (c) => {
667
+ const authUser = c.get("authUser");
668
+ if (!authUser) {
669
+ return c.json({ error: { code: "InvalidAuthenticationToken", message: "Authentication required." } }, 401);
670
+ }
671
+ const user = ms.users.findOneBy("email", authUser.login);
672
+ if (!user) {
673
+ return c.json({ error: { code: "Request_ResourceNotFound", message: "User not found." } }, 404);
674
+ }
675
+ return c.json({
676
+ "@odata.context": `${baseUrl}/v1.0/$metadata#users/$entity`,
677
+ id: user.oid,
678
+ displayName: user.name,
679
+ givenName: user.given_name,
680
+ surname: user.family_name,
681
+ mail: user.email,
682
+ userPrincipalName: user.preferred_username
683
+ });
684
+ });
685
+ app.get("/oauth2/v2.0/logout", (c) => {
686
+ const post_logout_redirect_uri = c.req.query("post_logout_redirect_uri");
687
+ if (post_logout_redirect_uri) {
688
+ const allClients = ms.oauthClients.all();
689
+ if (allClients.length > 0) {
690
+ const allowed = allClients.some(
691
+ (client) => matchesRedirectUri(post_logout_redirect_uri, client.redirect_uris)
692
+ );
693
+ if (!allowed) {
694
+ return c.text("Invalid post_logout_redirect_uri", 400);
695
+ }
696
+ }
697
+ return c.redirect(post_logout_redirect_uri, 302);
698
+ }
699
+ return c.text("Logged out", 200);
700
+ });
701
+ app.post("/oauth2/v2.0/revoke", async (c) => {
702
+ const contentType = c.req.header("Content-Type") ?? "";
703
+ const rawText = await c.req.text();
704
+ let token;
705
+ if (contentType.includes("application/json")) {
706
+ try {
707
+ const parsed = JSON.parse(rawText);
708
+ token = typeof parsed.token === "string" ? parsed.token : "";
709
+ } catch {
710
+ token = "";
711
+ }
712
+ } else {
713
+ const params = new URLSearchParams(rawText);
714
+ token = params.get("token") ?? "";
715
+ }
716
+ if (token && tokenMap) {
717
+ tokenMap.delete(token);
718
+ }
719
+ if (token) {
720
+ getRefreshTokens(store).delete(token);
721
+ }
722
+ return c.body(null, 200);
723
+ });
724
+ }
725
+ function seedDefaults(store, _baseUrl) {
726
+ const ms = getMicrosoftStore(store);
727
+ ms.users.insert({
728
+ oid: generateOid(),
729
+ email: "testuser@outlook.com",
730
+ name: "Test User",
731
+ given_name: "Test",
732
+ family_name: "User",
733
+ email_verified: true,
734
+ tenant_id: DEFAULT_TENANT_ID,
735
+ preferred_username: "testuser@outlook.com"
736
+ });
737
+ }
738
+ function seedFromConfig(store, _baseUrl, config) {
739
+ const ms = getMicrosoftStore(store);
740
+ if (config.users) {
741
+ for (const u of config.users) {
742
+ const existing = ms.users.findOneBy("email", u.email);
743
+ if (existing) continue;
744
+ const nameParts = (u.name ?? "").split(/\s+/);
745
+ ms.users.insert({
746
+ oid: generateOid(),
747
+ email: u.email,
748
+ name: u.name ?? u.email.split("@")[0],
749
+ given_name: u.given_name ?? nameParts[0] ?? "",
750
+ family_name: u.family_name ?? nameParts.slice(1).join(" ") ?? "",
751
+ email_verified: true,
752
+ tenant_id: u.tenant_id ?? DEFAULT_TENANT_ID,
753
+ preferred_username: u.email
754
+ });
755
+ }
756
+ }
757
+ if (config.oauth_clients) {
758
+ for (const client of config.oauth_clients) {
759
+ const existing = ms.oauthClients.findOneBy("client_id", client.client_id);
760
+ if (existing) continue;
761
+ ms.oauthClients.insert({
762
+ client_id: client.client_id,
763
+ client_secret: client.client_secret,
764
+ name: client.name,
765
+ redirect_uris: client.redirect_uris,
766
+ tenant_id: client.tenant_id ?? DEFAULT_TENANT_ID
767
+ });
768
+ }
769
+ }
770
+ }
771
+ var microsoftPlugin = {
772
+ name: "microsoft",
773
+ register(app, store, webhooks, baseUrl, tokenMap) {
774
+ const ctx = { app, store, webhooks, baseUrl, tokenMap };
775
+ oauthRoutes(ctx);
776
+ },
777
+ seed(store, baseUrl) {
778
+ seedDefaults(store, baseUrl);
779
+ }
780
+ };
781
+ var index_default = microsoftPlugin;
782
+ export {
783
+ index_default as default,
784
+ getMicrosoftStore,
785
+ microsoftPlugin,
786
+ seedFromConfig
787
+ };
788
+ //# sourceMappingURL=dist-DSSB3LYT.js.map