@emulators/apple 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 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
@@ -0,0 +1,47 @@
1
+ import { Entity, Collection, Store, ServicePlugin } from '@emulators/core';
2
+
3
+ interface AppleUser extends Entity {
4
+ uid: string;
5
+ email: string;
6
+ name: string;
7
+ given_name: string;
8
+ family_name: string;
9
+ email_verified: boolean;
10
+ is_private_email: boolean;
11
+ private_relay_email: string | null;
12
+ real_user_status: number;
13
+ }
14
+ interface AppleOAuthClient extends Entity {
15
+ client_id: string;
16
+ team_id: string;
17
+ key_id: string;
18
+ name: string;
19
+ redirect_uris: string[];
20
+ }
21
+
22
+ interface AppleStore {
23
+ users: Collection<AppleUser>;
24
+ oauthClients: Collection<AppleOAuthClient>;
25
+ }
26
+ declare function getAppleStore(store: Store): AppleStore;
27
+
28
+ interface AppleSeedConfig {
29
+ users?: Array<{
30
+ email: string;
31
+ name?: string;
32
+ given_name?: string;
33
+ family_name?: string;
34
+ is_private_email?: boolean;
35
+ }>;
36
+ oauth_clients?: Array<{
37
+ client_id: string;
38
+ team_id: string;
39
+ key_id?: string;
40
+ name: string;
41
+ redirect_uris: string[];
42
+ }>;
43
+ }
44
+ declare function seedFromConfig(store: Store, _baseUrl: string, config: AppleSeedConfig): void;
45
+ declare const applePlugin: ServicePlugin;
46
+
47
+ export { type AppleOAuthClient, type AppleSeedConfig, type AppleStore, type AppleUser, applePlugin, applePlugin as default, getAppleStore, seedFromConfig };
package/dist/index.js ADDED
@@ -0,0 +1,633 @@
1
+ // src/store.ts
2
+ function getAppleStore(store) {
3
+ return {
4
+ users: store.collection("apple.users", ["uid", "email"]),
5
+ oauthClients: store.collection("apple.oauth_clients", ["client_id"])
6
+ };
7
+ }
8
+
9
+ // src/helpers.ts
10
+ import { randomBytes } from "crypto";
11
+ function generateAppleUid() {
12
+ const prefix = randomBytes(3).toString("hex").toUpperCase();
13
+ const middle = randomBytes(16).toString("hex");
14
+ const suffix = randomBytes(2).toString("hex").toUpperCase();
15
+ return `${prefix}.${middle}.${suffix}`;
16
+ }
17
+ function generatePrivateRelayEmail() {
18
+ const id = randomBytes(12).toString("hex");
19
+ return `${id}@privaterelay.appleid.com`;
20
+ }
21
+
22
+ // src/routes/oauth.ts
23
+ import { randomBytes as randomBytes2 } from "crypto";
24
+ import { SignJWT, exportJWK, generateKeyPair } from "jose";
25
+
26
+ // ../core/dist/index.js
27
+ import { Hono } from "hono";
28
+ import { cors } from "hono/cors";
29
+ import { jwtVerify, importPKCS8 } from "jose";
30
+ import { readFileSync } from "fs";
31
+ import { fileURLToPath } from "url";
32
+ import { dirname, join } from "path";
33
+ function createErrorHandler(documentationUrl) {
34
+ return async (c, next) => {
35
+ if (documentationUrl) {
36
+ c.set("docsUrl", documentationUrl);
37
+ }
38
+ await next();
39
+ };
40
+ }
41
+ var errorHandler = createErrorHandler();
42
+ var isDebug = typeof process !== "undefined" && (process.env.DEBUG === "1" || process.env.DEBUG === "true" || process.env.EMULATE_DEBUG === "1");
43
+ function debug(label, ...args) {
44
+ if (isDebug) {
45
+ console.log(`[${label}]`, ...args);
46
+ }
47
+ }
48
+ var __dirname = dirname(fileURLToPath(import.meta.url));
49
+ var FONTS = {
50
+ "geist-sans.woff2": readFileSync(join(__dirname, "fonts", "geist-sans.woff2")),
51
+ "GeistPixel-Square.woff2": readFileSync(join(__dirname, "fonts", "GeistPixel-Square.woff2"))
52
+ };
53
+ function escapeHtml(s) {
54
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
55
+ }
56
+ function escapeAttr(s) {
57
+ return escapeHtml(s).replace(/'/g, "&#39;");
58
+ }
59
+ var CSS = `
60
+ @font-face{
61
+ font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;
62
+ src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');
63
+ }
64
+ @font-face{
65
+ font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;
66
+ src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');
67
+ }
68
+ *{box-sizing:border-box;margin:0;padding:0}
69
+ body{
70
+ font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;
71
+ background:#000;color:#33ff00;min-height:100vh;
72
+ -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;
73
+ }
74
+ .emu-bar{
75
+ border-bottom:1px solid #0a3300;padding:10px 20px;
76
+ display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;
77
+ }
78
+ .emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}
79
+ .emu-bar-links{margin-left:auto;display:flex;gap:16px;}
80
+ .emu-bar-links a{
81
+ color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;
82
+ }
83
+ .emu-bar-links a:hover{color:#33ff00;}
84
+ .emu-bar-links a .full{display:inline;}
85
+ .emu-bar-links a .short{display:none;}
86
+ @media(max-width:600px){
87
+ .emu-bar-links a .full{display:none;}
88
+ .emu-bar-links a .short{display:inline;}
89
+ }
90
+
91
+ .content{
92
+ display:flex;align-items:center;justify-content:center;
93
+ min-height:calc(100vh - 42px);padding:24px 16px;
94
+ }
95
+ .content-inner{width:100%;max-width:420px;}
96
+ .card-title{
97
+ font-family:'Geist Pixel',monospace;
98
+ font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;
99
+ }
100
+ .card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}
101
+ .powered-by{
102
+ position:fixed;bottom:0;left:0;right:0;
103
+ text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;
104
+ font-family:'Geist Pixel',monospace;
105
+ }
106
+ .powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}
107
+ .powered-by a:hover{color:#33ff00;}
108
+
109
+ .error-title{
110
+ font-family:'Geist Pixel',monospace;
111
+ color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;
112
+ }
113
+ .error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}
114
+ .error-card{text-align:center;}
115
+
116
+ .user-form{margin-bottom:8px;}
117
+ .user-form:last-of-type{margin-bottom:0;}
118
+ .user-btn{
119
+ width:100%;display:flex;align-items:center;gap:12px;
120
+ padding:10px 12px;border:1px solid #0a3300;border-radius:8px;
121
+ background:#000;color:inherit;cursor:pointer;text-align:left;
122
+ font:inherit;transition:border-color .15s;
123
+ }
124
+ .user-btn:hover{border-color:#33ff00;}
125
+ .avatar{
126
+ width:36px;height:36px;border-radius:50%;
127
+ background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;
128
+ display:flex;align-items:center;justify-content:center;flex-shrink:0;
129
+ font-family:'Geist Pixel',monospace;
130
+ }
131
+ .user-text{min-width:0;}
132
+ .user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}
133
+ .user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}
134
+ .user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}
135
+
136
+ .settings-layout{
137
+ max-width:920px;margin:0 auto;padding:28px 20px;
138
+ display:flex;gap:28px;
139
+ }
140
+ .settings-sidebar{width:200px;flex-shrink:0;}
141
+ .settings-sidebar a{
142
+ display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;
143
+ text-decoration:none;font-size:.8125rem;transition:color .15s;
144
+ }
145
+ .settings-sidebar a:hover{color:#33ff00;}
146
+ .settings-sidebar a.active{color:#33ff00;font-weight:600;}
147
+ .settings-main{flex:1;min-width:0;}
148
+
149
+ .s-card{
150
+ padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;
151
+ }
152
+ .s-card:last-child{border-bottom:none;}
153
+ .s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}
154
+ .s-icon{
155
+ width:42px;height:42px;border-radius:8px;
156
+ background:#0a3300;display:flex;align-items:center;justify-content:center;
157
+ font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;
158
+ font-family:'Geist Pixel',monospace;
159
+ }
160
+ .s-title{
161
+ font-family:'Geist Pixel',monospace;
162
+ font-size:1.25rem;font-weight:600;color:#33ff00;
163
+ }
164
+ .s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}
165
+ .section-heading{
166
+ font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;
167
+ display:flex;align-items:center;justify-content:space-between;
168
+ }
169
+ .perm-list{list-style:none;}
170
+ .perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}
171
+ .check{color:#33ff00;}
172
+ .org-row{
173
+ display:flex;align-items:center;gap:8px;padding:7px 0;
174
+ border-bottom:1px solid #0a3300;font-size:.8125rem;
175
+ }
176
+ .org-row:last-child{border-bottom:none;}
177
+ .org-icon{
178
+ width:22px;height:22px;border-radius:4px;background:#0a3300;
179
+ display:flex;align-items:center;justify-content:center;
180
+ font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;
181
+ font-family:'Geist Pixel',monospace;
182
+ }
183
+ .org-name{font-weight:600;color:#33ff00;}
184
+ .badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}
185
+ .badge-granted{background:#0a3300;color:#33ff00;}
186
+ .badge-denied{background:#1a0a0a;color:#ff4444;}
187
+ .badge-requested{background:#0a3300;color:#1a8c00;}
188
+ .btn-revoke{
189
+ display:inline-block;padding:5px 14px;border-radius:6px;
190
+ border:1px solid #0a3300;background:transparent;color:#ff4444;
191
+ font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;
192
+ }
193
+ .btn-revoke:hover{border-color:#ff4444;}
194
+ .info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}
195
+ .app-link{
196
+ display:flex;align-items:center;gap:12px;padding:12px;
197
+ border:1px solid #0a3300;border-radius:8px;background:#000;
198
+ text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;
199
+ }
200
+ .app-link:hover{border-color:#33ff00;}
201
+ .app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}
202
+ .app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}
203
+ .empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}
204
+ `;
205
+ var POWERED_BY = `<div class="powered-by">Powered by <a href="https://emulate.dev" target="_blank" rel="noopener">emulate</a></div>`;
206
+ function emuBar(service) {
207
+ const title = service ? `${escapeHtml(service)} Emulator` : "Emulator";
208
+ return `<div class="emu-bar">
209
+ <span class="emu-bar-title">${title}</span>
210
+ <nav class="emu-bar-links">
211
+ <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>
212
+ <a href="https://github.com/vercel-labs/emulate" target="_blank" rel="noopener"><span class="full">Source Code</span><span class="short">Source</span></a>
213
+ <a href="https://emulate.dev" target="_blank" rel="noopener"><span class="full">Learn More</span><span class="short">Learn</span></a>
214
+ </nav>
215
+ </div>`;
216
+ }
217
+ function head(title) {
218
+ return `<!DOCTYPE html>
219
+ <html lang="en">
220
+ <head>
221
+ <meta charset="utf-8"/>
222
+ <meta name="viewport" content="width=device-width,initial-scale=1"/>
223
+ <title>${escapeHtml(title)} | emulate</title>
224
+ <style>${CSS}</style>
225
+ </head>`;
226
+ }
227
+ function renderCardPage(title, subtitle, body, service) {
228
+ return `${head(title)}
229
+ <body>
230
+ ${emuBar(service)}
231
+ <div class="content">
232
+ <div class="content-inner">
233
+ <div class="card-title">${escapeHtml(title)}</div>
234
+ <div class="card-subtitle">${subtitle}</div>
235
+ ${body}
236
+ </div>
237
+ </div>
238
+ ${POWERED_BY}
239
+ </body></html>`;
240
+ }
241
+ function renderErrorPage(title, message, service) {
242
+ return `${head(title)}
243
+ <body>
244
+ ${emuBar(service)}
245
+ <div class="content">
246
+ <div class="content-inner error-card">
247
+ <div class="error-title">${escapeHtml(title)}</div>
248
+ <div class="error-msg">${escapeHtml(message)}</div>
249
+ </div>
250
+ </div>
251
+ ${POWERED_BY}
252
+ </body></html>`;
253
+ }
254
+ function renderUserButton(opts) {
255
+ const hiddens = Object.entries(opts.hiddenFields).map(([k, v]) => `<input type="hidden" name="${escapeAttr(k)}" value="${escapeAttr(v)}"/>`).join("");
256
+ const nameLine = opts.name ? `<div class="user-meta">${escapeHtml(opts.name)}</div>` : "";
257
+ const emailLine = opts.email ? `<div class="user-email">${escapeHtml(opts.email)}</div>` : "";
258
+ return `<form class="user-form" method="post" action="${escapeAttr(opts.formAction)}">
259
+ ${hiddens}
260
+ <button type="submit" class="user-btn">
261
+ <span class="avatar">${escapeHtml(opts.letter)}</span>
262
+ <span class="user-text">
263
+ <span class="user-login">${escapeHtml(opts.login)}</span>
264
+ ${nameLine}${emailLine}
265
+ </span>
266
+ </button>
267
+ </form>`;
268
+ }
269
+ function normalizeUri(uri) {
270
+ try {
271
+ const u = new URL(uri);
272
+ return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
273
+ } catch {
274
+ return uri.replace(/\/+$/, "").split("?")[0];
275
+ }
276
+ }
277
+ function matchesRedirectUri(incoming, registered) {
278
+ const normalized = normalizeUri(incoming);
279
+ return registered.some((r) => normalizeUri(r) === normalized);
280
+ }
281
+ function bodyStr(v) {
282
+ if (typeof v === "string") return v;
283
+ if (Array.isArray(v) && typeof v[0] === "string") return v[0];
284
+ return "";
285
+ }
286
+
287
+ // src/routes/oauth.ts
288
+ var keyPairPromise = generateKeyPair("RS256");
289
+ var KID = "emulate-apple-1";
290
+ var PENDING_CODE_TTL_MS = 5 * 60 * 1e3;
291
+ function getPendingCodes(store) {
292
+ let map = store.getData("apple.oauth.pendingCodes");
293
+ if (!map) {
294
+ map = /* @__PURE__ */ new Map();
295
+ store.setData("apple.oauth.pendingCodes", map);
296
+ }
297
+ return map;
298
+ }
299
+ function getRefreshTokens(store) {
300
+ let map = store.getData("apple.oauth.refreshTokens");
301
+ if (!map) {
302
+ map = /* @__PURE__ */ new Map();
303
+ store.setData("apple.oauth.refreshTokens", map);
304
+ }
305
+ return map;
306
+ }
307
+ function getFirstAuthTracker(store) {
308
+ let set = store.getData("apple.oauth.firstAuthTracker");
309
+ if (!set) {
310
+ set = /* @__PURE__ */ new Set();
311
+ store.setData("apple.oauth.firstAuthTracker", set);
312
+ }
313
+ return set;
314
+ }
315
+ function isPendingCodeExpired(p) {
316
+ return Date.now() - p.created_at > PENDING_CODE_TTL_MS;
317
+ }
318
+ var SERVICE_LABEL = "Apple";
319
+ async function createIdToken(user, clientId, nonce, baseUrl) {
320
+ const { privateKey } = await keyPairPromise;
321
+ const email = user.is_private_email && user.private_relay_email ? user.private_relay_email : user.email;
322
+ const now = Math.floor(Date.now() / 1e3);
323
+ const builder = new SignJWT({
324
+ sub: user.uid,
325
+ email,
326
+ email_verified: String(user.email_verified),
327
+ is_private_email: String(user.is_private_email),
328
+ real_user_status: user.real_user_status,
329
+ nonce_supported: true,
330
+ auth_time: now,
331
+ ...nonce ? { nonce } : {}
332
+ }).setProtectedHeader({ alg: "RS256", kid: KID, typ: "JWT" }).setIssuer(baseUrl).setAudience(clientId).setIssuedAt(now).setExpirationTime("1h");
333
+ return builder.sign(privateKey);
334
+ }
335
+ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
336
+ const as = getAppleStore(store);
337
+ app.get("/.well-known/openid-configuration", (c) => {
338
+ return c.json({
339
+ issuer: baseUrl,
340
+ authorization_endpoint: `${baseUrl}/auth/authorize`,
341
+ token_endpoint: `${baseUrl}/auth/token`,
342
+ revocation_endpoint: `${baseUrl}/auth/revoke`,
343
+ jwks_uri: `${baseUrl}/auth/keys`,
344
+ response_types_supported: ["code"],
345
+ response_modes_supported: ["query", "fragment", "form_post"],
346
+ subject_types_supported: ["pairwise"],
347
+ id_token_signing_alg_values_supported: ["RS256"],
348
+ scopes_supported: ["openid", "email", "name"],
349
+ token_endpoint_auth_methods_supported: ["client_secret_post"],
350
+ claims_supported: [
351
+ "aud",
352
+ "email",
353
+ "email_verified",
354
+ "exp",
355
+ "iat",
356
+ "is_private_email",
357
+ "iss",
358
+ "nonce",
359
+ "nonce_supported",
360
+ "real_user_status",
361
+ "sub",
362
+ "transfer_sub"
363
+ ]
364
+ });
365
+ });
366
+ app.get("/auth/keys", async (c) => {
367
+ const { publicKey } = await keyPairPromise;
368
+ const jwk = await exportJWK(publicKey);
369
+ return c.json({
370
+ keys: [{
371
+ ...jwk,
372
+ kid: KID,
373
+ use: "sig",
374
+ alg: "RS256"
375
+ }]
376
+ });
377
+ });
378
+ app.get("/auth/authorize", (c) => {
379
+ const client_id = c.req.query("client_id") ?? "";
380
+ const redirect_uri = c.req.query("redirect_uri") ?? "";
381
+ const scope = c.req.query("scope") ?? "";
382
+ const state = c.req.query("state") ?? "";
383
+ const nonce = c.req.query("nonce") ?? "";
384
+ const response_mode = c.req.query("response_mode") ?? "query";
385
+ const clientsConfigured = as.oauthClients.all().length > 0;
386
+ let clientName = "";
387
+ if (clientsConfigured) {
388
+ const client = as.oauthClients.findOneBy("client_id", client_id);
389
+ if (!client) {
390
+ return c.html(
391
+ renderErrorPage("Application not found", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),
392
+ 400
393
+ );
394
+ }
395
+ if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {
396
+ return c.html(
397
+ renderErrorPage("Redirect URI mismatch", "The redirect_uri is not registered for this application.", SERVICE_LABEL),
398
+ 400
399
+ );
400
+ }
401
+ clientName = client.name;
402
+ }
403
+ const subtitleText = clientName ? `Sign in to <strong>${escapeHtml(clientName)}</strong> with your Apple ID.` : "Choose a seeded user to continue.";
404
+ const users = as.users.all();
405
+ const userButtons = users.map((user) => {
406
+ return renderUserButton({
407
+ letter: (user.email[0] ?? "?").toUpperCase(),
408
+ login: user.email,
409
+ name: user.name,
410
+ email: user.email,
411
+ formAction: "/auth/authorize/callback",
412
+ hiddenFields: {
413
+ email: user.email,
414
+ redirect_uri,
415
+ scope,
416
+ state,
417
+ nonce,
418
+ client_id,
419
+ response_mode
420
+ }
421
+ });
422
+ }).join("\n");
423
+ const body = users.length === 0 ? '<p class="empty">No users in the emulator store.</p>' : userButtons;
424
+ return c.html(renderCardPage("Sign in with Apple", subtitleText, body, SERVICE_LABEL));
425
+ });
426
+ app.post("/auth/authorize/callback", async (c) => {
427
+ const body = await c.req.parseBody();
428
+ const email = bodyStr(body.email);
429
+ const redirect_uri = bodyStr(body.redirect_uri);
430
+ const scope = bodyStr(body.scope);
431
+ const state = bodyStr(body.state);
432
+ const client_id = bodyStr(body.client_id);
433
+ const nonce = bodyStr(body.nonce);
434
+ const response_mode = bodyStr(body.response_mode) || "query";
435
+ const code = randomBytes2(20).toString("hex");
436
+ getPendingCodes(store).set(code, {
437
+ email,
438
+ scope,
439
+ redirectUri: redirect_uri,
440
+ clientId: client_id,
441
+ nonce: nonce || null,
442
+ responseMode: response_mode,
443
+ created_at: Date.now()
444
+ });
445
+ debug("apple.oauth", `[Apple callback] code=${code.slice(0, 8)}... email=${email}`);
446
+ const tracker = getFirstAuthTracker(store);
447
+ const pairKey = `${email}:${client_id}`;
448
+ const isFirstAuth = !tracker.has(pairKey);
449
+ if (isFirstAuth) {
450
+ tracker.add(pairKey);
451
+ }
452
+ let userJson;
453
+ if (isFirstAuth) {
454
+ const user = as.users.findOneBy("email", email);
455
+ if (user) {
456
+ userJson = JSON.stringify({
457
+ name: { firstName: user.given_name, lastName: user.family_name },
458
+ email: user.email
459
+ });
460
+ }
461
+ }
462
+ if (response_mode === "form_post") {
463
+ const html = `<!DOCTYPE html>
464
+ <html>
465
+ <head><title>Submit</title></head>
466
+ <body onload="document.forms[0].submit()">
467
+ <form method="POST" action="${escapeAttr(redirect_uri)}">
468
+ <input type="hidden" name="code" value="${escapeAttr(code)}" />
469
+ <input type="hidden" name="state" value="${escapeAttr(state)}" />${userJson ? `
470
+ <input type="hidden" name="user" value="${escapeAttr(userJson)}" />` : ""}
471
+ </form>
472
+ </body>
473
+ </html>`;
474
+ return c.html(html);
475
+ }
476
+ const url = new URL(redirect_uri);
477
+ url.searchParams.set("code", code);
478
+ if (state) url.searchParams.set("state", state);
479
+ if (userJson) url.searchParams.set("user", userJson);
480
+ return c.redirect(url.toString(), 302);
481
+ });
482
+ app.post("/auth/token", async (c) => {
483
+ const rawText = await c.req.text();
484
+ const body = Object.fromEntries(new URLSearchParams(rawText));
485
+ const grant_type = body.grant_type ?? "";
486
+ const code = body.code ?? "";
487
+ const client_id = body.client_id ?? "";
488
+ const refresh_token = body.refresh_token ?? "";
489
+ if (grant_type === "authorization_code") {
490
+ const pendingMap = getPendingCodes(store);
491
+ const pending = pendingMap.get(code);
492
+ if (!pending) {
493
+ return c.json({ error: "invalid_grant", error_description: "The code is incorrect or expired." }, 400);
494
+ }
495
+ if (isPendingCodeExpired(pending)) {
496
+ pendingMap.delete(code);
497
+ return c.json({ error: "invalid_grant", error_description: "The code is incorrect or expired." }, 400);
498
+ }
499
+ pendingMap.delete(code);
500
+ const user = as.users.findOneBy("email", pending.email);
501
+ if (!user) {
502
+ return c.json({ error: "invalid_grant", error_description: "User not found." }, 400);
503
+ }
504
+ const accessToken = "apple_" + randomBytes2(20).toString("base64url");
505
+ const refreshToken = "r_apple_" + randomBytes2(20).toString("base64url");
506
+ const scopes = pending.scope ? pending.scope.split(/\s+/).filter(Boolean) : [];
507
+ if (tokenMap) {
508
+ tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });
509
+ }
510
+ getRefreshTokens(store).set(refreshToken, {
511
+ email: user.email,
512
+ clientId: pending.clientId,
513
+ scope: pending.scope,
514
+ nonce: pending.nonce
515
+ });
516
+ const idToken = await createIdToken(user, pending.clientId, pending.nonce, baseUrl);
517
+ debug("apple.oauth", `[Apple token] issued token for ${user.email}`);
518
+ return c.json({
519
+ access_token: accessToken,
520
+ token_type: "Bearer",
521
+ expires_in: 3600,
522
+ refresh_token: refreshToken,
523
+ id_token: idToken
524
+ });
525
+ }
526
+ if (grant_type === "refresh_token") {
527
+ const refreshMap = getRefreshTokens(store);
528
+ const stored = refreshMap.get(refresh_token);
529
+ if (!stored) {
530
+ return c.json({ error: "invalid_grant", error_description: "The refresh_token is invalid." }, 400);
531
+ }
532
+ const user = as.users.findOneBy("email", stored.email);
533
+ if (!user) {
534
+ return c.json({ error: "invalid_grant", error_description: "User not found." }, 400);
535
+ }
536
+ const accessToken = "apple_" + randomBytes2(20).toString("base64url");
537
+ const scopes = stored.scope ? stored.scope.split(/\s+/).filter(Boolean) : [];
538
+ if (tokenMap) {
539
+ tokenMap.set(accessToken, { login: user.email, id: user.id, scopes });
540
+ }
541
+ const idToken = await createIdToken(user, stored.clientId || client_id, stored.nonce, baseUrl);
542
+ debug("apple.oauth", `[Apple refresh] issued new token for ${user.email}`);
543
+ return c.json({
544
+ access_token: accessToken,
545
+ token_type: "Bearer",
546
+ expires_in: 3600,
547
+ id_token: idToken
548
+ });
549
+ }
550
+ return c.json({ error: "unsupported_grant_type", error_description: "Only authorization_code and refresh_token are supported." }, 400);
551
+ });
552
+ app.post("/auth/revoke", async (c) => {
553
+ const rawText = await c.req.text();
554
+ const params = new URLSearchParams(rawText);
555
+ const token = params.get("token") ?? "";
556
+ if (token && tokenMap) {
557
+ tokenMap.delete(token);
558
+ }
559
+ if (token) {
560
+ getRefreshTokens(store).delete(token);
561
+ }
562
+ return c.body(null, 200);
563
+ });
564
+ }
565
+
566
+ // src/index.ts
567
+ function seedDefaults(store, _baseUrl) {
568
+ const as = getAppleStore(store);
569
+ as.users.insert({
570
+ uid: generateAppleUid(),
571
+ email: "testuser@icloud.com",
572
+ name: "Test User",
573
+ given_name: "Test",
574
+ family_name: "User",
575
+ email_verified: true,
576
+ is_private_email: false,
577
+ private_relay_email: null,
578
+ real_user_status: 2
579
+ });
580
+ }
581
+ function seedFromConfig(store, _baseUrl, config) {
582
+ const as = getAppleStore(store);
583
+ if (config.users) {
584
+ for (const u of config.users) {
585
+ const existing = as.users.findOneBy("email", u.email);
586
+ if (existing) continue;
587
+ const nameParts = (u.name ?? "").split(/\s+/);
588
+ const isPrivate = u.is_private_email ?? false;
589
+ as.users.insert({
590
+ uid: generateAppleUid(),
591
+ email: u.email,
592
+ name: u.name ?? u.email.split("@")[0],
593
+ given_name: u.given_name ?? nameParts[0] ?? "",
594
+ family_name: u.family_name ?? nameParts.slice(1).join(" ") ?? "",
595
+ email_verified: true,
596
+ is_private_email: isPrivate,
597
+ private_relay_email: isPrivate ? generatePrivateRelayEmail() : null,
598
+ real_user_status: 2
599
+ });
600
+ }
601
+ }
602
+ if (config.oauth_clients) {
603
+ for (const client of config.oauth_clients) {
604
+ const existing = as.oauthClients.findOneBy("client_id", client.client_id);
605
+ if (existing) continue;
606
+ as.oauthClients.insert({
607
+ client_id: client.client_id,
608
+ team_id: client.team_id,
609
+ key_id: client.key_id ?? "TESTKEY001",
610
+ name: client.name,
611
+ redirect_uris: client.redirect_uris
612
+ });
613
+ }
614
+ }
615
+ }
616
+ var applePlugin = {
617
+ name: "apple",
618
+ register(app, store, webhooks, baseUrl, tokenMap) {
619
+ const ctx = { app, store, webhooks, baseUrl, tokenMap };
620
+ oauthRoutes(ctx);
621
+ },
622
+ seed(store, baseUrl) {
623
+ seedDefaults(store, baseUrl);
624
+ }
625
+ };
626
+ var index_default = applePlugin;
627
+ export {
628
+ applePlugin,
629
+ index_default as default,
630
+ getAppleStore,
631
+ seedFromConfig
632
+ };
633
+ //# 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 { AppleUser, AppleOAuthClient } from \"./entities.js\";\n\nexport interface AppleStore {\n users: Collection<AppleUser>;\n oauthClients: Collection<AppleOAuthClient>;\n}\n\nexport function getAppleStore(store: Store): AppleStore {\n return {\n users: store.collection<AppleUser>(\"apple.users\", [\"uid\", \"email\"]),\n oauthClients: store.collection<AppleOAuthClient>(\"apple.oauth_clients\", [\"client_id\"]),\n };\n}\n","import { randomBytes } from \"crypto\";\n\n/**\n * Generate a pairwise subject ID in Apple's format: \"XXXXXX.hex32.XXXX\"\n */\nexport function generateAppleUid(): string {\n const prefix = randomBytes(3).toString(\"hex\").toUpperCase();\n const middle = randomBytes(16).toString(\"hex\");\n const suffix = randomBytes(2).toString(\"hex\").toUpperCase();\n return `${prefix}.${middle}.${suffix}`;\n}\n\n/**\n * Generate a private relay email address.\n */\nexport function generatePrivateRelayEmail(): string {\n const id = randomBytes(12).toString(\"hex\");\n return `${id}@privaterelay.appleid.com`;\n}\n","import { 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 bodyStr,\n debug,\n} from \"@emulators/core\";\nimport { getAppleStore } from \"../store.js\";\nimport type { AppleUser } 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-apple-1\";\n\ntype PendingCode = {\n email: string;\n scope: string;\n redirectUri: string;\n clientId: string;\n nonce: string | null;\n responseMode: string;\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 = 5 * 60 * 1000;\n\nfunction getPendingCodes(store: Store): Map<string, PendingCode> {\n let map = store.getData<Map<string, PendingCode>>(\"apple.oauth.pendingCodes\");\n if (!map) {\n map = new Map();\n store.setData(\"apple.oauth.pendingCodes\", map);\n }\n return map;\n}\n\nfunction getRefreshTokens(store: Store): Map<string, StoredRefreshToken> {\n let map = store.getData<Map<string, StoredRefreshToken>>(\"apple.oauth.refreshTokens\");\n if (!map) {\n map = new Map();\n store.setData(\"apple.oauth.refreshTokens\", map);\n }\n return map;\n}\n\nfunction getFirstAuthTracker(store: Store): Set<string> {\n let set = store.getData<Set<string>>(\"apple.oauth.firstAuthTracker\");\n if (!set) {\n set = new Set();\n store.setData(\"apple.oauth.firstAuthTracker\", set);\n }\n return set;\n}\n\nfunction isPendingCodeExpired(p: PendingCode): boolean {\n return Date.now() - p.created_at > PENDING_CODE_TTL_MS;\n}\n\nconst SERVICE_LABEL = \"Apple\";\n\nasync function createIdToken(\n user: AppleUser,\n clientId: string,\n nonce: string | null,\n baseUrl: string,\n): Promise<string> {\n const { privateKey } = await keyPairPromise;\n\n const email = user.is_private_email && user.private_relay_email\n ? user.private_relay_email\n : user.email;\n\n const now = Math.floor(Date.now() / 1000);\n\n const builder = new SignJWT({\n sub: user.uid,\n email,\n email_verified: String(user.email_verified),\n is_private_email: String(user.is_private_email),\n real_user_status: user.real_user_status,\n nonce_supported: true,\n auth_time: now,\n ...(nonce ? { nonce } : {}),\n })\n .setProtectedHeader({ alg: \"RS256\", kid: KID, typ: \"JWT\" })\n .setIssuer(baseUrl)\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 as = getAppleStore(store);\n\n // ---------- OIDC Discovery ----------\n\n app.get(\"/.well-known/openid-configuration\", (c) => {\n return c.json({\n issuer: baseUrl,\n authorization_endpoint: `${baseUrl}/auth/authorize`,\n token_endpoint: `${baseUrl}/auth/token`,\n revocation_endpoint: `${baseUrl}/auth/revoke`,\n jwks_uri: `${baseUrl}/auth/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\", \"name\"],\n token_endpoint_auth_methods_supported: [\"client_secret_post\"],\n claims_supported: [\n \"aud\", \"email\", \"email_verified\", \"exp\", \"iat\",\n \"is_private_email\", \"iss\", \"nonce\", \"nonce_supported\",\n \"real_user_status\", \"sub\", \"transfer_sub\",\n ],\n });\n });\n\n // ---------- JWKS ----------\n\n app.get(\"/auth/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(\"/auth/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\n const clientsConfigured = as.oauthClients.all().length > 0;\n let clientName = \"\";\n if (clientsConfigured) {\n const client = as.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 Apple ID.`\n : \"Choose a seeded user to continue.\";\n\n const users = as.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: \"/auth/authorize/callback\",\n hiddenFields: {\n email: user.email,\n redirect_uri,\n scope,\n state,\n nonce,\n client_id,\n response_mode,\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 Apple\", subtitleText, body, SERVICE_LABEL));\n });\n\n // ---------- Authorization callback ----------\n\n app.post(\"/auth/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\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 responseMode: response_mode,\n created_at: Date.now(),\n });\n\n debug(\"apple.oauth\", `[Apple callback] code=${code.slice(0, 8)}... email=${email}`);\n\n // Track first authorization per user+client pair\n const tracker = getFirstAuthTracker(store);\n const pairKey = `${email}:${client_id}`;\n const isFirstAuth = !tracker.has(pairKey);\n if (isFirstAuth) {\n tracker.add(pairKey);\n }\n\n // Build user JSON blob (only on first auth)\n let userJson: string | undefined;\n if (isFirstAuth) {\n const user = as.users.findOneBy(\"email\", email as AppleUser[\"email\"]);\n if (user) {\n userJson = JSON.stringify({\n name: { firstName: user.given_name, lastName: user.family_name },\n email: user.email,\n });\n }\n }\n\n if (response_mode === \"form_post\") {\n // Return auto-submit form that POSTs to redirect_uri\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)}\" />${userJson ? `\\n<input type=\"hidden\" name=\"user\" value=\"${escapeAttr(userJson)}\" />` : \"\"}\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 if (userJson) url.searchParams.set(\"user\", userJson);\n\n return c.redirect(url.toString(), 302);\n });\n\n // ---------- Token exchange ----------\n\n app.post(\"/auth/token\", async (c) => {\n const rawText = await c.req.text();\n const body = Object.fromEntries(new URLSearchParams(rawText));\n\n const grant_type = body.grant_type ?? \"\";\n const code = body.code ?? \"\";\n const client_id = body.client_id ?? \"\";\n const refresh_token = body.refresh_token ?? \"\";\n\n if (grant_type === \"authorization_code\") {\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 // Single-use: delete immediately\n pendingMap.delete(code);\n\n const user = as.users.findOneBy(\"email\", pending.email as AppleUser[\"email\"]);\n if (!user) {\n return c.json({ error: \"invalid_grant\", error_description: \"User not found.\" }, 400);\n }\n\n const accessToken = \"apple_\" + randomBytes(20).toString(\"base64url\");\n const refreshToken = \"r_apple_\" + 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(\"apple.oauth\", `[Apple token] issued token for ${user.email}`);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: 3600,\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 = as.users.findOneBy(\"email\", stored.email as AppleUser[\"email\"]);\n if (!user) {\n return c.json({ error: \"invalid_grant\", error_description: \"User not found.\" }, 400);\n }\n\n const accessToken = \"apple_\" + 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 const idToken = await createIdToken(user, stored.clientId || client_id, stored.nonce, baseUrl);\n\n debug(\"apple.oauth\", `[Apple refresh] issued new token for ${user.email}`);\n\n // No new refresh_token for refresh grant\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: 3600,\n id_token: idToken,\n });\n }\n\n return c.json({ error: \"unsupported_grant_type\", error_description: \"Only authorization_code and refresh_token are supported.\" }, 400);\n });\n\n // ---------- Token revocation ----------\n\n app.post(\"/auth/revoke\", async (c) => {\n const rawText = await c.req.text();\n const params = new URLSearchParams(rawText);\n const token = params.get(\"token\") ?? \"\";\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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"&#39;\");\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 { getAppleStore } from \"./store.js\";\nimport { generateAppleUid, generatePrivateRelayEmail } from \"./helpers.js\";\nimport { oauthRoutes } from \"./routes/oauth.js\";\n\nexport { getAppleStore, type AppleStore } from \"./store.js\";\nexport * from \"./entities.js\";\n\nexport interface AppleSeedConfig {\n users?: Array<{\n email: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n is_private_email?: boolean;\n }>;\n oauth_clients?: Array<{\n client_id: string;\n team_id: string;\n key_id?: string;\n name: string;\n redirect_uris: string[];\n }>;\n}\n\nfunction seedDefaults(store: Store, _baseUrl: string): void {\n const as = getAppleStore(store);\n\n as.users.insert({\n uid: generateAppleUid(),\n email: \"testuser@icloud.com\",\n name: \"Test User\",\n given_name: \"Test\",\n family_name: \"User\",\n email_verified: true,\n is_private_email: false,\n private_relay_email: null,\n real_user_status: 2,\n });\n}\n\nexport function seedFromConfig(store: Store, _baseUrl: string, config: AppleSeedConfig): void {\n const as = getAppleStore(store);\n\n if (config.users) {\n for (const u of config.users) {\n const existing = as.users.findOneBy(\"email\", u.email);\n if (existing) continue;\n\n const nameParts = (u.name ?? \"\").split(/\\s+/);\n const isPrivate = u.is_private_email ?? false;\n\n as.users.insert({\n uid: generateAppleUid(),\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 is_private_email: isPrivate,\n private_relay_email: isPrivate ? generatePrivateRelayEmail() : null,\n real_user_status: 2,\n });\n }\n }\n\n if (config.oauth_clients) {\n for (const client of config.oauth_clients) {\n const existing = as.oauthClients.findOneBy(\"client_id\", client.client_id);\n if (existing) continue;\n as.oauthClients.insert({\n client_id: client.client_id,\n team_id: client.team_id,\n key_id: client.key_id ?? \"TESTKEY001\",\n name: client.name,\n redirect_uris: client.redirect_uris,\n });\n }\n }\n}\n\nexport const applePlugin: ServicePlugin = {\n name: \"apple\",\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 applePlugin;\n"],"mappings":";A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C,aAAa,EAAE,eAAe,UAAU,MAAM,CAAC,EAAE,KAAK,GAAG,KAAK;AAAA,QAC9D,gBAAgB;AAAA,QAChB,kBAAkB;AAAA,QAClB,qBAAqB,YAAY,0BAA0B,IAAI;AAAA,QAC/D,kBAAkB;AAAA,MACpB,CAAC;AAAA,IACH;AAAA,EACF;AAEA,MAAI,OAAO,eAAe;AACxB,eAAW,UAAU,OAAO,eAAe;AACzC,YAAM,WAAW,GAAG,aAAa,UAAU,aAAa,OAAO,SAAS;AACxE,UAAI,SAAU;AACd,SAAG,aAAa,OAAO;AAAA,QACrB,WAAW,OAAO;AAAA,QAClB,SAAS,OAAO;AAAA,QAChB,QAAQ,OAAO,UAAU;AAAA,QACzB,MAAM,OAAO;AAAA,QACb,eAAe,OAAO;AAAA,MACxB,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,IAAM,cAA6B;AAAA,EACxC,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":["randomBytes","randomBytes"]}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@emulators/apple",
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/apple"
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
+ }