@startup-api/cloudflare 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -0
- package/package.json +3 -1
- package/public/users/power-strip.js +32 -2
- package/public/users/profile.html +4 -0
- package/src/StartupAPIEnv.ts +3 -0
- package/src/auth/AtprotoProvider.ts +327 -0
- package/src/auth/OAuthProvider.ts +103 -3
- package/src/auth/atmosphereMark.ts +7 -0
- package/src/auth/atproto/crypto.ts +119 -0
- package/src/auth/atproto/identity.ts +182 -0
- package/src/auth/errorPage.ts +73 -0
- package/src/auth/index.ts +196 -195
- package/src/auth/providers.ts +2 -0
- package/src/createStartupAPI.ts +4 -4
- package/src/handlers/admin.ts +3 -1
- package/src/handlers/ssr.ts +7 -2
- package/src/handlers/utils.ts +7 -1
- package/src/schemas/config.ts +6 -0
- package/worker-configuration.d.ts +1 -5
package/src/auth/index.ts
CHANGED
|
@@ -2,8 +2,10 @@ import type { StartupAPIEnv } from '../StartupAPIEnv';
|
|
|
2
2
|
|
|
3
3
|
import { CookieManager } from '../CookieManager';
|
|
4
4
|
import { refreshEntitlements } from '../entitlements/service';
|
|
5
|
+
import { renderAuthError } from './errorPage';
|
|
5
6
|
import { computeRedirectBase, createProviders } from './providers';
|
|
6
7
|
import type { ProviderConfigs } from './providers';
|
|
8
|
+
import type { AuthContext, ExchangeResult, OAuthProvider } from './OAuthProvider';
|
|
7
9
|
|
|
8
10
|
export async function handleAuth(
|
|
9
11
|
request: Request,
|
|
@@ -25,21 +27,22 @@ export async function handleAuth(
|
|
|
25
27
|
// Instantiate active providers
|
|
26
28
|
const activeProviders = createProviders(env, redirectBase, providerConfigs);
|
|
27
29
|
|
|
30
|
+
const ctx: AuthContext = { request, env, url, redirectBase, authPath, usersPath, origin, cookieManager };
|
|
31
|
+
|
|
32
|
+
// Provider-specific auxiliary routes (e.g. the atproto client-metadata document).
|
|
33
|
+
for (const provider of activeProviders) {
|
|
34
|
+
const res = await provider.handleExtraRoute(ctx);
|
|
35
|
+
if (res) return res;
|
|
36
|
+
}
|
|
37
|
+
|
|
28
38
|
// Handle Auth Start
|
|
29
39
|
for (const provider of activeProviders) {
|
|
30
40
|
if (provider.isMatch(path, authPath)) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
// Use robust base64 encoding for state
|
|
37
|
-
const state = btoa(unescape(encodeURIComponent(JSON.stringify(stateObj))))
|
|
38
|
-
.replace(/\+/g, '-')
|
|
39
|
-
.replace(/\//g, '_')
|
|
40
|
-
.replace(/=+$/, '');
|
|
41
|
-
const authUrl = provider.getAuthUrl(state);
|
|
42
|
-
return Response.redirect(authUrl, 302);
|
|
41
|
+
try {
|
|
42
|
+
return await provider.authorize(ctx);
|
|
43
|
+
} catch (e) {
|
|
44
|
+
return renderAuthError(e instanceof Error ? e.message : String(e), 500, usersPath);
|
|
45
|
+
}
|
|
43
46
|
}
|
|
44
47
|
}
|
|
45
48
|
|
|
@@ -47,207 +50,205 @@ export async function handleAuth(
|
|
|
47
50
|
for (const provider of activeProviders) {
|
|
48
51
|
if (provider.isCallback(path, authPath)) {
|
|
49
52
|
console.log(`[Auth] Callback received for ${provider.name}`);
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
try {
|
|
57
|
-
// Robust base64 decoding
|
|
58
|
-
const base64 = stateBase64.replace(/-/g, '+').replace(/_/g, '/');
|
|
59
|
-
const stateJson = decodeURIComponent(escape(atob(base64)));
|
|
60
|
-
const stateObj = JSON.parse(stateJson);
|
|
61
|
-
returnUrl = stateObj.return_url;
|
|
62
|
-
} catch (e) {
|
|
63
|
-
console.error('Failed to parse state', e);
|
|
64
|
-
}
|
|
53
|
+
try {
|
|
54
|
+
const result = await provider.exchange(ctx);
|
|
55
|
+
return await finishLogin(provider, result, ctx);
|
|
56
|
+
} catch (e) {
|
|
57
|
+
const status = (e as { status?: number })?.status ?? 500;
|
|
58
|
+
return renderAuthError(e instanceof Error ? e.message : String(e), status, usersPath);
|
|
65
59
|
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
66
62
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const profile = await provider.getUserProfile(token.access_token);
|
|
70
|
-
|
|
71
|
-
const systemStub = env.SYSTEM.get(env.SYSTEM.idFromName('global'));
|
|
72
|
-
|
|
73
|
-
// 1. Try to resolve existing user by credential
|
|
74
|
-
const credentialStub = env.CREDENTIAL.get(env.CREDENTIAL.idFromName(provider.name));
|
|
75
|
-
const resolveData = await credentialStub.get(profile.id);
|
|
76
|
-
|
|
77
|
-
let userIdStr: string | null = null;
|
|
78
|
-
let staleSessionId: string | null = null;
|
|
79
|
-
|
|
80
|
-
if (resolveData) {
|
|
81
|
-
userIdStr = resolveData.user_id;
|
|
82
|
-
} else {
|
|
83
|
-
// 2. Not found, check if user is already logged in (to link account)
|
|
84
|
-
const cookieHeader = request.headers.get('Cookie');
|
|
85
|
-
if (cookieHeader) {
|
|
86
|
-
const cookies = cookieHeader.split(';').reduce(
|
|
87
|
-
(acc, cookie) => {
|
|
88
|
-
const [key, value] = cookie.split('=').map((c) => c.trim());
|
|
89
|
-
if (key && value) acc[key] = value;
|
|
90
|
-
return acc;
|
|
91
|
-
},
|
|
92
|
-
{} as Record<string, string>,
|
|
93
|
-
);
|
|
94
|
-
const sessionCookieEncrypted = cookies['session_id'];
|
|
95
|
-
if (sessionCookieEncrypted) {
|
|
96
|
-
const sessionCookie = await cookieManager.decrypt(sessionCookieEncrypted);
|
|
97
|
-
if (sessionCookie && sessionCookie.includes(':')) {
|
|
98
|
-
const parts = sessionCookie.split(':');
|
|
99
|
-
staleSessionId = parts[0];
|
|
100
|
-
userIdStr = parts[1];
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
63
|
+
return new Response('Auth route not found', { status: 404 });
|
|
64
|
+
}
|
|
105
65
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Shared post-exchange login finalization, provider-agnostic: resolve or create the user, link the
|
|
68
|
+
* credential, fetch login-time entitlements, ensure a personal account exists, mint a session and set
|
|
69
|
+
* the session cookie. `result.setCookies` lets a provider emit additional cookies (e.g. clearing
|
|
70
|
+
* transient flow state).
|
|
71
|
+
*/
|
|
72
|
+
async function finishLogin(provider: OAuthProvider, result: ExchangeResult, ctx: AuthContext): Promise<Response> {
|
|
73
|
+
const { env, request, usersPath, origin, cookieManager } = ctx;
|
|
74
|
+
const { token, profile, returnUrl } = result;
|
|
75
|
+
|
|
76
|
+
const systemStub = env.SYSTEM.get(env.SYSTEM.idFromName('global'));
|
|
77
|
+
|
|
78
|
+
// 1. Try to resolve existing user by credential
|
|
79
|
+
const credentialStub = env.CREDENTIAL.get(env.CREDENTIAL.idFromName(provider.name));
|
|
80
|
+
const resolveData = await credentialStub.get(profile.id);
|
|
81
|
+
|
|
82
|
+
let userIdStr: string | null = null;
|
|
83
|
+
let staleSessionId: string | null = null;
|
|
84
|
+
|
|
85
|
+
if (resolveData) {
|
|
86
|
+
userIdStr = resolveData.user_id;
|
|
87
|
+
} else {
|
|
88
|
+
// 2. Not found, check if user is already logged in (to link account)
|
|
89
|
+
const cookieHeader = request.headers.get('Cookie');
|
|
90
|
+
if (cookieHeader) {
|
|
91
|
+
const cookies = cookieHeader.split(';').reduce(
|
|
92
|
+
(acc, cookie) => {
|
|
93
|
+
const [key, value] = cookie.split('=').map((c) => c.trim());
|
|
94
|
+
if (key && value) acc[key] = value;
|
|
95
|
+
return acc;
|
|
96
|
+
},
|
|
97
|
+
{} as Record<string, string>,
|
|
98
|
+
);
|
|
99
|
+
const sessionCookieEncrypted = cookies['session_id'];
|
|
100
|
+
if (sessionCookieEncrypted) {
|
|
101
|
+
const sessionCookie = await cookieManager.decrypt(sessionCookieEncrypted);
|
|
102
|
+
if (sessionCookie && sessionCookie.includes(':')) {
|
|
103
|
+
const parts = sessionCookie.split(':');
|
|
104
|
+
staleSessionId = parts[0];
|
|
105
|
+
userIdStr = parts[1];
|
|
121
106
|
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
122
110
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
await userStub.storeImage('avatar', picBlob, picRes.headers.get('Content-Type') || 'image/jpeg');
|
|
135
|
-
// Update profile.picture to point to our worker
|
|
136
|
-
profile.picture = usersPath + 'me/avatar';
|
|
137
|
-
}
|
|
138
|
-
} catch (e) {
|
|
139
|
-
console.error('Failed to fetch avatar', e);
|
|
140
|
-
}
|
|
111
|
+
if (userIdStr) {
|
|
112
|
+
// Verify user still exists (has a profile)
|
|
113
|
+
const userStub = env.USER.get(env.USER.idFromString(userIdStr));
|
|
114
|
+
const profileData = await userStub.getProfile();
|
|
115
|
+
if (Object.keys(profileData).length === 0) {
|
|
116
|
+
// User was deleted!
|
|
117
|
+
if (staleSessionId) {
|
|
118
|
+
try {
|
|
119
|
+
await userStub.deleteSession(staleSessionId);
|
|
120
|
+
} catch (_e) {
|
|
121
|
+
// ignore
|
|
141
122
|
}
|
|
123
|
+
}
|
|
124
|
+
userIdStr = null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
142
127
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
128
|
+
const isNewUser = !userIdStr;
|
|
129
|
+
const id = userIdStr ? env.USER.idFromString(userIdStr) : env.USER.newUniqueId();
|
|
130
|
+
const userStub = env.USER.get(id);
|
|
131
|
+
userIdStr = id.toString();
|
|
132
|
+
|
|
133
|
+
// Fetch and Store Avatar (Only for new users)
|
|
134
|
+
if (isNewUser && profile.picture) {
|
|
135
|
+
try {
|
|
136
|
+
const picRes = await fetch(profile.picture);
|
|
137
|
+
if (picRes.ok) {
|
|
138
|
+
const picBlob = await picRes.arrayBuffer();
|
|
139
|
+
await userStub.storeImage('avatar', picBlob, picRes.headers.get('Content-Type') || 'image/jpeg');
|
|
140
|
+
// Update profile.picture to point to our worker
|
|
141
|
+
profile.picture = usersPath + 'me/avatar';
|
|
142
|
+
}
|
|
143
|
+
} catch (e) {
|
|
144
|
+
console.error('Failed to fetch avatar', e);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Register credential in provider-specific CredentialDO
|
|
149
|
+
await credentialStub.put({
|
|
150
|
+
user_id: userIdStr,
|
|
151
|
+
subject_id: profile.id,
|
|
152
|
+
access_token: token.access_token,
|
|
153
|
+
refresh_token: token.refresh_token,
|
|
154
|
+
expires_at: token.expires_in ? Date.now() + token.expires_in * 1000 : undefined,
|
|
155
|
+
scope: token.scope,
|
|
156
|
+
profile_data: profile,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// Register credential mapping in UserDO
|
|
160
|
+
await userStub.addCredential(provider.name, profile.id);
|
|
161
|
+
|
|
162
|
+
// Login-time entitlement fetch: providers that support entitlements (e.g. Patreon) get an
|
|
163
|
+
// initial entitlement snapshot now, so gating works even when no freshness mechanism is
|
|
164
|
+
// configured. Best-effort — never block or fail login on an entitlement error.
|
|
165
|
+
if (provider.supportsEntitlements()) {
|
|
166
|
+
try {
|
|
167
|
+
await refreshEntitlements(
|
|
168
|
+
env,
|
|
169
|
+
provider,
|
|
170
|
+
{
|
|
146
171
|
subject_id: profile.id,
|
|
172
|
+
user_id: userIdStr,
|
|
147
173
|
access_token: token.access_token,
|
|
148
174
|
refresh_token: token.refresh_token,
|
|
149
175
|
expires_at: token.expires_in ? Date.now() + token.expires_in * 1000 : undefined,
|
|
150
|
-
scope: token.scope,
|
|
176
|
+
scope: typeof token.scope === 'string' ? token.scope : undefined,
|
|
151
177
|
profile_data: profile,
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
// configured. Best-effort — never block or fail login on an entitlement error.
|
|
160
|
-
if (provider.supportsEntitlements()) {
|
|
161
|
-
try {
|
|
162
|
-
await refreshEntitlements(
|
|
163
|
-
env,
|
|
164
|
-
provider,
|
|
165
|
-
{
|
|
166
|
-
subject_id: profile.id,
|
|
167
|
-
user_id: userIdStr,
|
|
168
|
-
access_token: token.access_token,
|
|
169
|
-
refresh_token: token.refresh_token,
|
|
170
|
-
expires_at: token.expires_in ? Date.now() + token.expires_in * 1000 : undefined,
|
|
171
|
-
scope: typeof token.scope === 'string' ? token.scope : undefined,
|
|
172
|
-
profile_data: profile,
|
|
173
|
-
},
|
|
174
|
-
'oauth',
|
|
175
|
-
);
|
|
176
|
-
} catch (e) {
|
|
177
|
-
console.error('[auth] Login-time entitlement fetch failed', e);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
178
|
+
},
|
|
179
|
+
'oauth',
|
|
180
|
+
);
|
|
181
|
+
} catch (e) {
|
|
182
|
+
console.error('[auth] Login-time entitlement fetch failed', e);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
180
185
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
186
|
+
// Register User in SystemDO index (Only for new users)
|
|
187
|
+
if (isNewUser) {
|
|
188
|
+
await userStub.updateProfile(profile);
|
|
189
|
+
await systemStub.registerUser({
|
|
190
|
+
id: userIdStr,
|
|
191
|
+
name: profile.name || userIdStr,
|
|
192
|
+
email: profile.email,
|
|
193
|
+
provider: provider.name,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
191
196
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
197
|
+
// Ensure user has at least one account
|
|
198
|
+
const memberships = await userStub.getMemberships();
|
|
199
|
+
|
|
200
|
+
if (memberships.length === 0) {
|
|
201
|
+
// Create a personal account
|
|
202
|
+
const accountId = env.ACCOUNT.newUniqueId();
|
|
203
|
+
const accountStub = env.ACCOUNT.get(accountId);
|
|
204
|
+
const accountIdStr = accountId.toString();
|
|
205
|
+
|
|
206
|
+
// Initialize account info
|
|
207
|
+
await accountStub.updateInfo({
|
|
208
|
+
name: `${profile.name || userIdStr}'s Account`,
|
|
209
|
+
personal: true,
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
// Register Account in SystemDO
|
|
213
|
+
await systemStub.registerAccount({
|
|
214
|
+
id: accountIdStr,
|
|
215
|
+
name: `${profile.name || profile.id}'s Account`,
|
|
216
|
+
status: 'active',
|
|
217
|
+
plan: 'free',
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
// Add user as ADMIN to the account
|
|
221
|
+
await accountStub.addMember(id.toString(), 1);
|
|
222
|
+
|
|
223
|
+
// Add membership to user
|
|
224
|
+
await userStub.addMembership(accountIdStr, 1, true);
|
|
225
|
+
}
|
|
221
226
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
// Set cookie and redirect
|
|
226
|
-
const encryptedSession = await cookieManager.encrypt(`${session.sessionId}:${userIdStr}`);
|
|
227
|
-
const headers = new Headers();
|
|
228
|
-
headers.set('Set-Cookie', `session_id=${encryptedSession}; Path=/; HttpOnly; Secure; SameSite=Lax`);
|
|
229
|
-
|
|
230
|
-
let redirectUrl = !isNewUser ? usersPath + 'profile.html' : '/';
|
|
231
|
-
if (returnUrl) {
|
|
232
|
-
try {
|
|
233
|
-
const parsedReturn = new URL(returnUrl, origin);
|
|
234
|
-
if (parsedReturn.origin === origin) {
|
|
235
|
-
redirectUrl = parsedReturn.toString();
|
|
236
|
-
}
|
|
237
|
-
} catch (_e) {
|
|
238
|
-
if (returnUrl.startsWith('/')) {
|
|
239
|
-
redirectUrl = returnUrl;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
}
|
|
227
|
+
// Create Session
|
|
228
|
+
const session = await userStub.createSession({ provider: provider.name });
|
|
243
229
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
230
|
+
// Set cookie and redirect
|
|
231
|
+
const encryptedSession = await cookieManager.encrypt(`${session.sessionId}:${userIdStr}`);
|
|
232
|
+
const headers = new Headers();
|
|
233
|
+
headers.set('Set-Cookie', `session_id=${encryptedSession}; Path=/; HttpOnly; Secure; SameSite=Lax`);
|
|
234
|
+
for (const cookie of result.setCookies ?? []) {
|
|
235
|
+
headers.append('Set-Cookie', cookie);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
let redirectUrl = !isNewUser ? usersPath + 'profile.html' : '/';
|
|
239
|
+
if (returnUrl) {
|
|
240
|
+
try {
|
|
241
|
+
const parsedReturn = new URL(returnUrl, origin);
|
|
242
|
+
if (parsedReturn.origin === origin) {
|
|
243
|
+
redirectUrl = parsedReturn.toString();
|
|
244
|
+
}
|
|
245
|
+
} catch (_e) {
|
|
246
|
+
if (returnUrl.startsWith('/')) {
|
|
247
|
+
redirectUrl = returnUrl;
|
|
248
248
|
}
|
|
249
249
|
}
|
|
250
250
|
}
|
|
251
251
|
|
|
252
|
-
|
|
252
|
+
headers.set('Location', redirectUrl);
|
|
253
|
+
return new Response(null, { status: 302, headers });
|
|
253
254
|
}
|
package/src/auth/providers.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { OAuthProvider } from './OAuthProvider';
|
|
|
4
4
|
import { GoogleProvider } from './GoogleProvider';
|
|
5
5
|
import { TwitchProvider } from './TwitchProvider';
|
|
6
6
|
import { PatreonProvider } from './PatreonProvider';
|
|
7
|
+
import { AtprotoProvider } from './AtprotoProvider';
|
|
7
8
|
|
|
8
9
|
export type ProviderConfigs = Record<string, ProviderOptions>;
|
|
9
10
|
|
|
@@ -25,6 +26,7 @@ export function createProviders(env: StartupAPIEnv, redirectBase: string, provid
|
|
|
25
26
|
GoogleProvider.create(env, redirectBase, providerConfigs.google),
|
|
26
27
|
TwitchProvider.create(env, redirectBase, providerConfigs.twitch),
|
|
27
28
|
PatreonProvider.create(env, redirectBase, providerConfigs.patreon),
|
|
29
|
+
AtprotoProvider.create(env, redirectBase, providerConfigs.atproto),
|
|
28
30
|
].filter((p): p is OAuthProvider => p !== null);
|
|
29
31
|
}
|
|
30
32
|
|
package/src/createStartupAPI.ts
CHANGED
|
@@ -167,7 +167,7 @@ export function createStartupAPI(config: StartupAPIConfig = {}) {
|
|
|
167
167
|
const isAccounts = subPath === 'accounts.html' || subPath === 'accounts';
|
|
168
168
|
|
|
169
169
|
if (isProfile || isAccounts) {
|
|
170
|
-
return handleSSR(request, env, url, usersPath, cookieManager);
|
|
170
|
+
return handleSSR(request, env, url, usersPath, cookieManager, providerConfigs);
|
|
171
171
|
}
|
|
172
172
|
}
|
|
173
173
|
|
|
@@ -262,7 +262,7 @@ export function createStartupAPI(config: StartupAPIConfig = {}) {
|
|
|
262
262
|
|
|
263
263
|
// Admin Routes
|
|
264
264
|
if (url.pathname.startsWith(usersPath + 'admin/')) {
|
|
265
|
-
return handleAdmin(request, env, usersPath, cookieManager);
|
|
265
|
+
return handleAdmin(request, env, usersPath, cookieManager, providerConfigs);
|
|
266
266
|
}
|
|
267
267
|
|
|
268
268
|
// Intercept requests to usersPath and serve them from the public/users directory.
|
|
@@ -336,7 +336,7 @@ export function createStartupAPI(config: StartupAPIConfig = {}) {
|
|
|
336
336
|
return denyResponse(decision, {
|
|
337
337
|
usersPath,
|
|
338
338
|
returnUrl,
|
|
339
|
-
activeProviders: getActiveProviders(env),
|
|
339
|
+
activeProviders: getActiveProviders(env, providerConfigs),
|
|
340
340
|
authenticated,
|
|
341
341
|
request,
|
|
342
342
|
env,
|
|
@@ -345,7 +345,7 @@ export function createStartupAPI(config: StartupAPIConfig = {}) {
|
|
|
345
345
|
}
|
|
346
346
|
|
|
347
347
|
const response = await originFetch(newRequest);
|
|
348
|
-
const providers = getActiveProviders(env);
|
|
348
|
+
const providers = getActiveProviders(env, providerConfigs);
|
|
349
349
|
return injectPowerStrip(response, usersPath, providers);
|
|
350
350
|
}
|
|
351
351
|
|
package/src/handlers/admin.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { StartupAPIEnv } from '../StartupAPIEnv';
|
|
2
2
|
import { CookieManager } from '../CookieManager';
|
|
3
3
|
import { getUserFromSession, checkAndClearStaleSession, isAdmin, parseCookies, getActiveProviders } from './utils';
|
|
4
|
+
import type { ProviderConfigs } from '../auth/providers';
|
|
4
5
|
import { Plan } from '../billing/Plan';
|
|
5
6
|
import { UserProfileSchema } from '../schemas/user';
|
|
6
7
|
import { SystemAccountSchema, MemberSchema } from '../schemas/account';
|
|
@@ -11,6 +12,7 @@ export async function handleAdmin(
|
|
|
11
12
|
env: StartupAPIEnv,
|
|
12
13
|
usersPath: string,
|
|
13
14
|
cookieManager: CookieManager,
|
|
15
|
+
providerConfigs: ProviderConfigs = {},
|
|
14
16
|
): Promise<Response> {
|
|
15
17
|
const user = await getUserFromSession(request, env, cookieManager);
|
|
16
18
|
if (!user || !isAdmin(user, env)) {
|
|
@@ -31,7 +33,7 @@ export async function handleAdmin(
|
|
|
31
33
|
html = html.replace(/\{\{ssr:([a-z0-9_]+)\}\}/g, (match, key) => {
|
|
32
34
|
const replacements: Record<string, string> = {
|
|
33
35
|
plans_json: JSON.stringify(Plan.getAll()).replace(/"/g, '"'),
|
|
34
|
-
providers: getActiveProviders(env).join(','),
|
|
36
|
+
providers: getActiveProviders(env, providerConfigs).join(','),
|
|
35
37
|
};
|
|
36
38
|
return replacements[key] !== undefined ? replacements[key] : match;
|
|
37
39
|
});
|
package/src/handlers/ssr.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { StartupAPIEnv } from '../StartupAPIEnv';
|
|
2
2
|
import { CookieManager } from '../CookieManager';
|
|
3
3
|
import { getUserFromSession, checkAndClearStaleSession, isAdmin, getActiveProviders } from './utils';
|
|
4
|
+
import type { ProviderConfigs } from '../auth/providers';
|
|
5
|
+
import { ATMOSPHERE_MARK_PATH } from '../auth/atmosphereMark';
|
|
4
6
|
import { Plan } from '../billing/Plan';
|
|
5
7
|
|
|
6
8
|
export async function handleSSR(
|
|
@@ -9,6 +11,7 @@ export async function handleSSR(
|
|
|
9
11
|
url: URL,
|
|
10
12
|
usersPath: string,
|
|
11
13
|
cookieManager: CookieManager,
|
|
14
|
+
providerConfigs: ProviderConfigs = {},
|
|
12
15
|
): Promise<Response> {
|
|
13
16
|
const user = await getUserFromSession(request, env, cookieManager);
|
|
14
17
|
if (!user) {
|
|
@@ -90,7 +93,7 @@ export async function handleSSR(
|
|
|
90
93
|
// Prepare SSR values
|
|
91
94
|
const replacements: Record<string, string> = {
|
|
92
95
|
plans_json: JSON.stringify(Plan.getAll()).replace(/"/g, '"'),
|
|
93
|
-
providers: getActiveProviders(env).join(','),
|
|
96
|
+
providers: getActiveProviders(env, providerConfigs).join(','),
|
|
94
97
|
profile_json: JSON.stringify(data).replace(/"/g, '"'),
|
|
95
98
|
credentials_json: JSON.stringify(credentials).replace(/"/g, '"'),
|
|
96
99
|
profile_name: data.profile.name || 'Anonymous',
|
|
@@ -105,7 +108,7 @@ export async function handleSSR(
|
|
|
105
108
|
: '',
|
|
106
109
|
nav_account_display: account && (account.role === 1 || data.is_admin) ? 'display: block;' : 'display: none;',
|
|
107
110
|
credentials_list_html: renderCredentialsList(credentials, data.credential?.provider),
|
|
108
|
-
link_credentials_html: renderLinkCredentialsList(getActiveProviders(env), url.href),
|
|
111
|
+
link_credentials_html: renderLinkCredentialsList(getActiveProviders(env, providerConfigs), url.href),
|
|
109
112
|
};
|
|
110
113
|
|
|
111
114
|
if (account) {
|
|
@@ -212,6 +215,8 @@ function getProviderIcon(provider: string): string {
|
|
|
212
215
|
return '<svg viewBox="0 0 24 24" width="24" height="24" class="twitch-icon"><path d="M11.571 4.714h1.715v5.143H11.57zm4.715 0H18v5.143h-1.714zM6 0L1.714 4.286v15.428h5.143V24l4.286-4.286h3.428L22.286 12V0zm14.571 11.143l-3.428 3.428h-3.429l-3 3v-3H6.857V1.714h13.714z" fill="currentColor"/></svg>';
|
|
213
216
|
} else if (provider === 'patreon') {
|
|
214
217
|
return '<svg viewBox="0 0 24 24" width="24" height="24" class="patreon-icon"><path d="M14.82 2.41c3.96 0 7.18 3.24 7.18 7.21 0 3.96-3.22 7.18-7.18 7.18-3.97 0-7.21-3.22-7.21-7.18 0-3.97 3.24-7.21 7.21-7.21M2 21.6h3.5V2.41H2V21.6z" fill="currentColor"/></svg>';
|
|
218
|
+
} else if (provider === 'atproto') {
|
|
219
|
+
return `<svg viewBox="0 0 32 32" width="24" height="24" class="atproto-icon"><path fill-rule="evenodd" clip-rule="evenodd" d="${ATMOSPHERE_MARK_PATH}" fill="#4a8ad4"/></svg>`;
|
|
215
220
|
}
|
|
216
221
|
return '';
|
|
217
222
|
}
|
package/src/handlers/utils.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { StartupAPIEnv } from '../StartupAPIEnv';
|
|
2
2
|
import { CookieManager } from '../CookieManager';
|
|
3
|
+
import { isAtprotoEnabled } from '../auth/AtprotoProvider';
|
|
4
|
+
import type { ProviderConfigs } from '../auth/providers';
|
|
3
5
|
|
|
4
|
-
export function getActiveProviders(env: StartupAPIEnv): string[] {
|
|
6
|
+
export function getActiveProviders(env: StartupAPIEnv, providerConfigs: ProviderConfigs = {}): string[] {
|
|
5
7
|
const providers: string[] = [];
|
|
6
8
|
if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
|
|
7
9
|
providers.push('google');
|
|
@@ -12,6 +14,10 @@ export function getActiveProviders(env: StartupAPIEnv): string[] {
|
|
|
12
14
|
if (env.PATREON_CLIENT_ID && env.PATREON_CLIENT_SECRET) {
|
|
13
15
|
providers.push('patreon');
|
|
14
16
|
}
|
|
17
|
+
// atproto has no env credentials; it is enabled via factory config or the ATPROTO_ENABLED env flag.
|
|
18
|
+
if (isAtprotoEnabled(providerConfigs.atproto, env)) {
|
|
19
|
+
providers.push('atproto');
|
|
20
|
+
}
|
|
15
21
|
return providers;
|
|
16
22
|
}
|
|
17
23
|
|
package/src/schemas/config.ts
CHANGED
|
@@ -28,6 +28,12 @@ export const ProviderOptionsSchema = z.object({
|
|
|
28
28
|
scopes: z.union([z.string(), z.array(z.string())]).optional(),
|
|
29
29
|
/** Patreon only: restrict entitlements to a single campaign id. */
|
|
30
30
|
campaignId: z.string().optional(),
|
|
31
|
+
/** atproto only: display name advertised in the client-metadata document. Default: "StartupAPI". */
|
|
32
|
+
clientName: z.string().optional(),
|
|
33
|
+
/** atproto only: override the PLC directory used to resolve did:plc identities. Default: https://plc.directory. */
|
|
34
|
+
plcUrl: z.string().optional(),
|
|
35
|
+
/** atproto only: override the DNS-over-HTTPS resolver used for handle resolution. */
|
|
36
|
+
dohUrl: z.string().optional(),
|
|
31
37
|
freshness: ProviderFreshnessSchema.optional(),
|
|
32
38
|
});
|
|
33
39
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* eslint-disable */
|
|
2
|
-
// Generated by Wrangler by running `wrangler types` (hash:
|
|
2
|
+
// Generated by Wrangler by running `wrangler types` (hash: 21e6c5c76a7bbde8583fcbcc839c03e7)
|
|
3
3
|
// Runtime types generated with workerd@1.20260120.0 2025-09-27 global_fetch_strictly_public
|
|
4
4
|
declare namespace Cloudflare {
|
|
5
5
|
interface GlobalProps {
|
|
@@ -15,7 +15,6 @@ declare namespace Cloudflare {
|
|
|
15
15
|
ORIGIN_URL: "https://startup-api-demo-origin.sergeychernyshev.workers.dev/";
|
|
16
16
|
TWITCH_CLIENT_ID: "";
|
|
17
17
|
TWITCH_CLIENT_SECRET: "";
|
|
18
|
-
GITHUB_PROJECT_ID: string;
|
|
19
18
|
USER: DurableObjectNamespace<import("./src/index").UserDO>;
|
|
20
19
|
ACCOUNT: DurableObjectNamespace<import("./src/index").AccountDO>;
|
|
21
20
|
SYSTEM: DurableObjectNamespace<import("./src/index").SystemDO>;
|
|
@@ -36,7 +35,6 @@ declare namespace Cloudflare {
|
|
|
36
35
|
PATREON_CLIENT_ID: "";
|
|
37
36
|
PATREON_CLIENT_SECRET: "";
|
|
38
37
|
PATREON_WEBHOOK_SECRET: "";
|
|
39
|
-
GITHUB_PROJECT_ID: string;
|
|
40
38
|
USER: DurableObjectNamespace<import("./src/index").UserDO>;
|
|
41
39
|
ACCOUNT: DurableObjectNamespace<import("./src/index").AccountDO>;
|
|
42
40
|
SYSTEM: DurableObjectNamespace<import("./src/index").SystemDO>;
|
|
@@ -56,14 +54,12 @@ declare namespace Cloudflare {
|
|
|
56
54
|
PATREON_CLIENT_ID: "patreon-id";
|
|
57
55
|
PATREON_CLIENT_SECRET: "patreon-secret";
|
|
58
56
|
PATREON_WEBHOOK_SECRET: "whsec-test";
|
|
59
|
-
GITHUB_PROJECT_ID: string;
|
|
60
57
|
USER: DurableObjectNamespace<import("./src/index").UserDO>;
|
|
61
58
|
ACCOUNT: DurableObjectNamespace<import("./src/index").AccountDO>;
|
|
62
59
|
SYSTEM: DurableObjectNamespace<import("./src/index").SystemDO>;
|
|
63
60
|
CREDENTIAL: DurableObjectNamespace<import("./src/index").CredentialDO>;
|
|
64
61
|
}
|
|
65
62
|
interface Env {
|
|
66
|
-
GITHUB_PROJECT_ID: string;
|
|
67
63
|
IMAGE_STORAGE: R2Bucket;
|
|
68
64
|
ASSETS: Fetcher;
|
|
69
65
|
ENVIRONMENT?: "preview" | "" | "test";
|