@emulators/microsoft 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/fonts/GeistPixel-Square.woff2 +0 -0
- package/dist/fonts/geist-sans.woff2 +0 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +795 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding any notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. Please also get an informed
|
|
186
|
+
understanding of your current status in the "Work made for hire"
|
|
187
|
+
or other employer IP clauses in your jurisdiction and contracts
|
|
188
|
+
before applying.
|
|
189
|
+
|
|
190
|
+
Copyright 2025 Chris Tate
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
Binary file
|
|
Binary file
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Entity, Collection, Store, ServicePlugin } from '@emulators/core';
|
|
2
|
+
|
|
3
|
+
interface MicrosoftUser extends Entity {
|
|
4
|
+
/** Object ID (oid) — unique per-tenant user identifier */
|
|
5
|
+
oid: string;
|
|
6
|
+
email: string;
|
|
7
|
+
name: string;
|
|
8
|
+
given_name: string;
|
|
9
|
+
family_name: string;
|
|
10
|
+
email_verified: boolean;
|
|
11
|
+
/** Microsoft tenant ID */
|
|
12
|
+
tenant_id: string;
|
|
13
|
+
/** User principal name (usually email) */
|
|
14
|
+
preferred_username: string;
|
|
15
|
+
}
|
|
16
|
+
interface MicrosoftOAuthClient extends Entity {
|
|
17
|
+
client_id: string;
|
|
18
|
+
client_secret: string;
|
|
19
|
+
name: string;
|
|
20
|
+
redirect_uris: string[];
|
|
21
|
+
/** Tenant ID this app is registered in */
|
|
22
|
+
tenant_id: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface MicrosoftStore {
|
|
26
|
+
users: Collection<MicrosoftUser>;
|
|
27
|
+
oauthClients: Collection<MicrosoftOAuthClient>;
|
|
28
|
+
}
|
|
29
|
+
declare function getMicrosoftStore(store: Store): MicrosoftStore;
|
|
30
|
+
|
|
31
|
+
interface MicrosoftSeedConfig {
|
|
32
|
+
users?: Array<{
|
|
33
|
+
email: string;
|
|
34
|
+
name?: string;
|
|
35
|
+
given_name?: string;
|
|
36
|
+
family_name?: string;
|
|
37
|
+
tenant_id?: string;
|
|
38
|
+
}>;
|
|
39
|
+
oauth_clients?: Array<{
|
|
40
|
+
client_id: string;
|
|
41
|
+
client_secret: string;
|
|
42
|
+
name: string;
|
|
43
|
+
redirect_uris: string[];
|
|
44
|
+
tenant_id?: string;
|
|
45
|
+
}>;
|
|
46
|
+
}
|
|
47
|
+
declare function seedFromConfig(store: Store, _baseUrl: string, config: MicrosoftSeedConfig): void;
|
|
48
|
+
declare const microsoftPlugin: ServicePlugin;
|
|
49
|
+
|
|
50
|
+
export { type MicrosoftOAuthClient, type MicrosoftSeedConfig, type MicrosoftStore, type MicrosoftUser, microsoftPlugin as default, getMicrosoftStore, microsoftPlugin, seedFromConfig };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,795 @@
|
|
|
1
|
+
// src/store.ts
|
|
2
|
+
function getMicrosoftStore(store) {
|
|
3
|
+
return {
|
|
4
|
+
users: store.collection("microsoft.users", ["oid", "email"]),
|
|
5
|
+
oauthClients: store.collection("microsoft.oauth_clients", ["client_id"])
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// src/helpers.ts
|
|
10
|
+
import { randomUUID } from "crypto";
|
|
11
|
+
var DEFAULT_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad";
|
|
12
|
+
function generateOid() {
|
|
13
|
+
return randomUUID();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/routes/oauth.ts
|
|
17
|
+
import { createHash, randomBytes } from "crypto";
|
|
18
|
+
import { SignJWT, exportJWK, generateKeyPair } from "jose";
|
|
19
|
+
|
|
20
|
+
// ../core/dist/index.js
|
|
21
|
+
import { Hono } from "hono";
|
|
22
|
+
import { cors } from "hono/cors";
|
|
23
|
+
import { jwtVerify, importPKCS8 } from "jose";
|
|
24
|
+
import { readFileSync } from "fs";
|
|
25
|
+
import { fileURLToPath } from "url";
|
|
26
|
+
import { dirname, join } from "path";
|
|
27
|
+
import { timingSafeEqual } from "crypto";
|
|
28
|
+
function createErrorHandler(documentationUrl) {
|
|
29
|
+
return async (c, next) => {
|
|
30
|
+
if (documentationUrl) {
|
|
31
|
+
c.set("docsUrl", documentationUrl);
|
|
32
|
+
}
|
|
33
|
+
await next();
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
var errorHandler = createErrorHandler();
|
|
37
|
+
var isDebug = typeof process !== "undefined" && (process.env.DEBUG === "1" || process.env.DEBUG === "true" || process.env.EMULATE_DEBUG === "1");
|
|
38
|
+
function debug(label, ...args) {
|
|
39
|
+
if (isDebug) {
|
|
40
|
+
console.log(`[${label}]`, ...args);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
44
|
+
var FONTS = {
|
|
45
|
+
"geist-sans.woff2": readFileSync(join(__dirname, "fonts", "geist-sans.woff2")),
|
|
46
|
+
"GeistPixel-Square.woff2": readFileSync(join(__dirname, "fonts", "GeistPixel-Square.woff2"))
|
|
47
|
+
};
|
|
48
|
+
function escapeHtml(s) {
|
|
49
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
50
|
+
}
|
|
51
|
+
function escapeAttr(s) {
|
|
52
|
+
return escapeHtml(s).replace(/'/g, "'");
|
|
53
|
+
}
|
|
54
|
+
var CSS = `
|
|
55
|
+
@font-face{
|
|
56
|
+
font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;
|
|
57
|
+
src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');
|
|
58
|
+
}
|
|
59
|
+
@font-face{
|
|
60
|
+
font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;
|
|
61
|
+
src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');
|
|
62
|
+
}
|
|
63
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
64
|
+
body{
|
|
65
|
+
font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;
|
|
66
|
+
background:#000;color:#33ff00;min-height:100vh;
|
|
67
|
+
-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;
|
|
68
|
+
}
|
|
69
|
+
.emu-bar{
|
|
70
|
+
border-bottom:1px solid #0a3300;padding:10px 20px;
|
|
71
|
+
display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;
|
|
72
|
+
}
|
|
73
|
+
.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}
|
|
74
|
+
.emu-bar-links{margin-left:auto;display:flex;gap:16px;}
|
|
75
|
+
.emu-bar-links a{
|
|
76
|
+
color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;
|
|
77
|
+
}
|
|
78
|
+
.emu-bar-links a:hover{color:#33ff00;}
|
|
79
|
+
.emu-bar-links a .full{display:inline;}
|
|
80
|
+
.emu-bar-links a .short{display:none;}
|
|
81
|
+
@media(max-width:600px){
|
|
82
|
+
.emu-bar-links a .full{display:none;}
|
|
83
|
+
.emu-bar-links a .short{display:inline;}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
.content{
|
|
87
|
+
display:flex;align-items:center;justify-content:center;
|
|
88
|
+
min-height:calc(100vh - 42px);padding:24px 16px;
|
|
89
|
+
}
|
|
90
|
+
.content-inner{width:100%;max-width:420px;}
|
|
91
|
+
.card-title{
|
|
92
|
+
font-family:'Geist Pixel',monospace;
|
|
93
|
+
font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;
|
|
94
|
+
}
|
|
95
|
+
.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}
|
|
96
|
+
.powered-by{
|
|
97
|
+
position:fixed;bottom:0;left:0;right:0;
|
|
98
|
+
text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;
|
|
99
|
+
font-family:'Geist Pixel',monospace;
|
|
100
|
+
}
|
|
101
|
+
.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}
|
|
102
|
+
.powered-by a:hover{color:#33ff00;}
|
|
103
|
+
|
|
104
|
+
.error-title{
|
|
105
|
+
font-family:'Geist Pixel',monospace;
|
|
106
|
+
color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;
|
|
107
|
+
}
|
|
108
|
+
.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}
|
|
109
|
+
.error-card{text-align:center;}
|
|
110
|
+
|
|
111
|
+
.user-form{margin-bottom:8px;}
|
|
112
|
+
.user-form:last-of-type{margin-bottom:0;}
|
|
113
|
+
.user-btn{
|
|
114
|
+
width:100%;display:flex;align-items:center;gap:12px;
|
|
115
|
+
padding:10px 12px;border:1px solid #0a3300;border-radius:8px;
|
|
116
|
+
background:#000;color:inherit;cursor:pointer;text-align:left;
|
|
117
|
+
font:inherit;transition:border-color .15s;
|
|
118
|
+
}
|
|
119
|
+
.user-btn:hover{border-color:#33ff00;}
|
|
120
|
+
.avatar{
|
|
121
|
+
width:36px;height:36px;border-radius:50%;
|
|
122
|
+
background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;
|
|
123
|
+
display:flex;align-items:center;justify-content:center;flex-shrink:0;
|
|
124
|
+
font-family:'Geist Pixel',monospace;
|
|
125
|
+
}
|
|
126
|
+
.user-text{min-width:0;}
|
|
127
|
+
.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}
|
|
128
|
+
.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}
|
|
129
|
+
.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}
|
|
130
|
+
|
|
131
|
+
.settings-layout{
|
|
132
|
+
max-width:920px;margin:0 auto;padding:28px 20px;
|
|
133
|
+
display:flex;gap:28px;
|
|
134
|
+
}
|
|
135
|
+
.settings-sidebar{width:200px;flex-shrink:0;}
|
|
136
|
+
.settings-sidebar a{
|
|
137
|
+
display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;
|
|
138
|
+
text-decoration:none;font-size:.8125rem;transition:color .15s;
|
|
139
|
+
}
|
|
140
|
+
.settings-sidebar a:hover{color:#33ff00;}
|
|
141
|
+
.settings-sidebar a.active{color:#33ff00;font-weight:600;}
|
|
142
|
+
.settings-main{flex:1;min-width:0;}
|
|
143
|
+
|
|
144
|
+
.s-card{
|
|
145
|
+
padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;
|
|
146
|
+
}
|
|
147
|
+
.s-card:last-child{border-bottom:none;}
|
|
148
|
+
.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}
|
|
149
|
+
.s-icon{
|
|
150
|
+
width:42px;height:42px;border-radius:8px;
|
|
151
|
+
background:#0a3300;display:flex;align-items:center;justify-content:center;
|
|
152
|
+
font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;
|
|
153
|
+
font-family:'Geist Pixel',monospace;
|
|
154
|
+
}
|
|
155
|
+
.s-title{
|
|
156
|
+
font-family:'Geist Pixel',monospace;
|
|
157
|
+
font-size:1.25rem;font-weight:600;color:#33ff00;
|
|
158
|
+
}
|
|
159
|
+
.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}
|
|
160
|
+
.section-heading{
|
|
161
|
+
font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;
|
|
162
|
+
display:flex;align-items:center;justify-content:space-between;
|
|
163
|
+
}
|
|
164
|
+
.perm-list{list-style:none;}
|
|
165
|
+
.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}
|
|
166
|
+
.check{color:#33ff00;}
|
|
167
|
+
.org-row{
|
|
168
|
+
display:flex;align-items:center;gap:8px;padding:7px 0;
|
|
169
|
+
border-bottom:1px solid #0a3300;font-size:.8125rem;
|
|
170
|
+
}
|
|
171
|
+
.org-row:last-child{border-bottom:none;}
|
|
172
|
+
.org-icon{
|
|
173
|
+
width:22px;height:22px;border-radius:4px;background:#0a3300;
|
|
174
|
+
display:flex;align-items:center;justify-content:center;
|
|
175
|
+
font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;
|
|
176
|
+
font-family:'Geist Pixel',monospace;
|
|
177
|
+
}
|
|
178
|
+
.org-name{font-weight:600;color:#33ff00;}
|
|
179
|
+
.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}
|
|
180
|
+
.badge-granted{background:#0a3300;color:#33ff00;}
|
|
181
|
+
.badge-denied{background:#1a0a0a;color:#ff4444;}
|
|
182
|
+
.badge-requested{background:#0a3300;color:#1a8c00;}
|
|
183
|
+
.btn-revoke{
|
|
184
|
+
display:inline-block;padding:5px 14px;border-radius:6px;
|
|
185
|
+
border:1px solid #0a3300;background:transparent;color:#ff4444;
|
|
186
|
+
font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;
|
|
187
|
+
}
|
|
188
|
+
.btn-revoke:hover{border-color:#ff4444;}
|
|
189
|
+
.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}
|
|
190
|
+
.app-link{
|
|
191
|
+
display:flex;align-items:center;gap:12px;padding:12px;
|
|
192
|
+
border:1px solid #0a3300;border-radius:8px;background:#000;
|
|
193
|
+
text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;
|
|
194
|
+
}
|
|
195
|
+
.app-link:hover{border-color:#33ff00;}
|
|
196
|
+
.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}
|
|
197
|
+
.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}
|
|
198
|
+
.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}
|
|
199
|
+
`;
|
|
200
|
+
var POWERED_BY = `<div class="powered-by">Powered by <a href="https://emulate.dev" target="_blank" rel="noopener">emulate</a></div>`;
|
|
201
|
+
function emuBar(service) {
|
|
202
|
+
const title = service ? `${escapeHtml(service)} Emulator` : "Emulator";
|
|
203
|
+
return `<div class="emu-bar">
|
|
204
|
+
<span class="emu-bar-title">${title}</span>
|
|
205
|
+
<nav class="emu-bar-links">
|
|
206
|
+
<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>
|
|
207
|
+
<a href="https://github.com/vercel-labs/emulate" target="_blank" rel="noopener"><span class="full">Source Code</span><span class="short">Source</span></a>
|
|
208
|
+
<a href="https://emulate.dev" target="_blank" rel="noopener"><span class="full">Learn More</span><span class="short">Learn</span></a>
|
|
209
|
+
</nav>
|
|
210
|
+
</div>`;
|
|
211
|
+
}
|
|
212
|
+
function head(title) {
|
|
213
|
+
return `<!DOCTYPE html>
|
|
214
|
+
<html lang="en">
|
|
215
|
+
<head>
|
|
216
|
+
<meta charset="utf-8"/>
|
|
217
|
+
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
|
218
|
+
<title>${escapeHtml(title)} | emulate</title>
|
|
219
|
+
<style>${CSS}</style>
|
|
220
|
+
</head>`;
|
|
221
|
+
}
|
|
222
|
+
function renderCardPage(title, subtitle, body, service) {
|
|
223
|
+
return `${head(title)}
|
|
224
|
+
<body>
|
|
225
|
+
${emuBar(service)}
|
|
226
|
+
<div class="content">
|
|
227
|
+
<div class="content-inner">
|
|
228
|
+
<div class="card-title">${escapeHtml(title)}</div>
|
|
229
|
+
<div class="card-subtitle">${subtitle}</div>
|
|
230
|
+
${body}
|
|
231
|
+
</div>
|
|
232
|
+
</div>
|
|
233
|
+
${POWERED_BY}
|
|
234
|
+
</body></html>`;
|
|
235
|
+
}
|
|
236
|
+
function renderErrorPage(title, message, service) {
|
|
237
|
+
return `${head(title)}
|
|
238
|
+
<body>
|
|
239
|
+
${emuBar(service)}
|
|
240
|
+
<div class="content">
|
|
241
|
+
<div class="content-inner error-card">
|
|
242
|
+
<div class="error-title">${escapeHtml(title)}</div>
|
|
243
|
+
<div class="error-msg">${escapeHtml(message)}</div>
|
|
244
|
+
</div>
|
|
245
|
+
</div>
|
|
246
|
+
${POWERED_BY}
|
|
247
|
+
</body></html>`;
|
|
248
|
+
}
|
|
249
|
+
function renderUserButton(opts) {
|
|
250
|
+
const hiddens = Object.entries(opts.hiddenFields).map(([k, v]) => `<input type="hidden" name="${escapeAttr(k)}" value="${escapeAttr(v)}"/>`).join("");
|
|
251
|
+
const nameLine = opts.name ? `<div class="user-meta">${escapeHtml(opts.name)}</div>` : "";
|
|
252
|
+
const emailLine = opts.email ? `<div class="user-email">${escapeHtml(opts.email)}</div>` : "";
|
|
253
|
+
return `<form class="user-form" method="post" action="${escapeAttr(opts.formAction)}">
|
|
254
|
+
${hiddens}
|
|
255
|
+
<button type="submit" class="user-btn">
|
|
256
|
+
<span class="avatar">${escapeHtml(opts.letter)}</span>
|
|
257
|
+
<span class="user-text">
|
|
258
|
+
<span class="user-login">${escapeHtml(opts.login)}</span>
|
|
259
|
+
${nameLine}${emailLine}
|
|
260
|
+
</span>
|
|
261
|
+
</button>
|
|
262
|
+
</form>`;
|
|
263
|
+
}
|
|
264
|
+
function normalizeUri(uri) {
|
|
265
|
+
try {
|
|
266
|
+
const u = new URL(uri);
|
|
267
|
+
return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
|
|
268
|
+
} catch {
|
|
269
|
+
return uri.replace(/\/+$/, "").split("?")[0];
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function matchesRedirectUri(incoming, registered) {
|
|
273
|
+
const normalized = normalizeUri(incoming);
|
|
274
|
+
return registered.some((r) => normalizeUri(r) === normalized);
|
|
275
|
+
}
|
|
276
|
+
function constantTimeSecretEqual(a, b) {
|
|
277
|
+
const bufA = Buffer.from(a, "utf-8");
|
|
278
|
+
const bufB = Buffer.from(b, "utf-8");
|
|
279
|
+
if (bufA.length !== bufB.length) return false;
|
|
280
|
+
return timingSafeEqual(bufA, bufB);
|
|
281
|
+
}
|
|
282
|
+
function bodyStr(v) {
|
|
283
|
+
if (typeof v === "string") return v;
|
|
284
|
+
if (Array.isArray(v) && typeof v[0] === "string") return v[0];
|
|
285
|
+
return "";
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// src/routes/oauth.ts
|
|
289
|
+
var keyPairPromise = generateKeyPair("RS256");
|
|
290
|
+
var KID = "emulate-microsoft-1";
|
|
291
|
+
var PENDING_CODE_TTL_MS = 10 * 60 * 1e3;
|
|
292
|
+
function getPendingCodes(store) {
|
|
293
|
+
let map = store.getData("microsoft.oauth.pendingCodes");
|
|
294
|
+
if (!map) {
|
|
295
|
+
map = /* @__PURE__ */ new Map();
|
|
296
|
+
store.setData("microsoft.oauth.pendingCodes", map);
|
|
297
|
+
}
|
|
298
|
+
return map;
|
|
299
|
+
}
|
|
300
|
+
function getRefreshTokens(store) {
|
|
301
|
+
let map = store.getData("microsoft.oauth.refreshTokens");
|
|
302
|
+
if (!map) {
|
|
303
|
+
map = /* @__PURE__ */ new Map();
|
|
304
|
+
store.setData("microsoft.oauth.refreshTokens", map);
|
|
305
|
+
}
|
|
306
|
+
return map;
|
|
307
|
+
}
|
|
308
|
+
function isPendingCodeExpired(p) {
|
|
309
|
+
return Date.now() - p.created_at > PENDING_CODE_TTL_MS;
|
|
310
|
+
}
|
|
311
|
+
var SERVICE_LABEL = "Microsoft";
|
|
312
|
+
async function createIdToken(user, clientId, nonce, baseUrl) {
|
|
313
|
+
const { privateKey } = await keyPairPromise;
|
|
314
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
315
|
+
const builder = new SignJWT({
|
|
316
|
+
sub: user.oid,
|
|
317
|
+
email: user.email,
|
|
318
|
+
name: user.name,
|
|
319
|
+
given_name: user.given_name,
|
|
320
|
+
family_name: user.family_name,
|
|
321
|
+
preferred_username: user.preferred_username,
|
|
322
|
+
oid: user.oid,
|
|
323
|
+
tid: user.tenant_id,
|
|
324
|
+
ver: "2.0",
|
|
325
|
+
...nonce ? { nonce } : {}
|
|
326
|
+
}).setProtectedHeader({ alg: "RS256", kid: KID, typ: "JWT" }).setIssuer(`${baseUrl}/${user.tenant_id}/v2.0`).setAudience(clientId).setIssuedAt(now).setExpirationTime("1h");
|
|
327
|
+
return builder.sign(privateKey);
|
|
328
|
+
}
|
|
329
|
+
function oauthRoutes({ app, store, baseUrl, tokenMap }) {
|
|
330
|
+
const ms = getMicrosoftStore(store);
|
|
331
|
+
const oidcConfig = (tenantId) => ({
|
|
332
|
+
issuer: `${baseUrl}/${tenantId}/v2.0`,
|
|
333
|
+
authorization_endpoint: `${baseUrl}/oauth2/v2.0/authorize`,
|
|
334
|
+
token_endpoint: `${baseUrl}/oauth2/v2.0/token`,
|
|
335
|
+
userinfo_endpoint: `${baseUrl}/oidc/userinfo`,
|
|
336
|
+
end_session_endpoint: `${baseUrl}/oauth2/v2.0/logout`,
|
|
337
|
+
jwks_uri: `${baseUrl}/discovery/v2.0/keys`,
|
|
338
|
+
response_types_supported: ["code"],
|
|
339
|
+
response_modes_supported: ["query", "fragment", "form_post"],
|
|
340
|
+
subject_types_supported: ["pairwise"],
|
|
341
|
+
id_token_signing_alg_values_supported: ["RS256"],
|
|
342
|
+
scopes_supported: ["openid", "email", "profile", "offline_access", "User.Read", ".default"],
|
|
343
|
+
grant_types_supported: ["authorization_code", "refresh_token", "client_credentials"],
|
|
344
|
+
token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic"],
|
|
345
|
+
claims_supported: [
|
|
346
|
+
"sub",
|
|
347
|
+
"iss",
|
|
348
|
+
"aud",
|
|
349
|
+
"exp",
|
|
350
|
+
"iat",
|
|
351
|
+
"nonce",
|
|
352
|
+
"name",
|
|
353
|
+
"email",
|
|
354
|
+
"given_name",
|
|
355
|
+
"family_name",
|
|
356
|
+
"preferred_username",
|
|
357
|
+
"oid",
|
|
358
|
+
"tid",
|
|
359
|
+
"ver"
|
|
360
|
+
],
|
|
361
|
+
code_challenge_methods_supported: ["plain", "S256"]
|
|
362
|
+
});
|
|
363
|
+
app.get("/.well-known/openid-configuration", (c) => {
|
|
364
|
+
return c.json(oidcConfig(DEFAULT_TENANT_ID));
|
|
365
|
+
});
|
|
366
|
+
app.get("/:tenant/v2.0/.well-known/openid-configuration", (c) => {
|
|
367
|
+
const tenant = c.req.param("tenant");
|
|
368
|
+
return c.json(oidcConfig(tenant === "common" || tenant === "organizations" || tenant === "consumers" ? DEFAULT_TENANT_ID : tenant));
|
|
369
|
+
});
|
|
370
|
+
app.get("/discovery/v2.0/keys", async (c) => {
|
|
371
|
+
const { publicKey } = await keyPairPromise;
|
|
372
|
+
const jwk = await exportJWK(publicKey);
|
|
373
|
+
return c.json({
|
|
374
|
+
keys: [{
|
|
375
|
+
...jwk,
|
|
376
|
+
kid: KID,
|
|
377
|
+
use: "sig",
|
|
378
|
+
alg: "RS256"
|
|
379
|
+
}]
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
app.get("/oauth2/v2.0/authorize", (c) => {
|
|
383
|
+
const client_id = c.req.query("client_id") ?? "";
|
|
384
|
+
const redirect_uri = c.req.query("redirect_uri") ?? "";
|
|
385
|
+
const scope = c.req.query("scope") ?? "";
|
|
386
|
+
const state = c.req.query("state") ?? "";
|
|
387
|
+
const nonce = c.req.query("nonce") ?? "";
|
|
388
|
+
const response_mode = c.req.query("response_mode") ?? "query";
|
|
389
|
+
const code_challenge = c.req.query("code_challenge") ?? "";
|
|
390
|
+
const code_challenge_method = c.req.query("code_challenge_method") ?? "";
|
|
391
|
+
const clientsConfigured = ms.oauthClients.all().length > 0;
|
|
392
|
+
let clientName = "";
|
|
393
|
+
if (clientsConfigured) {
|
|
394
|
+
const client = ms.oauthClients.findOneBy("client_id", client_id);
|
|
395
|
+
if (!client) {
|
|
396
|
+
return c.html(
|
|
397
|
+
renderErrorPage("Application not found", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),
|
|
398
|
+
400
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {
|
|
402
|
+
return c.html(
|
|
403
|
+
renderErrorPage("Redirect URI mismatch", "The redirect_uri is not registered for this application.", SERVICE_LABEL),
|
|
404
|
+
400
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
clientName = client.name;
|
|
408
|
+
}
|
|
409
|
+
const subtitleText = clientName ? `Sign in to <strong>${escapeHtml(clientName)}</strong> with your Microsoft account.` : "Choose a seeded user to continue.";
|
|
410
|
+
const users = ms.users.all();
|
|
411
|
+
const userButtons = users.map((user) => {
|
|
412
|
+
return renderUserButton({
|
|
413
|
+
letter: (user.email[0] ?? "?").toUpperCase(),
|
|
414
|
+
login: user.email,
|
|
415
|
+
name: user.name,
|
|
416
|
+
email: user.email,
|
|
417
|
+
formAction: "/oauth2/v2.0/authorize/callback",
|
|
418
|
+
hiddenFields: {
|
|
419
|
+
email: user.email,
|
|
420
|
+
redirect_uri,
|
|
421
|
+
scope,
|
|
422
|
+
state,
|
|
423
|
+
nonce,
|
|
424
|
+
client_id,
|
|
425
|
+
response_mode,
|
|
426
|
+
code_challenge,
|
|
427
|
+
code_challenge_method
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
}).join("\n");
|
|
431
|
+
const body = users.length === 0 ? '<p class="empty">No users in the emulator store.</p>' : userButtons;
|
|
432
|
+
return c.html(renderCardPage("Sign in with Microsoft", subtitleText, body, SERVICE_LABEL));
|
|
433
|
+
});
|
|
434
|
+
app.post("/oauth2/v2.0/authorize/callback", async (c) => {
|
|
435
|
+
const body = await c.req.parseBody();
|
|
436
|
+
const email = bodyStr(body.email);
|
|
437
|
+
const redirect_uri = bodyStr(body.redirect_uri);
|
|
438
|
+
const scope = bodyStr(body.scope);
|
|
439
|
+
const state = bodyStr(body.state);
|
|
440
|
+
const client_id = bodyStr(body.client_id);
|
|
441
|
+
const nonce = bodyStr(body.nonce);
|
|
442
|
+
const response_mode = bodyStr(body.response_mode) || "query";
|
|
443
|
+
const code_challenge = bodyStr(body.code_challenge);
|
|
444
|
+
const code_challenge_method = bodyStr(body.code_challenge_method);
|
|
445
|
+
const clientsConfigured = ms.oauthClients.all().length > 0;
|
|
446
|
+
if (clientsConfigured) {
|
|
447
|
+
const client = ms.oauthClients.findOneBy("client_id", client_id);
|
|
448
|
+
if (!client) {
|
|
449
|
+
return c.html(
|
|
450
|
+
renderErrorPage("Application not found", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),
|
|
451
|
+
400
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {
|
|
455
|
+
return c.html(
|
|
456
|
+
renderErrorPage("Redirect URI mismatch", "The redirect_uri is not registered for this application.", SERVICE_LABEL),
|
|
457
|
+
400
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const code = randomBytes(20).toString("hex");
|
|
462
|
+
getPendingCodes(store).set(code, {
|
|
463
|
+
email,
|
|
464
|
+
scope,
|
|
465
|
+
redirectUri: redirect_uri,
|
|
466
|
+
clientId: client_id,
|
|
467
|
+
nonce: nonce || null,
|
|
468
|
+
codeChallenge: code_challenge || null,
|
|
469
|
+
codeChallengeMethod: code_challenge_method || null,
|
|
470
|
+
created_at: Date.now()
|
|
471
|
+
});
|
|
472
|
+
debug("microsoft.oauth", `[Microsoft callback] code=${code.slice(0, 8)}... email=${email}`);
|
|
473
|
+
if (response_mode === "form_post") {
|
|
474
|
+
const html = `<!DOCTYPE html>
|
|
475
|
+
<html>
|
|
476
|
+
<head><title>Submit</title></head>
|
|
477
|
+
<body onload="document.forms[0].submit()">
|
|
478
|
+
<form method="POST" action="${escapeAttr(redirect_uri)}">
|
|
479
|
+
<input type="hidden" name="code" value="${escapeAttr(code)}" />
|
|
480
|
+
<input type="hidden" name="state" value="${escapeAttr(state)}" />
|
|
481
|
+
</form>
|
|
482
|
+
</body>
|
|
483
|
+
</html>`;
|
|
484
|
+
return c.html(html);
|
|
485
|
+
}
|
|
486
|
+
const url = new URL(redirect_uri);
|
|
487
|
+
url.searchParams.set("code", code);
|
|
488
|
+
if (state) url.searchParams.set("state", state);
|
|
489
|
+
return c.redirect(url.toString(), 302);
|
|
490
|
+
});
|
|
491
|
+
app.post("/oauth2/v2.0/token", async (c) => {
|
|
492
|
+
const contentType = c.req.header("Content-Type") ?? "";
|
|
493
|
+
const rawText = await c.req.text();
|
|
494
|
+
let body;
|
|
495
|
+
if (contentType.includes("application/json")) {
|
|
496
|
+
try {
|
|
497
|
+
body = JSON.parse(rawText);
|
|
498
|
+
} catch {
|
|
499
|
+
body = {};
|
|
500
|
+
}
|
|
501
|
+
} else {
|
|
502
|
+
body = Object.fromEntries(new URLSearchParams(rawText));
|
|
503
|
+
}
|
|
504
|
+
const grant_type = typeof body.grant_type === "string" ? body.grant_type : "";
|
|
505
|
+
const code = typeof body.code === "string" ? body.code : "";
|
|
506
|
+
let client_id = typeof body.client_id === "string" ? body.client_id : "";
|
|
507
|
+
let client_secret = typeof body.client_secret === "string" ? body.client_secret : "";
|
|
508
|
+
const refresh_token = typeof body.refresh_token === "string" ? body.refresh_token : "";
|
|
509
|
+
const redirect_uri = typeof body.redirect_uri === "string" ? body.redirect_uri : "";
|
|
510
|
+
const code_verifier = typeof body.code_verifier === "string" ? body.code_verifier : void 0;
|
|
511
|
+
const scope = typeof body.scope === "string" ? body.scope : "";
|
|
512
|
+
const authHeader = c.req.header("Authorization") ?? "";
|
|
513
|
+
if (authHeader.startsWith("Basic ")) {
|
|
514
|
+
const decoded = Buffer.from(authHeader.slice(6), "base64").toString();
|
|
515
|
+
const sep = decoded.indexOf(":");
|
|
516
|
+
if (sep !== -1) {
|
|
517
|
+
const headerId = decodeURIComponent(decoded.slice(0, sep));
|
|
518
|
+
const headerSecret = decodeURIComponent(decoded.slice(sep + 1));
|
|
519
|
+
if (!client_id) client_id = headerId;
|
|
520
|
+
if (!client_secret) client_secret = headerSecret;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (grant_type === "authorization_code") {
|
|
524
|
+
const clientsConfigured = ms.oauthClients.all().length > 0;
|
|
525
|
+
if (clientsConfigured) {
|
|
526
|
+
const client = ms.oauthClients.findOneBy("client_id", client_id);
|
|
527
|
+
if (!client) {
|
|
528
|
+
return c.json({ error: "invalid_client", error_description: "The client_id is incorrect." }, 401);
|
|
529
|
+
}
|
|
530
|
+
if (!constantTimeSecretEqual(client_secret, client.client_secret)) {
|
|
531
|
+
return c.json({ error: "invalid_client", error_description: "The client_secret is incorrect." }, 401);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const pendingMap = getPendingCodes(store);
|
|
535
|
+
const pending = pendingMap.get(code);
|
|
536
|
+
if (!pending) {
|
|
537
|
+
return c.json({ error: "invalid_grant", error_description: "The code is incorrect or expired." }, 400);
|
|
538
|
+
}
|
|
539
|
+
if (isPendingCodeExpired(pending)) {
|
|
540
|
+
pendingMap.delete(code);
|
|
541
|
+
return c.json({ error: "invalid_grant", error_description: "The code is incorrect or expired." }, 400);
|
|
542
|
+
}
|
|
543
|
+
if (pending.redirectUri && redirect_uri && pending.redirectUri !== redirect_uri) {
|
|
544
|
+
pendingMap.delete(code);
|
|
545
|
+
return c.json({ error: "invalid_grant", error_description: "The redirect_uri does not match the one used in the authorization request." }, 400);
|
|
546
|
+
}
|
|
547
|
+
if (pending.codeChallenge !== null) {
|
|
548
|
+
if (code_verifier === void 0) {
|
|
549
|
+
return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
|
|
550
|
+
}
|
|
551
|
+
const method = (pending.codeChallengeMethod ?? "plain").toLowerCase();
|
|
552
|
+
if (method === "s256") {
|
|
553
|
+
const expected = createHash("sha256").update(code_verifier).digest("base64url");
|
|
554
|
+
if (expected !== pending.codeChallenge) {
|
|
555
|
+
return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
|
|
556
|
+
}
|
|
557
|
+
} else if (method === "plain") {
|
|
558
|
+
if (code_verifier !== pending.codeChallenge) {
|
|
559
|
+
return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
|
|
560
|
+
}
|
|
561
|
+
} else {
|
|
562
|
+
return c.json({ error: "invalid_grant", error_description: "PKCE verification failed." }, 400);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
pendingMap.delete(code);
|
|
566
|
+
const user = ms.users.findOneBy("email", pending.email);
|
|
567
|
+
if (!user) {
|
|
568
|
+
return c.json({ error: "invalid_grant", error_description: "User not found." }, 400);
|
|
569
|
+
}
|
|
570
|
+
const accessToken = "microsoft_" + randomBytes(20).toString("base64url");
|
|
571
|
+
const refreshToken = "r_microsoft_" + randomBytes(20).toString("base64url");
|
|
572
|
+
const scopes = pending.scope ? pending.scope.split(/\s+/).filter(Boolean) : [];
|
|
573
|
+
if (tokenMap) {
|
|
574
|
+
tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });
|
|
575
|
+
}
|
|
576
|
+
getRefreshTokens(store).set(refreshToken, {
|
|
577
|
+
email: user.email,
|
|
578
|
+
clientId: pending.clientId,
|
|
579
|
+
scope: pending.scope,
|
|
580
|
+
nonce: pending.nonce
|
|
581
|
+
});
|
|
582
|
+
const idToken = await createIdToken(user, pending.clientId, pending.nonce, baseUrl);
|
|
583
|
+
debug("microsoft.oauth", `[Microsoft token] issued token for ${user.email}`);
|
|
584
|
+
return c.json({
|
|
585
|
+
access_token: accessToken,
|
|
586
|
+
token_type: "Bearer",
|
|
587
|
+
expires_in: 3600,
|
|
588
|
+
scope: pending.scope || "openid email profile",
|
|
589
|
+
refresh_token: refreshToken,
|
|
590
|
+
id_token: idToken
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
if (grant_type === "refresh_token") {
|
|
594
|
+
const refreshMap = getRefreshTokens(store);
|
|
595
|
+
const stored = refreshMap.get(refresh_token);
|
|
596
|
+
if (!stored) {
|
|
597
|
+
return c.json({ error: "invalid_grant", error_description: "The refresh_token is invalid." }, 400);
|
|
598
|
+
}
|
|
599
|
+
const user = ms.users.findOneBy("email", stored.email);
|
|
600
|
+
if (!user) {
|
|
601
|
+
return c.json({ error: "invalid_grant", error_description: "User not found." }, 400);
|
|
602
|
+
}
|
|
603
|
+
const accessToken = "microsoft_" + randomBytes(20).toString("base64url");
|
|
604
|
+
const newRefreshToken = "r_microsoft_" + randomBytes(20).toString("base64url");
|
|
605
|
+
const scopes = stored.scope ? stored.scope.split(/\s+/).filter(Boolean) : [];
|
|
606
|
+
if (tokenMap) {
|
|
607
|
+
tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });
|
|
608
|
+
}
|
|
609
|
+
refreshMap.delete(refresh_token);
|
|
610
|
+
refreshMap.set(newRefreshToken, {
|
|
611
|
+
email: stored.email,
|
|
612
|
+
clientId: stored.clientId,
|
|
613
|
+
scope: stored.scope,
|
|
614
|
+
nonce: stored.nonce
|
|
615
|
+
});
|
|
616
|
+
const idToken = await createIdToken(user, stored.clientId || client_id, stored.nonce, baseUrl);
|
|
617
|
+
debug("microsoft.oauth", `[Microsoft refresh] issued new token for ${user.email}`);
|
|
618
|
+
return c.json({
|
|
619
|
+
access_token: accessToken,
|
|
620
|
+
token_type: "Bearer",
|
|
621
|
+
expires_in: 3600,
|
|
622
|
+
scope: stored.scope || "openid email profile",
|
|
623
|
+
refresh_token: newRefreshToken,
|
|
624
|
+
id_token: idToken
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
if (grant_type === "client_credentials") {
|
|
628
|
+
const clientsConfigured = ms.oauthClients.all().length > 0;
|
|
629
|
+
if (clientsConfigured) {
|
|
630
|
+
const client = ms.oauthClients.findOneBy("client_id", client_id);
|
|
631
|
+
if (!client) {
|
|
632
|
+
return c.json({ error: "invalid_client", error_description: "The client_id is incorrect." }, 401);
|
|
633
|
+
}
|
|
634
|
+
if (!constantTimeSecretEqual(client_secret, client.client_secret)) {
|
|
635
|
+
return c.json({ error: "invalid_client", error_description: "The client_secret is incorrect." }, 401);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
const accessToken = "microsoft_" + randomBytes(20).toString("base64url");
|
|
639
|
+
const scopes = scope ? scope.split(/\s+/).filter(Boolean) : [".default"];
|
|
640
|
+
if (tokenMap) {
|
|
641
|
+
tokenMap.set(accessToken, { login: client_id, id: 0, scopes });
|
|
642
|
+
}
|
|
643
|
+
debug("microsoft.oauth", `[Microsoft client_credentials] issued token for ${client_id}`);
|
|
644
|
+
return c.json({
|
|
645
|
+
access_token: accessToken,
|
|
646
|
+
token_type: "Bearer",
|
|
647
|
+
expires_in: 3600,
|
|
648
|
+
scope: scope || ".default"
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
return c.json({ error: "unsupported_grant_type", error_description: "Only authorization_code, refresh_token, and client_credentials are supported." }, 400);
|
|
652
|
+
});
|
|
653
|
+
app.get("/oidc/userinfo", (c) => {
|
|
654
|
+
const authUser = c.get("authUser");
|
|
655
|
+
if (!authUser) {
|
|
656
|
+
return c.json({ error: "invalid_token", error_description: "Authentication required." }, 401);
|
|
657
|
+
}
|
|
658
|
+
const user = ms.users.findOneBy("email", authUser.login);
|
|
659
|
+
if (!user) {
|
|
660
|
+
return c.json({ error: "invalid_token", error_description: "User not found." }, 401);
|
|
661
|
+
}
|
|
662
|
+
return c.json({
|
|
663
|
+
sub: user.oid,
|
|
664
|
+
email: user.email,
|
|
665
|
+
name: user.name,
|
|
666
|
+
given_name: user.given_name,
|
|
667
|
+
family_name: user.family_name,
|
|
668
|
+
preferred_username: user.preferred_username
|
|
669
|
+
});
|
|
670
|
+
});
|
|
671
|
+
app.get("/v1.0/me", (c) => {
|
|
672
|
+
const authUser = c.get("authUser");
|
|
673
|
+
if (!authUser) {
|
|
674
|
+
return c.json({ error: { code: "InvalidAuthenticationToken", message: "Authentication required." } }, 401);
|
|
675
|
+
}
|
|
676
|
+
const user = ms.users.findOneBy("email", authUser.login);
|
|
677
|
+
if (!user) {
|
|
678
|
+
return c.json({ error: { code: "Request_ResourceNotFound", message: "User not found." } }, 404);
|
|
679
|
+
}
|
|
680
|
+
return c.json({
|
|
681
|
+
"@odata.context": `${baseUrl}/v1.0/$metadata#users/$entity`,
|
|
682
|
+
id: user.oid,
|
|
683
|
+
displayName: user.name,
|
|
684
|
+
givenName: user.given_name,
|
|
685
|
+
surname: user.family_name,
|
|
686
|
+
mail: user.email,
|
|
687
|
+
userPrincipalName: user.preferred_username
|
|
688
|
+
});
|
|
689
|
+
});
|
|
690
|
+
app.get("/oauth2/v2.0/logout", (c) => {
|
|
691
|
+
const post_logout_redirect_uri = c.req.query("post_logout_redirect_uri");
|
|
692
|
+
if (post_logout_redirect_uri) {
|
|
693
|
+
const allClients = ms.oauthClients.all();
|
|
694
|
+
if (allClients.length > 0) {
|
|
695
|
+
const allowed = allClients.some(
|
|
696
|
+
(client) => matchesRedirectUri(post_logout_redirect_uri, client.redirect_uris)
|
|
697
|
+
);
|
|
698
|
+
if (!allowed) {
|
|
699
|
+
return c.text("Invalid post_logout_redirect_uri", 400);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
return c.redirect(post_logout_redirect_uri, 302);
|
|
703
|
+
}
|
|
704
|
+
return c.text("Logged out", 200);
|
|
705
|
+
});
|
|
706
|
+
app.post("/oauth2/v2.0/revoke", async (c) => {
|
|
707
|
+
const contentType = c.req.header("Content-Type") ?? "";
|
|
708
|
+
const rawText = await c.req.text();
|
|
709
|
+
let token;
|
|
710
|
+
if (contentType.includes("application/json")) {
|
|
711
|
+
try {
|
|
712
|
+
const parsed = JSON.parse(rawText);
|
|
713
|
+
token = typeof parsed.token === "string" ? parsed.token : "";
|
|
714
|
+
} catch {
|
|
715
|
+
token = "";
|
|
716
|
+
}
|
|
717
|
+
} else {
|
|
718
|
+
const params = new URLSearchParams(rawText);
|
|
719
|
+
token = params.get("token") ?? "";
|
|
720
|
+
}
|
|
721
|
+
if (token && tokenMap) {
|
|
722
|
+
tokenMap.delete(token);
|
|
723
|
+
}
|
|
724
|
+
if (token) {
|
|
725
|
+
getRefreshTokens(store).delete(token);
|
|
726
|
+
}
|
|
727
|
+
return c.body(null, 200);
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// src/index.ts
|
|
732
|
+
function seedDefaults(store, _baseUrl) {
|
|
733
|
+
const ms = getMicrosoftStore(store);
|
|
734
|
+
ms.users.insert({
|
|
735
|
+
oid: generateOid(),
|
|
736
|
+
email: "testuser@outlook.com",
|
|
737
|
+
name: "Test User",
|
|
738
|
+
given_name: "Test",
|
|
739
|
+
family_name: "User",
|
|
740
|
+
email_verified: true,
|
|
741
|
+
tenant_id: DEFAULT_TENANT_ID,
|
|
742
|
+
preferred_username: "testuser@outlook.com"
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
function seedFromConfig(store, _baseUrl, config) {
|
|
746
|
+
const ms = getMicrosoftStore(store);
|
|
747
|
+
if (config.users) {
|
|
748
|
+
for (const u of config.users) {
|
|
749
|
+
const existing = ms.users.findOneBy("email", u.email);
|
|
750
|
+
if (existing) continue;
|
|
751
|
+
const nameParts = (u.name ?? "").split(/\s+/);
|
|
752
|
+
ms.users.insert({
|
|
753
|
+
oid: generateOid(),
|
|
754
|
+
email: u.email,
|
|
755
|
+
name: u.name ?? u.email.split("@")[0],
|
|
756
|
+
given_name: u.given_name ?? nameParts[0] ?? "",
|
|
757
|
+
family_name: u.family_name ?? nameParts.slice(1).join(" ") ?? "",
|
|
758
|
+
email_verified: true,
|
|
759
|
+
tenant_id: u.tenant_id ?? DEFAULT_TENANT_ID,
|
|
760
|
+
preferred_username: u.email
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
if (config.oauth_clients) {
|
|
765
|
+
for (const client of config.oauth_clients) {
|
|
766
|
+
const existing = ms.oauthClients.findOneBy("client_id", client.client_id);
|
|
767
|
+
if (existing) continue;
|
|
768
|
+
ms.oauthClients.insert({
|
|
769
|
+
client_id: client.client_id,
|
|
770
|
+
client_secret: client.client_secret,
|
|
771
|
+
name: client.name,
|
|
772
|
+
redirect_uris: client.redirect_uris,
|
|
773
|
+
tenant_id: client.tenant_id ?? DEFAULT_TENANT_ID
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
var microsoftPlugin = {
|
|
779
|
+
name: "microsoft",
|
|
780
|
+
register(app, store, webhooks, baseUrl, tokenMap) {
|
|
781
|
+
const ctx = { app, store, webhooks, baseUrl, tokenMap };
|
|
782
|
+
oauthRoutes(ctx);
|
|
783
|
+
},
|
|
784
|
+
seed(store, baseUrl) {
|
|
785
|
+
seedDefaults(store, baseUrl);
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
var index_default = microsoftPlugin;
|
|
789
|
+
export {
|
|
790
|
+
index_default as default,
|
|
791
|
+
getMicrosoftStore,
|
|
792
|
+
microsoftPlugin,
|
|
793
|
+
seedFromConfig
|
|
794
|
+
};
|
|
795
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/store.ts","../src/helpers.ts","../src/routes/oauth.ts","../../core/src/store.ts","../../core/src/server.ts","../../core/src/webhooks.ts","../../core/src/middleware/error-handler.ts","../../core/src/middleware/auth.ts","../../core/src/debug.ts","../../core/src/fonts.ts","../../core/src/middleware/pagination.ts","../../core/src/ui.ts","../../core/src/oauth-helpers.ts","../src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type { MicrosoftUser, MicrosoftOAuthClient } from \"./entities.js\";\n\nexport interface MicrosoftStore {\n users: Collection<MicrosoftUser>;\n oauthClients: Collection<MicrosoftOAuthClient>;\n}\n\nexport function getMicrosoftStore(store: Store): MicrosoftStore {\n return {\n users: store.collection<MicrosoftUser>(\"microsoft.users\", [\"oid\", \"email\"]),\n oauthClients: store.collection<MicrosoftOAuthClient>(\"microsoft.oauth_clients\", [\"client_id\"]),\n };\n}\n","import { randomUUID } from \"crypto\";\n\n/** Default tenant ID used when none is configured */\nexport const DEFAULT_TENANT_ID = \"9188040d-6c67-4c5b-b112-36a304b66dad\";\n\n/**\n * Generate a Microsoft-style object ID (UUID v4 format).\n */\nexport function generateOid(): string {\n return randomUUID();\n}\n","import { createHash, randomBytes } from \"crypto\";\nimport { SignJWT, exportJWK, generateKeyPair } from \"jose\";\nimport type { RouteContext } from \"@emulators/core\";\nimport {\n escapeHtml,\n escapeAttr,\n renderCardPage,\n renderErrorPage,\n renderUserButton,\n matchesRedirectUri,\n constantTimeSecretEqual,\n bodyStr,\n debug,\n} from \"@emulators/core\";\nimport { getMicrosoftStore } from \"../store.js\";\nimport { DEFAULT_TENANT_ID } from \"../helpers.js\";\nimport type { MicrosoftUser } from \"../entities.js\";\nimport type { Store } from \"@emulators/core\";\n\n// RSA key pair generated at module load for signing id_tokens\nconst keyPairPromise = generateKeyPair(\"RS256\");\nconst KID = \"emulate-microsoft-1\";\n\ntype PendingCode = {\n email: string;\n scope: string;\n redirectUri: string;\n clientId: string;\n nonce: string | null;\n codeChallenge: string | null;\n codeChallengeMethod: string | null;\n created_at: number;\n};\n\ntype StoredRefreshToken = {\n email: string;\n clientId: string;\n scope: string;\n nonce: string | null;\n};\n\nconst PENDING_CODE_TTL_MS = 10 * 60 * 1000;\n\nfunction getPendingCodes(store: Store): Map<string, PendingCode> {\n let map = store.getData<Map<string, PendingCode>>(\"microsoft.oauth.pendingCodes\");\n if (!map) {\n map = new Map();\n store.setData(\"microsoft.oauth.pendingCodes\", map);\n }\n return map;\n}\n\nfunction getRefreshTokens(store: Store): Map<string, StoredRefreshToken> {\n let map = store.getData<Map<string, StoredRefreshToken>>(\"microsoft.oauth.refreshTokens\");\n if (!map) {\n map = new Map();\n store.setData(\"microsoft.oauth.refreshTokens\", map);\n }\n return map;\n}\n\nfunction isPendingCodeExpired(p: PendingCode): boolean {\n return Date.now() - p.created_at > PENDING_CODE_TTL_MS;\n}\n\nconst SERVICE_LABEL = \"Microsoft\";\n\nasync function createIdToken(\n user: MicrosoftUser,\n clientId: string,\n nonce: string | null,\n baseUrl: string,\n): Promise<string> {\n const { privateKey } = await keyPairPromise;\n const now = Math.floor(Date.now() / 1000);\n\n const builder = new SignJWT({\n sub: user.oid,\n email: user.email,\n name: user.name,\n given_name: user.given_name,\n family_name: user.family_name,\n preferred_username: user.preferred_username,\n oid: user.oid,\n tid: user.tenant_id,\n ver: \"2.0\",\n ...(nonce ? { nonce } : {}),\n })\n .setProtectedHeader({ alg: \"RS256\", kid: KID, typ: \"JWT\" })\n .setIssuer(`${baseUrl}/${user.tenant_id}/v2.0`)\n .setAudience(clientId)\n .setIssuedAt(now)\n .setExpirationTime(\"1h\");\n\n return builder.sign(privateKey);\n}\n\nexport function oauthRoutes({ app, store, baseUrl, tokenMap }: RouteContext): void {\n const ms = getMicrosoftStore(store);\n\n // ---------- OpenID Configuration ----------\n // Microsoft uses /{tenant}/v2.0/.well-known/openid-configuration\n // We also serve at /.well-known/openid-configuration for convenience.\n\n const oidcConfig = (tenantId: string) => ({\n issuer: `${baseUrl}/${tenantId}/v2.0`,\n authorization_endpoint: `${baseUrl}/oauth2/v2.0/authorize`,\n token_endpoint: `${baseUrl}/oauth2/v2.0/token`,\n userinfo_endpoint: `${baseUrl}/oidc/userinfo`,\n end_session_endpoint: `${baseUrl}/oauth2/v2.0/logout`,\n jwks_uri: `${baseUrl}/discovery/v2.0/keys`,\n response_types_supported: [\"code\"],\n response_modes_supported: [\"query\", \"fragment\", \"form_post\"],\n subject_types_supported: [\"pairwise\"],\n id_token_signing_alg_values_supported: [\"RS256\"],\n scopes_supported: [\"openid\", \"email\", \"profile\", \"offline_access\", \"User.Read\", \".default\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\", \"client_credentials\"],\n token_endpoint_auth_methods_supported: [\"client_secret_post\", \"client_secret_basic\"],\n claims_supported: [\n \"sub\", \"iss\", \"aud\", \"exp\", \"iat\", \"nonce\",\n \"name\", \"email\", \"given_name\", \"family_name\",\n \"preferred_username\", \"oid\", \"tid\", \"ver\",\n ],\n code_challenge_methods_supported: [\"plain\", \"S256\"],\n });\n\n app.get(\"/.well-known/openid-configuration\", (c) => {\n return c.json(oidcConfig(DEFAULT_TENANT_ID));\n });\n\n app.get(\"/:tenant/v2.0/.well-known/openid-configuration\", (c) => {\n const tenant = c.req.param(\"tenant\");\n return c.json(oidcConfig(tenant === \"common\" || tenant === \"organizations\" || tenant === \"consumers\" ? DEFAULT_TENANT_ID : tenant));\n });\n\n // ---------- JWKS ----------\n\n app.get(\"/discovery/v2.0/keys\", async (c) => {\n const { publicKey } = await keyPairPromise;\n const jwk = await exportJWK(publicKey);\n return c.json({\n keys: [{\n ...jwk,\n kid: KID,\n use: \"sig\",\n alg: \"RS256\",\n }],\n });\n });\n\n // ---------- Authorization page ----------\n\n app.get(\"/oauth2/v2.0/authorize\", (c) => {\n const client_id = c.req.query(\"client_id\") ?? \"\";\n const redirect_uri = c.req.query(\"redirect_uri\") ?? \"\";\n const scope = c.req.query(\"scope\") ?? \"\";\n const state = c.req.query(\"state\") ?? \"\";\n const nonce = c.req.query(\"nonce\") ?? \"\";\n const response_mode = c.req.query(\"response_mode\") ?? \"query\";\n const code_challenge = c.req.query(\"code_challenge\") ?? \"\";\n const code_challenge_method = c.req.query(\"code_challenge_method\") ?? \"\";\n\n const clientsConfigured = ms.oauthClients.all().length > 0;\n let clientName = \"\";\n if (clientsConfigured) {\n const client = ms.oauthClients.findOneBy(\"client_id\", client_id);\n if (!client) {\n return c.html(\n renderErrorPage(\"Application not found\", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),\n 400,\n );\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {\n return c.html(\n renderErrorPage(\"Redirect URI mismatch\", \"The redirect_uri is not registered for this application.\", SERVICE_LABEL),\n 400,\n );\n }\n clientName = client.name;\n }\n\n const subtitleText = clientName\n ? `Sign in to <strong>${escapeHtml(clientName)}</strong> with your Microsoft account.`\n : \"Choose a seeded user to continue.\";\n\n const users = ms.users.all();\n const userButtons = users\n .map((user) => {\n return renderUserButton({\n letter: (user.email[0] ?? \"?\").toUpperCase(),\n login: user.email,\n name: user.name,\n email: user.email,\n formAction: \"/oauth2/v2.0/authorize/callback\",\n hiddenFields: {\n email: user.email,\n redirect_uri,\n scope,\n state,\n nonce,\n client_id,\n response_mode,\n code_challenge,\n code_challenge_method,\n },\n });\n })\n .join(\"\\n\");\n\n const body = users.length === 0\n ? '<p class=\"empty\">No users in the emulator store.</p>'\n : userButtons;\n\n return c.html(renderCardPage(\"Sign in with Microsoft\", subtitleText, body, SERVICE_LABEL));\n });\n\n // ---------- Authorization callback ----------\n\n app.post(\"/oauth2/v2.0/authorize/callback\", async (c) => {\n const body = await c.req.parseBody();\n const email = bodyStr(body.email);\n const redirect_uri = bodyStr(body.redirect_uri);\n const scope = bodyStr(body.scope);\n const state = bodyStr(body.state);\n const client_id = bodyStr(body.client_id);\n const nonce = bodyStr(body.nonce);\n const response_mode = bodyStr(body.response_mode) || \"query\";\n const code_challenge = bodyStr(body.code_challenge);\n const code_challenge_method = bodyStr(body.code_challenge_method);\n\n // Validate redirect_uri against registered client\n const clientsConfigured = ms.oauthClients.all().length > 0;\n if (clientsConfigured) {\n const client = ms.oauthClients.findOneBy(\"client_id\", client_id);\n if (!client) {\n return c.html(\n renderErrorPage(\"Application not found\", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),\n 400,\n );\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {\n return c.html(\n renderErrorPage(\"Redirect URI mismatch\", \"The redirect_uri is not registered for this application.\", SERVICE_LABEL),\n 400,\n );\n }\n }\n\n const code = randomBytes(20).toString(\"hex\");\n\n getPendingCodes(store).set(code, {\n email,\n scope,\n redirectUri: redirect_uri,\n clientId: client_id,\n nonce: nonce || null,\n codeChallenge: code_challenge || null,\n codeChallengeMethod: code_challenge_method || null,\n created_at: Date.now(),\n });\n\n debug(\"microsoft.oauth\", `[Microsoft callback] code=${code.slice(0, 8)}... email=${email}`);\n\n if (response_mode === \"form_post\") {\n const html = `<!DOCTYPE html>\n<html>\n<head><title>Submit</title></head>\n<body onload=\"document.forms[0].submit()\">\n<form method=\"POST\" action=\"${escapeAttr(redirect_uri)}\">\n<input type=\"hidden\" name=\"code\" value=\"${escapeAttr(code)}\" />\n<input type=\"hidden\" name=\"state\" value=\"${escapeAttr(state)}\" />\n</form>\n</body>\n</html>`;\n return c.html(html);\n }\n\n // Default: query mode redirect\n const url = new URL(redirect_uri);\n url.searchParams.set(\"code\", code);\n if (state) url.searchParams.set(\"state\", state);\n\n return c.redirect(url.toString(), 302);\n });\n\n // ---------- Token exchange ----------\n\n app.post(\"/oauth2/v2.0/token\", async (c) => {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const rawText = await c.req.text();\n\n let body: Record<string, unknown>;\n if (contentType.includes(\"application/json\")) {\n try { body = JSON.parse(rawText); } catch { body = {}; }\n } else {\n body = Object.fromEntries(new URLSearchParams(rawText));\n }\n\n const grant_type = typeof body.grant_type === \"string\" ? body.grant_type : \"\";\n const code = typeof body.code === \"string\" ? body.code : \"\";\n let client_id = typeof body.client_id === \"string\" ? body.client_id : \"\";\n let client_secret = typeof body.client_secret === \"string\" ? body.client_secret : \"\";\n const refresh_token = typeof body.refresh_token === \"string\" ? body.refresh_token : \"\";\n const redirect_uri = typeof body.redirect_uri === \"string\" ? body.redirect_uri : \"\";\n const code_verifier = typeof body.code_verifier === \"string\" ? body.code_verifier : undefined;\n const scope = typeof body.scope === \"string\" ? body.scope : \"\";\n\n // Support client_secret_basic: credentials in Authorization header\n const authHeader = c.req.header(\"Authorization\") ?? \"\";\n if (authHeader.startsWith(\"Basic \")) {\n const decoded = Buffer.from(authHeader.slice(6), \"base64\").toString();\n const sep = decoded.indexOf(\":\");\n if (sep !== -1) {\n const headerId = decodeURIComponent(decoded.slice(0, sep));\n const headerSecret = decodeURIComponent(decoded.slice(sep + 1));\n if (!client_id) client_id = headerId;\n if (!client_secret) client_secret = headerSecret;\n }\n }\n\n if (grant_type === \"authorization_code\") {\n const clientsConfigured = ms.oauthClients.all().length > 0;\n if (clientsConfigured) {\n const client = ms.oauthClients.findOneBy(\"client_id\", client_id);\n if (!client) {\n return c.json({ error: \"invalid_client\", error_description: \"The client_id is incorrect.\" }, 401);\n }\n if (!constantTimeSecretEqual(client_secret, client.client_secret)) {\n return c.json({ error: \"invalid_client\", error_description: \"The client_secret is incorrect.\" }, 401);\n }\n }\n\n const pendingMap = getPendingCodes(store);\n const pending = pendingMap.get(code);\n if (!pending) {\n return c.json({ error: \"invalid_grant\", error_description: \"The code is incorrect or expired.\" }, 400);\n }\n if (isPendingCodeExpired(pending)) {\n pendingMap.delete(code);\n return c.json({ error: \"invalid_grant\", error_description: \"The code is incorrect or expired.\" }, 400);\n }\n\n // Verify redirect_uri matches the one used in the authorization request (RFC 6749 §4.1.3)\n if (pending.redirectUri && redirect_uri && pending.redirectUri !== redirect_uri) {\n pendingMap.delete(code);\n return c.json({ error: \"invalid_grant\", error_description: \"The redirect_uri does not match the one used in the authorization request.\" }, 400);\n }\n\n // PKCE verification\n if (pending.codeChallenge !== null) {\n if (code_verifier === undefined) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n const method = (pending.codeChallengeMethod ?? \"plain\").toLowerCase();\n if (method === \"s256\") {\n const expected = createHash(\"sha256\").update(code_verifier).digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n } else if (method === \"plain\") {\n if (code_verifier !== pending.codeChallenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n } else {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n }\n\n // Single-use: delete immediately\n pendingMap.delete(code);\n\n const user = ms.users.findOneBy(\"email\", pending.email as MicrosoftUser[\"email\"]);\n if (!user) {\n return c.json({ error: \"invalid_grant\", error_description: \"User not found.\" }, 400);\n }\n\n const accessToken = \"microsoft_\" + randomBytes(20).toString(\"base64url\");\n const refreshToken = \"r_microsoft_\" + randomBytes(20).toString(\"base64url\");\n const scopes = pending.scope ? pending.scope.split(/\\s+/).filter(Boolean) : [];\n\n if (tokenMap) {\n tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });\n }\n\n // Store refresh token\n getRefreshTokens(store).set(refreshToken, {\n email: user.email,\n clientId: pending.clientId,\n scope: pending.scope,\n nonce: pending.nonce,\n });\n\n const idToken = await createIdToken(user, pending.clientId, pending.nonce, baseUrl);\n\n debug(\"microsoft.oauth\", `[Microsoft token] issued token for ${user.email}`);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: 3600,\n scope: pending.scope || \"openid email profile\",\n refresh_token: refreshToken,\n id_token: idToken,\n });\n }\n\n if (grant_type === \"refresh_token\") {\n const refreshMap = getRefreshTokens(store);\n const stored = refreshMap.get(refresh_token);\n if (!stored) {\n return c.json({ error: \"invalid_grant\", error_description: \"The refresh_token is invalid.\" }, 400);\n }\n\n const user = ms.users.findOneBy(\"email\", stored.email as MicrosoftUser[\"email\"]);\n if (!user) {\n return c.json({ error: \"invalid_grant\", error_description: \"User not found.\" }, 400);\n }\n\n const accessToken = \"microsoft_\" + randomBytes(20).toString(\"base64url\");\n const newRefreshToken = \"r_microsoft_\" + randomBytes(20).toString(\"base64url\");\n const scopes = stored.scope ? stored.scope.split(/\\s+/).filter(Boolean) : [];\n\n if (tokenMap) {\n tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });\n }\n\n // Rotate refresh token\n refreshMap.delete(refresh_token);\n refreshMap.set(newRefreshToken, {\n email: stored.email,\n clientId: stored.clientId,\n scope: stored.scope,\n nonce: stored.nonce,\n });\n\n const idToken = await createIdToken(user, stored.clientId || client_id, stored.nonce, baseUrl);\n\n debug(\"microsoft.oauth\", `[Microsoft refresh] issued new token for ${user.email}`);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: 3600,\n scope: stored.scope || \"openid email profile\",\n refresh_token: newRefreshToken,\n id_token: idToken,\n });\n }\n\n if (grant_type === \"client_credentials\") {\n const clientsConfigured = ms.oauthClients.all().length > 0;\n if (clientsConfigured) {\n const client = ms.oauthClients.findOneBy(\"client_id\", client_id);\n if (!client) {\n return c.json({ error: \"invalid_client\", error_description: \"The client_id is incorrect.\" }, 401);\n }\n if (!constantTimeSecretEqual(client_secret, client.client_secret)) {\n return c.json({ error: \"invalid_client\", error_description: \"The client_secret is incorrect.\" }, 401);\n }\n }\n\n const accessToken = \"microsoft_\" + randomBytes(20).toString(\"base64url\");\n const scopes = scope ? scope.split(/\\s+/).filter(Boolean) : [\".default\"];\n\n if (tokenMap) {\n tokenMap.set(accessToken, { login: client_id, id: 0, scopes });\n }\n\n debug(\"microsoft.oauth\", `[Microsoft client_credentials] issued token for ${client_id}`);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: 3600,\n scope: scope || \".default\",\n });\n }\n\n return c.json({ error: \"unsupported_grant_type\", error_description: \"Only authorization_code, refresh_token, and client_credentials are supported.\" }, 400);\n });\n\n // ---------- UserInfo (Microsoft Graph /oidc/userinfo) ----------\n\n app.get(\"/oidc/userinfo\", (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) {\n return c.json({ error: \"invalid_token\", error_description: \"Authentication required.\" }, 401);\n }\n\n const user = ms.users.findOneBy(\"email\", authUser.login as MicrosoftUser[\"email\"]);\n if (!user) {\n return c.json({ error: \"invalid_token\", error_description: \"User not found.\" }, 401);\n }\n\n return c.json({\n sub: user.oid,\n email: user.email,\n name: user.name,\n given_name: user.given_name,\n family_name: user.family_name,\n preferred_username: user.preferred_username,\n });\n });\n\n // ---------- Microsoft Graph /me endpoint ----------\n\n app.get(\"/v1.0/me\", (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) {\n return c.json({ error: { code: \"InvalidAuthenticationToken\", message: \"Authentication required.\" } }, 401);\n }\n\n const user = ms.users.findOneBy(\"email\", authUser.login as MicrosoftUser[\"email\"]);\n if (!user) {\n return c.json({ error: { code: \"Request_ResourceNotFound\", message: \"User not found.\" } }, 404);\n }\n\n return c.json({\n \"@odata.context\": `${baseUrl}/v1.0/$metadata#users/$entity`,\n id: user.oid,\n displayName: user.name,\n givenName: user.given_name,\n surname: user.family_name,\n mail: user.email,\n userPrincipalName: user.preferred_username,\n });\n });\n\n // ---------- Logout ----------\n\n app.get(\"/oauth2/v2.0/logout\", (c) => {\n const post_logout_redirect_uri = c.req.query(\"post_logout_redirect_uri\");\n if (post_logout_redirect_uri) {\n // Validate against registered client redirect URIs\n const allClients = ms.oauthClients.all();\n if (allClients.length > 0) {\n const allowed = allClients.some((client) =>\n matchesRedirectUri(post_logout_redirect_uri, client.redirect_uris),\n );\n if (!allowed) {\n return c.text(\"Invalid post_logout_redirect_uri\", 400);\n }\n }\n return c.redirect(post_logout_redirect_uri, 302);\n }\n return c.text(\"Logged out\", 200);\n });\n\n // ---------- Token revocation ----------\n\n app.post(\"/oauth2/v2.0/revoke\", async (c) => {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const rawText = await c.req.text();\n\n let token: string;\n if (contentType.includes(\"application/json\")) {\n try {\n const parsed = JSON.parse(rawText);\n token = typeof parsed.token === \"string\" ? parsed.token : \"\";\n } catch {\n token = \"\";\n }\n } else {\n const params = new URLSearchParams(rawText);\n token = params.get(\"token\") ?? \"\";\n }\n\n if (token && tokenMap) {\n tokenMap.delete(token);\n }\n\n // Also check refresh tokens\n if (token) {\n getRefreshTokens(store).delete(token);\n }\n\n return c.body(null, 200);\n });\n}\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids).map((id) => this.items.get(id)!).filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n}\n","import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport { authMiddleware, type AuthFallback, type TokenMap, type AppKeyResolver, type AppEnv } from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://emulate.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404\n )\n );\n\n return { app, store, webhooks, port, baseUrl, tokenMap };\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(event: string, action: string | undefined, payload: unknown, owner: string, repo?: string): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return (\n event === \"ping\" ||\n s.events.includes(\"*\") ||\n s.events.includes(event)\n );\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ErrorHandler, MiddlewareHandler } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Hono routes handler throws to the app error handler, not to outer middleware try/catch.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"hono\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(\n Buffer.from(payloadB64, \"base64url\").toString()\n );\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401\n );\n }\n await next();\n };\n}\n","const isDebug = typeof process !== \"undefined\" && (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"hono\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst FONTS: Record<string, Buffer> = {\n \"geist-sans.woff2\": readFileSync(join(__dirname, \"fonts\", \"geist-sans.woff2\")),\n \"GeistPixel-Square.woff2\": readFileSync(join(__dirname, \"fonts\", \"GeistPixel-Square.woff2\")),\n};\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n const buf = FONTS[name];\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n}\n","import type { Context } from \"hono\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(\n c: Context,\n totalCount: number,\n page: number,\n perPage: number\n): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","export function escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"'\");\n}\n\nconst CSS = `\n@font-face{\n font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;\n src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');\n}\n@font-face{\n font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;\n src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');\n}\n*{box-sizing:border-box;margin:0;padding:0}\nbody{\n font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;\n background:#000;color:#33ff00;min-height:100vh;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n}\n.emu-bar{\n border-bottom:1px solid #0a3300;padding:10px 20px;\n display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;\n}\n.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}\n.emu-bar-links{margin-left:auto;display:flex;gap:16px;}\n.emu-bar-links a{\n color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;\n}\n.emu-bar-links a:hover{color:#33ff00;}\n.emu-bar-links a .full{display:inline;}\n.emu-bar-links a .short{display:none;}\n@media(max-width:600px){\n .emu-bar-links a .full{display:none;}\n .emu-bar-links a .short{display:inline;}\n}\n\n.content{\n display:flex;align-items:center;justify-content:center;\n min-height:calc(100vh - 42px);padding:24px 16px;\n}\n.content-inner{width:100%;max-width:420px;}\n.card-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;\n}\n.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}\n.powered-by{\n position:fixed;bottom:0;left:0;right:0;\n text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;\n font-family:'Geist Pixel',monospace;\n}\n.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.powered-by a:hover{color:#33ff00;}\n\n.error-title{\n font-family:'Geist Pixel',monospace;\n color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;\n}\n.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}\n.error-card{text-align:center;}\n\n.user-form{margin-bottom:8px;}\n.user-form:last-of-type{margin-bottom:0;}\n.user-btn{\n width:100%;display:flex;align-items:center;gap:12px;\n padding:10px 12px;border:1px solid #0a3300;border-radius:8px;\n background:#000;color:inherit;cursor:pointer;text-align:left;\n font:inherit;transition:border-color .15s;\n}\n.user-btn:hover{border-color:#33ff00;}\n.avatar{\n width:36px;height:36px;border-radius:50%;\n background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.user-text{min-width:0;}\n.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}\n.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}\n.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}\n\n.settings-layout{\n max-width:920px;margin:0 auto;padding:28px 20px;\n display:flex;gap:28px;\n}\n.settings-sidebar{width:200px;flex-shrink:0;}\n.settings-sidebar a{\n display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;\n text-decoration:none;font-size:.8125rem;transition:color .15s;\n}\n.settings-sidebar a:hover{color:#33ff00;}\n.settings-sidebar a.active{color:#33ff00;font-weight:600;}\n.settings-main{flex:1;min-width:0;}\n\n.s-card{\n padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;\n}\n.s-card:last-child{border-bottom:none;}\n.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}\n.s-icon{\n width:42px;height:42px;border-radius:8px;\n background:#0a3300;display:flex;align-items:center;justify-content:center;\n font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.s-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.25rem;font-weight:600;color:#33ff00;\n}\n.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.section-heading{\n font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;\n display:flex;align-items:center;justify-content:space-between;\n}\n.perm-list{list-style:none;}\n.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}\n.check{color:#33ff00;}\n.org-row{\n display:flex;align-items:center;gap:8px;padding:7px 0;\n border-bottom:1px solid #0a3300;font-size:.8125rem;\n}\n.org-row:last-child{border-bottom:none;}\n.org-icon{\n width:22px;height:22px;border-radius:4px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;\n font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.org-name{font-weight:600;color:#33ff00;}\n.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}\n.badge-granted{background:#0a3300;color:#33ff00;}\n.badge-denied{background:#1a0a0a;color:#ff4444;}\n.badge-requested{background:#0a3300;color:#1a8c00;}\n.btn-revoke{\n display:inline-block;padding:5px 14px;border-radius:6px;\n border:1px solid #0a3300;background:transparent;color:#ff4444;\n font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;\n}\n.btn-revoke:hover{border-color:#ff4444;}\n.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <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>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(\n title: string,\n subtitle: string,\n body: string,\n service?: string\n): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(\n title: string,\n sidebarHtml: string,\n bodyHtml: string,\n service?: string\n): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name\n ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>`\n : \"\";\n const emailLine = opts.email\n ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>`\n : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import type { Hono } from \"hono\";\nimport type { ServicePlugin, Store, WebhookDispatcher, TokenMap, AppEnv, RouteContext } from \"@emulators/core\";\nimport { getMicrosoftStore } from \"./store.js\";\nimport { generateOid, DEFAULT_TENANT_ID } from \"./helpers.js\";\nimport { oauthRoutes } from \"./routes/oauth.js\";\n\nexport { getMicrosoftStore, type MicrosoftStore } from \"./store.js\";\nexport * from \"./entities.js\";\n\n\nexport interface MicrosoftSeedConfig {\n users?: Array<{\n email: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n tenant_id?: string;\n }>;\n oauth_clients?: Array<{\n client_id: string;\n client_secret: string;\n name: string;\n redirect_uris: string[];\n tenant_id?: string;\n }>;\n}\n\nfunction seedDefaults(store: Store, _baseUrl: string): void {\n const ms = getMicrosoftStore(store);\n\n ms.users.insert({\n oid: generateOid(),\n email: \"testuser@outlook.com\",\n name: \"Test User\",\n given_name: \"Test\",\n family_name: \"User\",\n email_verified: true,\n tenant_id: DEFAULT_TENANT_ID,\n preferred_username: \"testuser@outlook.com\",\n });\n}\n\nexport function seedFromConfig(store: Store, _baseUrl: string, config: MicrosoftSeedConfig): void {\n const ms = getMicrosoftStore(store);\n\n if (config.users) {\n for (const u of config.users) {\n const existing = ms.users.findOneBy(\"email\", u.email);\n if (existing) continue;\n\n const nameParts = (u.name ?? \"\").split(/\\s+/);\n ms.users.insert({\n oid: generateOid(),\n email: u.email,\n name: u.name ?? u.email.split(\"@\")[0],\n given_name: u.given_name ?? nameParts[0] ?? \"\",\n family_name: u.family_name ?? nameParts.slice(1).join(\" \") ?? \"\",\n email_verified: true,\n tenant_id: u.tenant_id ?? DEFAULT_TENANT_ID,\n preferred_username: u.email,\n });\n }\n }\n\n if (config.oauth_clients) {\n for (const client of config.oauth_clients) {\n const existing = ms.oauthClients.findOneBy(\"client_id\", client.client_id);\n if (existing) continue;\n ms.oauthClients.insert({\n client_id: client.client_id,\n client_secret: client.client_secret,\n name: client.name,\n redirect_uris: client.redirect_uris,\n tenant_id: client.tenant_id ?? DEFAULT_TENANT_ID,\n });\n }\n }\n}\n\nexport const microsoftPlugin: ServicePlugin = {\n name: \"microsoft\",\n register(app: Hono<AppEnv>, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void {\n const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap };\n oauthRoutes(ctx);\n },\n seed(store: Store, baseUrl: string): void {\n seedDefaults(store, baseUrl);\n },\n};\n\nexport default microsoftPlugin;\n"],"mappings":";AAQO,SAAS,kBAAkB,OAA8B;AAC9D,SAAO;AAAA,IACL,OAAO,MAAM,WAA0B,mBAAmB,CAAC,OAAO,OAAO,CAAC;AAAA,IAC1E,cAAc,MAAM,WAAiC,2BAA2B,CAAC,WAAW,CAAC;AAAA,EAC/F;AACF;;;ACbA,SAAS,kBAAkB;AAGpB,IAAM,oBAAoB;AAK1B,SAAS,cAAsB;AACpC,SAAO,WAAW;AACpB;;;ACVA,SAAS,YAAY,mBAAmB;AACxC,SAAS,SAAS,WAAW,uBAAuB;;;AEDpD,SAAS,YAAY;AACrB,SAAS,YAAY;AGArB,SAAS,WAAW,mBAAmB;AEDvC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;AGF9B,SAAS,uBAAuB;ANsCzB,SAAS,mBAAmB,kBAA8C;AAC/E,SAAO,OAAO,GAAG,SAAS;AACxB,QAAI,kBAAkB;AACpB,QAAE,IAAI,WAAW,gBAAgB;IACnC;AACA,UAAM,KAAK;EACb;AACF;AAEO,IAAM,eAAkC,mBAAmB;AE/ClE,IAAM,UAAU,OAAO,YAAY,gBAAgB,QAAQ,IAAI,UAAU,OAAO,QAAQ,IAAI,UAAU,UAAU,QAAQ,IAAI,kBAAkB;AAEvI,SAAS,MAAM,UAAkB,MAAuB;AAC7D,MAAI,SAAS;AACX,YAAQ,IAAI,IAAI,KAAK,KAAK,GAAG,IAAI;EACnC;AACF;ACAA,IAAM,YAAY,QAAQ,cAAc,YAAY,GAAG,CAAC;AAExD,IAAM,QAAgC;EACpC,oBAAoB,aAAa,KAAK,WAAW,SAAS,kBAAkB,CAAC;EAC7E,2BAA2B,aAAa,KAAK,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AAAA,IACH;AAAA,EACF;AACF;AAEO,IAAM,kBAAiC;AAAA,EAC5C,MAAM;AAAA,EACN,SAAS,KAAmB,OAAc,UAA6B,SAAiB,UAA2B;AACjH,UAAM,MAAoB,EAAE,KAAK,OAAO,UAAU,SAAS,SAAS;AACpE,gBAAY,GAAG;AAAA,EACjB;AAAA,EACA,KAAK,OAAc,SAAuB;AACxC,iBAAa,OAAO,OAAO;AAAA,EAC7B;AACF;AAEA,IAAO,gBAAQ;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@emulators/microsoft",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://emulate.dev",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/vercel-labs/emulate.git",
|
|
18
|
+
"directory": "packages/@emulators/microsoft"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/vercel-labs/emulate/issues"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"hono": "^4",
|
|
31
|
+
"jose": "^6",
|
|
32
|
+
"@emulators/core": "0.3.0"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"tsup": "^8",
|
|
36
|
+
"typescript": "^5.7",
|
|
37
|
+
"vitest": "^4.1.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup --clean",
|
|
41
|
+
"dev": "tsup --watch",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"clean": "rm -rf dist .turbo"
|
|
44
|
+
}
|
|
45
|
+
}
|