@usebecky/extension 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -2
- package/dist/accounts.d.ts +85 -0
- package/dist/accounts.js +149 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/run.d.ts +25 -0
- package/dist/cli/run.js +330 -0
- package/dist/cli/skill.d.ts +16 -0
- package/dist/cli/skill.js +106 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +56 -0
- package/dist/dev/pages.d.ts +155 -0
- package/dist/dev/pages.js +243 -0
- package/dist/dev/plans.d.ts +45 -0
- package/dist/dev/plans.js +135 -0
- package/dist/dev/samples.d.ts +61 -0
- package/dist/dev/samples.js +191 -0
- package/dist/dev/server.d.ts +120 -0
- package/dist/dev/server.js +1657 -0
- package/dist/dev/tagging.d.ts +16 -0
- package/dist/dev/tagging.js +81 -0
- package/dist/dev/ui-render.d.ts +25 -0
- package/dist/dev/ui-render.js +256 -0
- package/dist/dev/wordmark.d.ts +1 -0
- package/dist/dev/wordmark.js +2 -0
- package/dist/errors.d.ts +98 -0
- package/dist/errors.js +110 -0
- package/dist/events.d.ts +92 -0
- package/dist/events.js +54 -0
- package/dist/extension.d.ts +214 -0
- package/dist/extension.js +497 -0
- package/dist/handlers.d.ts +39 -0
- package/dist/handlers.js +113 -0
- package/dist/identity.d.ts +99 -0
- package/dist/identity.js +134 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +17 -0
- package/dist/jwt.d.ts +62 -0
- package/dist/jwt.js +152 -0
- package/dist/manifest.d.ts +42 -0
- package/dist/manifest.js +785 -0
- package/dist/node.d.ts +10 -0
- package/dist/node.js +56 -0
- package/dist/pkce.d.ts +9 -0
- package/dist/pkce.js +16 -0
- package/dist/stores.d.ts +100 -0
- package/dist/stores.js +159 -0
- package/dist/types.d.ts +346 -0
- package/dist/types.js +70 -0
- package/dist/ui/handler.d.ts +66 -0
- package/dist/ui/handler.js +105 -0
- package/dist/ui/schema.d.ts +423 -0
- package/dist/ui/schema.js +666 -0
- package/dist/webhooks.d.ts +26 -0
- package/dist/webhooks.js +99 -0
- package/package.json +57 -4
- package/skill/usebecky-extension/SKILL.md +181 -0
- package/skill/usebecky-extension/references/accounts.md +125 -0
- package/skill/usebecky-extension/references/dev-server.md +102 -0
- package/skill/usebecky-extension/references/manifest.md +104 -0
- package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/skill/usebecky-extension/references/partner-api.md +87 -0
- package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/skill/usebecky-extension/references/ui.md +172 -0
- package/skill/usebecky-extension/references/webhooks.md +97 -0
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// createExtension(): everything an extension's server needs to talk to usebecky.
|
|
2
|
+
//
|
|
3
|
+
// install authorizeUrl() sends the customer to usebecky's consent screen (OAuth 2 + PKCE S256)
|
|
4
|
+
// callback handleCallback() swaps the code for tokens and stores them per project
|
|
5
|
+
// API api(project) calls /extensions/v1 and refreshes tokens on its own (rotation-safe)
|
|
6
|
+
// webhooks verifyWebhook() / webhookHandler() check usebecky-signature and hand you typed events
|
|
7
|
+
import { provisionHandler as makeProvisionHandler, ssoHandler as makeSsoHandler } from "./accounts.js";
|
|
8
|
+
import { randomToken } from "./crypto.js";
|
|
9
|
+
import { ConfigError, ExtensionError, InstallationRevokedError, OAuthCallbackError, PartnerApiError, partnerErrorHint, readErrorBody, TokenError } from "./errors.js";
|
|
10
|
+
import { memoryReplayGuard, verifyIdToken as verifyIdTokenWith, verifyLaunchToken as verifyLaunchTokenWith } from "./identity.js";
|
|
11
|
+
import { createJwks } from "./jwt.js";
|
|
12
|
+
import { errorPage, jsonResponse } from "./handlers.js";
|
|
13
|
+
import { codeChallengeFor, createCodeVerifier } from "./pkce.js";
|
|
14
|
+
import { memoryStateStore } from "./stores.js";
|
|
15
|
+
import { EXTENSION_SCOPES } from "./types.js";
|
|
16
|
+
import { verifyWebhook } from "./webhooks.js";
|
|
17
|
+
import { uiHandler as makeUiHandler } from "./ui/handler.js";
|
|
18
|
+
/** usebecky's API. */
|
|
19
|
+
export const DEFAULT_API_URL = 'https://api.usebecky.com';
|
|
20
|
+
/** usebecky's dashboard: the consent screen is `<dashboard>/oauth/authorize`. */
|
|
21
|
+
export const DEFAULT_DASHBOARD_URL = 'https://app.usebecky.com';
|
|
22
|
+
/** Path of the partner API (OAuth token endpoint included) under the API URL. */
|
|
23
|
+
export const PARTNER_API_PATH = '/extensions/v1';
|
|
24
|
+
/** Path of the consent screen under the dashboard URL. */
|
|
25
|
+
export const AUTHORIZE_PATH = '/oauth/authorize';
|
|
26
|
+
/** How long a started sign-in may take before its state expires. */
|
|
27
|
+
export const STATE_TTL_SECONDS = 600;
|
|
28
|
+
/**
|
|
29
|
+
* The cookie the install handler sets with the sign-in's state, so the callback only finishes in the browser
|
|
30
|
+
* that started it (an attacker can't send a victim a callback link for the attacker's project).
|
|
31
|
+
*/
|
|
32
|
+
export const STATE_COOKIE = 'usebecky_oauth_state';
|
|
33
|
+
/** Webhook bodies above this are refused before verifying (usebecky's are a few KB). */
|
|
34
|
+
export const MAX_WEBHOOK_BYTES = 1024 * 1024;
|
|
35
|
+
function need(value, name, env) {
|
|
36
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
37
|
+
throw new ConfigError({
|
|
38
|
+
code: 'missing_option',
|
|
39
|
+
message: `createExtension: "${name}" is missing.`,
|
|
40
|
+
hint: `Set ${env} in your environment (usebecky: Developer → your extension → Credentials and testing → Create credentials; the dev server prints test values).`,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return value.trim();
|
|
44
|
+
}
|
|
45
|
+
function absoluteUrl(value, name) {
|
|
46
|
+
try {
|
|
47
|
+
return new URL(value);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new ConfigError({ code: 'invalid_option', message: `createExtension: "${name}" must be a full address like https://example.com/oauth/callback, got "${value}".` });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const trimSlash = (s) => s.replace(/\/+$/, '');
|
|
54
|
+
/** Scopes from a token response (string or list), or null when absent. */
|
|
55
|
+
function scopesOf(scope) {
|
|
56
|
+
const list = Array.isArray(scope) ? scope : typeof scope === 'string' ? scope.split(/[\s,]+/) : null;
|
|
57
|
+
return list ? list.filter((s) => EXTENSION_SCOPES.includes(s)) : null;
|
|
58
|
+
}
|
|
59
|
+
function queryOf(input) {
|
|
60
|
+
if (input instanceof URLSearchParams)
|
|
61
|
+
return input;
|
|
62
|
+
if (input instanceof URL)
|
|
63
|
+
return input.searchParams;
|
|
64
|
+
if (typeof input === 'string')
|
|
65
|
+
return new URL(input, 'http://localhost').searchParams;
|
|
66
|
+
if (typeof Request !== 'undefined' && input instanceof Request)
|
|
67
|
+
return new URL(input.url).searchParams;
|
|
68
|
+
const raw = input.originalUrl ?? input.url ?? '';
|
|
69
|
+
return new URL(raw, 'http://localhost').searchParams;
|
|
70
|
+
}
|
|
71
|
+
/** A cookie from a Request or Node's `req` (CallbackInput); undefined for URLs and query strings. */
|
|
72
|
+
function cookieOf(input, name) {
|
|
73
|
+
let header;
|
|
74
|
+
if (typeof Request !== 'undefined' && input instanceof Request)
|
|
75
|
+
header = input.headers.get('cookie');
|
|
76
|
+
else if (input && typeof input === 'object' && 'headers' in input) {
|
|
77
|
+
const h = input.headers?.cookie;
|
|
78
|
+
header = Array.isArray(h) ? h.join('; ') : h;
|
|
79
|
+
}
|
|
80
|
+
for (const part of (header ?? '').split(';')) {
|
|
81
|
+
const i = part.indexOf('=');
|
|
82
|
+
if (i > 0 && part.slice(0, i).trim() === name)
|
|
83
|
+
return decodeURIComponent(part.slice(i + 1).trim());
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
/** Project refs are short lowercase ids; anything else from a query string is ignored. */
|
|
88
|
+
const PROJECT_REF = /^[a-z0-9][a-z0-9-]{1,62}$/;
|
|
89
|
+
/**
|
|
90
|
+
* usebecky's team suspended the extension. That revokes every token for good, so the kit has deleted the stored ones:
|
|
91
|
+
* once the suspension ends, each customer connects the extension again.
|
|
92
|
+
*/
|
|
93
|
+
function suspendedError(project, status) {
|
|
94
|
+
return new InstallationRevokedError({
|
|
95
|
+
code: 'extension_suspended',
|
|
96
|
+
message: `usebecky suspended this extension, so it no longer works for the project ${project}.`,
|
|
97
|
+
hint: `${partnerErrorHint('extension_suspended')} The stored tokens were deleted: once the suspension ends, customers connect the extension again.`,
|
|
98
|
+
status,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
export function createExtension(options) {
|
|
102
|
+
const clientId = need(options.clientId, 'clientId', 'USEBECKY_CLIENT_ID');
|
|
103
|
+
const clientSecret = need(options.clientSecret, 'clientSecret', 'USEBECKY_CLIENT_SECRET');
|
|
104
|
+
const redirectUri = absoluteUrl(need(options.redirectUri, 'redirectUri', 'PUBLIC_URL (your server address)'), 'redirectUri').toString();
|
|
105
|
+
const apiUrl = trimSlash(absoluteUrl(options.apiUrl?.trim() || DEFAULT_API_URL, 'apiUrl').toString());
|
|
106
|
+
const dashboardUrl = trimSlash(absoluteUrl(options.dashboardUrl?.trim() || (apiUrl === DEFAULT_API_URL ? DEFAULT_DASHBOARD_URL : apiUrl), 'dashboardUrl').toString());
|
|
107
|
+
const dashboardOrigin = new URL(dashboardUrl).origin;
|
|
108
|
+
if (!options.tokenStore)
|
|
109
|
+
throw new ConfigError({ code: 'missing_option', message: 'createExtension: "tokenStore" is missing.', hint: 'Use memoryTokenStore() to try things out, fileTokenStore() on one server, or sqlTokenStore() with your database.' });
|
|
110
|
+
const tokenStore = options.tokenStore;
|
|
111
|
+
const stateStore = options.stateStore ?? memoryStateStore();
|
|
112
|
+
const doFetch = options.fetch ?? ((...args) => fetch(...args));
|
|
113
|
+
const now = options.now ?? Date.now;
|
|
114
|
+
const margin = (options.refreshMarginSeconds ?? 60) * 1000;
|
|
115
|
+
const authorizeEndpoint = `${dashboardUrl}${AUTHORIZE_PATH}`;
|
|
116
|
+
const partnerBase = `${apiUrl}${PARTNER_API_PATH}`;
|
|
117
|
+
const inflight = new Map();
|
|
118
|
+
// usebecky signs id_tokens and launch tokens; its keys are at <apiUrl>/.well-known/jwks.json (issuer = apiUrl).
|
|
119
|
+
const jwks = createJwks({ apiUrl, fetch: doFetch, now });
|
|
120
|
+
const replayGuard = options.replayGuard ?? memoryReplayGuard({ now });
|
|
121
|
+
const clock = () => Math.floor(now() / 1000);
|
|
122
|
+
const tokenOptions = () => ({ clientId, apiUrl, jwks, fetch: doFetch, now: clock });
|
|
123
|
+
// ---- token endpoint ----------------------------------------------------------------------
|
|
124
|
+
async function tokenRequest(params) {
|
|
125
|
+
let res;
|
|
126
|
+
try {
|
|
127
|
+
res = await doFetch(`${partnerBase}/oauth/token`, {
|
|
128
|
+
method: 'POST',
|
|
129
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
130
|
+
body: new URLSearchParams({ ...params, client_id: clientId, client_secret: clientSecret }).toString(),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
throw new TokenError({ code: 'network_error', message: `Could not reach usebecky at ${apiUrl}: ${err.message}`, hint: 'Check USEBECKY_API_URL and your internet connection.' });
|
|
135
|
+
}
|
|
136
|
+
const body = (await res.json().catch(() => null));
|
|
137
|
+
if (!res.ok || !body || typeof body.access_token !== 'string') {
|
|
138
|
+
const e = readErrorBody(body);
|
|
139
|
+
const code = e.code ?? (res.ok ? 'invalid_response' : 'token_request_failed');
|
|
140
|
+
const hint = e.hint ?? (code === 'invalid_client' ? 'The client id or secret is wrong: check USEBECKY_CLIENT_ID and USEBECKY_CLIENT_SECRET.' : code === 'extension_suspended' ? partnerErrorHint(code) : undefined);
|
|
141
|
+
throw new TokenError({ code, message: e.message ?? `usebecky refused the token request (HTTP ${res.status}).`, hint, status: res.status });
|
|
142
|
+
}
|
|
143
|
+
return body;
|
|
144
|
+
}
|
|
145
|
+
function toStored(project, installationId, t, previous, scopes) {
|
|
146
|
+
const refreshToken = t.refresh_token ?? previous?.refreshToken;
|
|
147
|
+
if (!refreshToken)
|
|
148
|
+
throw new TokenError({ code: 'invalid_response', message: 'usebecky sent no refresh token.' });
|
|
149
|
+
const expiresIn = Number.isFinite(Number(t.expires_in)) && Number(t.expires_in) > 0 ? Number(t.expires_in) : 3600;
|
|
150
|
+
return { project, installationId, accessToken: t.access_token, refreshToken, expiresAt: now() + expiresIn * 1000, scopes: scopesOf(t.scope) ?? scopes ?? previous?.scopes ?? [] };
|
|
151
|
+
}
|
|
152
|
+
async function stored(project) {
|
|
153
|
+
const t = await tokenStore.get(project);
|
|
154
|
+
if (!t) {
|
|
155
|
+
throw new InstallationRevokedError({
|
|
156
|
+
code: 'not_connected',
|
|
157
|
+
message: `This extension is not connected to the project ${project} (no tokens are stored for it).`,
|
|
158
|
+
hint: 'The customer installs it from usebecky (Extensions), which runs your install route.',
|
|
159
|
+
status: 401,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return t;
|
|
163
|
+
}
|
|
164
|
+
function refresh(project, seen) {
|
|
165
|
+
const running = inflight.get(project);
|
|
166
|
+
if (running)
|
|
167
|
+
return running;
|
|
168
|
+
const run = async () => {
|
|
169
|
+
const current = await stored(project);
|
|
170
|
+
// Another request (or instance) refreshed while we waited: use its tokens.
|
|
171
|
+
if (seen && current.accessToken !== seen.accessToken && current.expiresAt - margin > now())
|
|
172
|
+
return current;
|
|
173
|
+
let t;
|
|
174
|
+
try {
|
|
175
|
+
t = await tokenRequest({ grant_type: 'refresh_token', refresh_token: current.refreshToken });
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
// Only invalid_grant and extension_suspended (a suspension revokes every token for good) mean the install's
|
|
179
|
+
// tokens are dead. invalid_client (a wrong secret after a deploy) or an outage must never cost every customer
|
|
180
|
+
// their connection.
|
|
181
|
+
if (err instanceof TokenError && (err.code === 'invalid_grant' || err.code === 'extension_suspended')) {
|
|
182
|
+
const latest = await tokenStore.get(project);
|
|
183
|
+
// The customer may have reconnected meanwhile: those new tokens stay.
|
|
184
|
+
if (latest && latest.refreshToken !== current.refreshToken)
|
|
185
|
+
return latest;
|
|
186
|
+
if (latest)
|
|
187
|
+
await tokenStore.delete(project);
|
|
188
|
+
if (err.code === 'extension_suspended')
|
|
189
|
+
throw suspendedError(project, err.status);
|
|
190
|
+
throw new InstallationRevokedError({
|
|
191
|
+
code: 'installation_revoked',
|
|
192
|
+
message: `usebecky no longer accepts this extension's tokens for the project ${project}: it was uninstalled, or its access was revoked.`,
|
|
193
|
+
hint: 'The stored tokens were deleted. It works again once the customer installs it again.',
|
|
194
|
+
status: 401,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
throw err;
|
|
198
|
+
}
|
|
199
|
+
const next = toStored(project, current.installationId, t, current);
|
|
200
|
+
const latest = await tokenStore.get(project);
|
|
201
|
+
// A reconnect stored newer tokens while we refreshed: keep those, drop ours.
|
|
202
|
+
if (latest && latest.refreshToken !== current.refreshToken)
|
|
203
|
+
return latest;
|
|
204
|
+
await tokenStore.set(next);
|
|
205
|
+
return next;
|
|
206
|
+
};
|
|
207
|
+
const p = (tokenStore.lock ? tokenStore.lock(project, run) : run()).finally(() => inflight.delete(project));
|
|
208
|
+
inflight.set(project, p);
|
|
209
|
+
return p;
|
|
210
|
+
}
|
|
211
|
+
async function validTokens(project) {
|
|
212
|
+
const t = await stored(project);
|
|
213
|
+
if (t.expiresAt - margin > now())
|
|
214
|
+
return t;
|
|
215
|
+
return refresh(project, t);
|
|
216
|
+
}
|
|
217
|
+
// ---- partner API -------------------------------------------------------------------------
|
|
218
|
+
async function partnerFetch(token, method, path, init = {}) {
|
|
219
|
+
const url = new URL(`${partnerBase}${path.startsWith('/') ? path : `/${path}`}`);
|
|
220
|
+
for (const [k, v] of Object.entries(init.query ?? {}))
|
|
221
|
+
if (v !== undefined && v !== '')
|
|
222
|
+
url.searchParams.set(k, v);
|
|
223
|
+
try {
|
|
224
|
+
return await doFetch(url, {
|
|
225
|
+
method,
|
|
226
|
+
headers: { authorization: `Bearer ${token}`, accept: 'application/json', ...(init.body !== undefined ? { 'content-type': 'application/json' } : {}) },
|
|
227
|
+
body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
throw new PartnerApiError({ code: 'network_error', message: `Could not reach usebecky at ${apiUrl}: ${err.message}`, hint: 'Check USEBECKY_API_URL and your internet connection. Try again in a moment.' });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async function apiRequest(project, method, path, init) {
|
|
235
|
+
let tokens = await validTokens(project);
|
|
236
|
+
let res = await partnerFetch(tokens.accessToken, method, path, init);
|
|
237
|
+
if (res.status === 401) {
|
|
238
|
+
// Expired early, or rotated elsewhere: refresh once and retry.
|
|
239
|
+
tokens = await refresh(project, tokens);
|
|
240
|
+
res = await partnerFetch(tokens.accessToken, method, path, init);
|
|
241
|
+
if (res.status === 401) {
|
|
242
|
+
throw new InstallationRevokedError({ code: 'installation_revoked', message: `usebecky refused this extension's access to the project ${project}, even with fresh tokens.`, hint: 'It was probably uninstalled. It works again once the customer installs it again.', status: 401 });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const body = res.status === 204 ? null : await res.json().catch(() => null);
|
|
246
|
+
if (!res.ok) {
|
|
247
|
+
const e = readErrorBody(body);
|
|
248
|
+
const code = e.code ?? (res.status === 403 ? 'insufficient_scope' : res.status === 429 ? 'rate_limited' : res.status === 404 ? 'not_found' : 'api_error');
|
|
249
|
+
if (code === 'extension_suspended') {
|
|
250
|
+
// The tokens are revoked for good: forget them, unless a newer install stored others meanwhile.
|
|
251
|
+
const latest = await tokenStore.get(project);
|
|
252
|
+
if (latest?.accessToken === tokens.accessToken)
|
|
253
|
+
await tokenStore.delete(project);
|
|
254
|
+
throw suspendedError(project, res.status);
|
|
255
|
+
}
|
|
256
|
+
throw new PartnerApiError({ code, message: e.message ?? `The partner API answered HTTP ${res.status} for ${method} ${path}.`, hint: e.hint ?? partnerErrorHint(code), status: res.status, details: e.details });
|
|
257
|
+
}
|
|
258
|
+
return body;
|
|
259
|
+
}
|
|
260
|
+
function api(project) {
|
|
261
|
+
return {
|
|
262
|
+
installation: () => apiRequest(project, 'GET', '/installation'),
|
|
263
|
+
project: () => apiRequest(project, 'GET', '/project'),
|
|
264
|
+
analyticsSummary: (range = {}) => apiRequest(project, 'GET', '/analytics/summary', { query: { from: range.from, to: range.to } }),
|
|
265
|
+
updateSettings: (settings) => apiRequest(project, 'PUT', '/installation/settings', { body: settings }),
|
|
266
|
+
clearSettings: () => apiRequest(project, 'DELETE', '/installation/settings'),
|
|
267
|
+
request: (method, path, init) => apiRequest(project, method, path, init),
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
// ---- OAuth ---------------------------------------------------------------------------------
|
|
271
|
+
/** install_url's return_url, only when it points at the dashboard (anything else could send people anywhere). */
|
|
272
|
+
function dashboardLink(value) {
|
|
273
|
+
if (!value || value.length > 2000)
|
|
274
|
+
return undefined;
|
|
275
|
+
try {
|
|
276
|
+
const u = new URL(value);
|
|
277
|
+
return u.origin === dashboardOrigin && !u.username && !u.password ? u.toString() : undefined;
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return undefined;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
async function authorizeUrl(opts = {}) {
|
|
284
|
+
const state = opts.state ?? randomToken(24);
|
|
285
|
+
if (state.length < 16)
|
|
286
|
+
throw new ConfigError({ code: 'invalid_option', message: 'authorizeUrl: "state" must be a random, unguessable string of at least 16 characters (or leave it out).' });
|
|
287
|
+
const verifier = createCodeVerifier();
|
|
288
|
+
const project = opts.project && PROJECT_REF.test(opts.project) ? opts.project : undefined;
|
|
289
|
+
const returnUrl = dashboardLink(opts.returnUrl);
|
|
290
|
+
// OpenID: the id_token (listings that create accounts from the sign-in) must repeat this nonce.
|
|
291
|
+
const nonce = randomToken(16);
|
|
292
|
+
await stateStore.set(state, { verifier, project, createdAt: now(), nonce, ...(opts.bindToBrowser ? { browserBound: true } : {}), ...(returnUrl ? { returnUrl } : {}) }, STATE_TTL_SECONDS);
|
|
293
|
+
const url = new URL(authorizeEndpoint);
|
|
294
|
+
url.searchParams.set('response_type', 'code');
|
|
295
|
+
url.searchParams.set('client_id', clientId);
|
|
296
|
+
url.searchParams.set('redirect_uri', redirectUri);
|
|
297
|
+
url.searchParams.set('state', state);
|
|
298
|
+
url.searchParams.set('code_challenge', await codeChallengeFor(verifier));
|
|
299
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
300
|
+
url.searchParams.set('nonce', nonce);
|
|
301
|
+
const scopes = opts.scopes ?? options.scopes;
|
|
302
|
+
if (scopes?.length)
|
|
303
|
+
url.searchParams.set('scope', scopes.join(' '));
|
|
304
|
+
if (project)
|
|
305
|
+
url.searchParams.set('project', project);
|
|
306
|
+
return url.toString();
|
|
307
|
+
}
|
|
308
|
+
async function handleCallback(input) {
|
|
309
|
+
const q = queryOf(input);
|
|
310
|
+
const state = q.get('state') ?? '';
|
|
311
|
+
const error = q.get('error');
|
|
312
|
+
if (error) {
|
|
313
|
+
if (state)
|
|
314
|
+
await stateStore.take(state);
|
|
315
|
+
if (error === 'access_denied')
|
|
316
|
+
throw new OAuthCallbackError({ code: 'access_denied', message: 'The extension was not connected: access was not allowed.', hint: 'Install it again from usebecky whenever you like.', status: 400 });
|
|
317
|
+
// Never show error_description: anyone can put text into this address.
|
|
318
|
+
const code = /^[a-z_]{1,40}$/.test(error) ? error : 'authorization_failed';
|
|
319
|
+
throw new OAuthCallbackError({ code, message: `usebecky could not connect the extension (${code}).`, hint: 'Try installing it again from usebecky.', status: 400 });
|
|
320
|
+
}
|
|
321
|
+
const code = q.get('code');
|
|
322
|
+
if (!code || !state)
|
|
323
|
+
throw new OAuthCallbackError({ code: 'invalid_request', message: 'This address needs the code and state that usebecky adds. Start from your install link.', status: 400 });
|
|
324
|
+
const pending = await stateStore.take(state);
|
|
325
|
+
if (!pending) {
|
|
326
|
+
throw new OAuthCallbackError({ code: 'invalid_state', message: 'This sign-in link has expired or was already used.', hint: 'Start the install again. A sign-in has to finish within 10 minutes.', status: 400 });
|
|
327
|
+
}
|
|
328
|
+
if (pending.browserBound && cookieOf(input, STATE_COOKIE) !== state) {
|
|
329
|
+
throw new OAuthCallbackError({ code: 'invalid_state', message: 'This sign-in was started in another browser (or its cookie is gone).', hint: 'Start the install again in this browser.', status: 400 });
|
|
330
|
+
}
|
|
331
|
+
const t = await tokenRequest({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, code_verifier: pending.verifier });
|
|
332
|
+
// The token answer names the project and the install; GET /installation (any token may call it) adds the
|
|
333
|
+
// project's name, the scopes and the settings.
|
|
334
|
+
const res = await partnerFetch(t.access_token, 'GET', '/installation');
|
|
335
|
+
const body = (await res.json().catch(() => null));
|
|
336
|
+
if (!res.ok || !body || typeof body.id !== 'string' || typeof body.project?.ref !== 'string') {
|
|
337
|
+
const e = readErrorBody(body);
|
|
338
|
+
const code = e.code ?? 'api_error';
|
|
339
|
+
throw new PartnerApiError({ code, message: e.message ?? `Could not load the install (HTTP ${res.status}).`, hint: e.hint ?? partnerErrorHint(code), status: res.status, details: e.details });
|
|
340
|
+
}
|
|
341
|
+
const installation = body;
|
|
342
|
+
const project = installation.project.ref;
|
|
343
|
+
// The account at your service: who allowed access, signed by usebecky (checked before anything is stored).
|
|
344
|
+
let identity;
|
|
345
|
+
if (typeof t.id_token === 'string') {
|
|
346
|
+
identity = await verifyIdTokenWith(t.id_token, { ...tokenOptions(), nonce: pending.nonce });
|
|
347
|
+
if (identity.usebecky_install !== installation.id)
|
|
348
|
+
throw new TokenError({ code: 'invalid_token', message: 'The id_token belongs to another install.', status: 400 });
|
|
349
|
+
}
|
|
350
|
+
const tokens = toStored(project, installation.id, t, undefined, installation.scopes);
|
|
351
|
+
// A refresh with the old tokens finishes first (outside the lock: it may be waiting for it), then the
|
|
352
|
+
// new tokens are written under the lock; a refresh that started earlier never overwrites them.
|
|
353
|
+
await inflight.get(project)?.catch(() => { });
|
|
354
|
+
await (tokenStore.lock ? tokenStore.lock(project, async () => tokenStore.set(tokens)) : tokenStore.set(tokens));
|
|
355
|
+
return { installation, project, scopes: tokens.scopes, state, ...(pending.returnUrl ? { returnUrl: pending.returnUrl } : {}), ...(identity ? { identity } : {}) };
|
|
356
|
+
}
|
|
357
|
+
async function forget(project) {
|
|
358
|
+
await tokenStore.delete(project);
|
|
359
|
+
}
|
|
360
|
+
async function revoke(project) {
|
|
361
|
+
const t = await tokenStore.get(project);
|
|
362
|
+
if (!t)
|
|
363
|
+
return false;
|
|
364
|
+
let ok = false;
|
|
365
|
+
try {
|
|
366
|
+
const res = await doFetch(`${partnerBase}/oauth/revoke`, {
|
|
367
|
+
method: 'POST',
|
|
368
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
369
|
+
body: new URLSearchParams({ token: t.refreshToken, token_type_hint: 'refresh_token', client_id: clientId, client_secret: clientSecret }).toString(),
|
|
370
|
+
});
|
|
371
|
+
ok = res.ok;
|
|
372
|
+
}
|
|
373
|
+
catch { }
|
|
374
|
+
await tokenStore.delete(project);
|
|
375
|
+
return ok;
|
|
376
|
+
}
|
|
377
|
+
// ---- webhooks ------------------------------------------------------------------------------
|
|
378
|
+
function verify(rawBody, headers, opts) {
|
|
379
|
+
return verifyWebhook(rawBody, headers, options.webhookSecret, { now: Math.floor(now() / 1000), ...opts });
|
|
380
|
+
}
|
|
381
|
+
function webhookHandler(handlers, opts = {}) {
|
|
382
|
+
return async (request) => {
|
|
383
|
+
if (request.method !== 'POST')
|
|
384
|
+
return jsonResponse(405, { error: { code: 'method_not_allowed', message: 'usebecky sends webhooks with POST.' } }, { allow: 'POST' });
|
|
385
|
+
if (Number(request.headers.get('content-length') ?? 0) > MAX_WEBHOOK_BYTES)
|
|
386
|
+
return jsonResponse(413, { error: { code: 'payload_too_large', message: 'usebecky webhooks are far smaller than this.' } });
|
|
387
|
+
let event;
|
|
388
|
+
try {
|
|
389
|
+
const raw = new Uint8Array(await request.arrayBuffer());
|
|
390
|
+
if (raw.length > MAX_WEBHOOK_BYTES)
|
|
391
|
+
return jsonResponse(413, { error: { code: 'payload_too_large', message: 'usebecky webhooks are far smaller than this.' } });
|
|
392
|
+
event = await verify(raw, request.headers);
|
|
393
|
+
}
|
|
394
|
+
catch (err) {
|
|
395
|
+
if (err instanceof ExtensionError) {
|
|
396
|
+
if (err.status >= 500)
|
|
397
|
+
console.error(`[usebecky-extension] ${err.message} ${err.hint ?? ''}`);
|
|
398
|
+
return jsonResponse(err.status >= 400 ? err.status : 400, { error: err.toJSON() });
|
|
399
|
+
}
|
|
400
|
+
throw err;
|
|
401
|
+
}
|
|
402
|
+
try {
|
|
403
|
+
if (event.type === 'extension.uninstalled' && opts.forgetOnUninstall !== false) {
|
|
404
|
+
// Only the install the event is about: a late retry must not delete the tokens of a reinstall.
|
|
405
|
+
const current = await tokenStore.get(event.project);
|
|
406
|
+
const id = event.data?.installation_id;
|
|
407
|
+
if (current && (!id || current.installationId === id))
|
|
408
|
+
await tokenStore.delete(event.project);
|
|
409
|
+
}
|
|
410
|
+
if (typeof handlers === 'function')
|
|
411
|
+
await handlers(event);
|
|
412
|
+
else {
|
|
413
|
+
const own = handlers[event.type];
|
|
414
|
+
if (own)
|
|
415
|
+
await own(event);
|
|
416
|
+
if (handlers['*'])
|
|
417
|
+
await handlers['*'](event);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
catch (err) {
|
|
421
|
+
console.error(`[usebecky-extension] Your handler for "${event.type}" (${event.id}) failed: ${err?.message ?? err}`);
|
|
422
|
+
return jsonResponse(500, { error: { code: 'handler_error', message: `The handler for "${event.type}" failed, so usebecky will retry this event.` } });
|
|
423
|
+
}
|
|
424
|
+
return jsonResponse(200, { received: true });
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
function oauthHandlers(opts = {}) {
|
|
428
|
+
const installPath = opts.installPath ?? '/install';
|
|
429
|
+
const stateCookie = (request, value, maxAge) => `${STATE_COOKIE}=${value}; Max-Age=${maxAge}; Path=/; HttpOnly; SameSite=Lax${new URL(request.url).protocol === 'https:' || redirectUri.startsWith('https:') ? '; Secure' : ''}`;
|
|
430
|
+
const withCleared = (request, response) => {
|
|
431
|
+
const headers = new Headers(response.headers);
|
|
432
|
+
headers.append('set-cookie', stateCookie(request, '', 0));
|
|
433
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
434
|
+
};
|
|
435
|
+
return {
|
|
436
|
+
install: async (request) => {
|
|
437
|
+
// usebecky opens install_url with ?project=<ref>&return_url=<the extension's page in the dashboard>.
|
|
438
|
+
const q = new URL(request.url).searchParams;
|
|
439
|
+
const state = randomToken(24);
|
|
440
|
+
const location = await authorizeUrl({ project: q.get('project') ?? undefined, state, bindToBrowser: true, returnUrl: q.get('return_url') ?? undefined });
|
|
441
|
+
return new Response(null, { status: 302, headers: { location, 'cache-control': 'no-store', 'set-cookie': stateCookie(request, state, STATE_TTL_SECONDS) } });
|
|
442
|
+
},
|
|
443
|
+
callback: async (request) => {
|
|
444
|
+
let result;
|
|
445
|
+
try {
|
|
446
|
+
result = await handleCallback(request);
|
|
447
|
+
}
|
|
448
|
+
catch (err) {
|
|
449
|
+
const e = err instanceof ExtensionError
|
|
450
|
+
? err
|
|
451
|
+
: new ExtensionError({ code: 'internal_error', message: 'Something went wrong while connecting the extension.', status: 500 });
|
|
452
|
+
if (!(err instanceof ExtensionError))
|
|
453
|
+
console.error(`[usebecky-extension] OAuth callback failed: ${err?.message ?? err}`);
|
|
454
|
+
const custom = opts.onError ? await opts.onError(e, request) : undefined;
|
|
455
|
+
if (custom)
|
|
456
|
+
return withCleared(request, custom);
|
|
457
|
+
const status = e instanceof OAuthCallbackError ? 400 : e.status >= 400 && e.status < 600 ? (e.status === 401 ? 400 : e.status) : 502;
|
|
458
|
+
const title = e.code === 'access_denied' ? 'Not connected' : 'The extension could not be connected';
|
|
459
|
+
return withCleared(request, errorPage(status, title, `${e.message}${e.hint ? ` ${e.hint}` : ''}`, installPath));
|
|
460
|
+
}
|
|
461
|
+
const custom = opts.onInstalled ? await opts.onInstalled(result, request) : undefined;
|
|
462
|
+
return withCleared(request, custom ?? new Response(null, { status: 302, headers: { location: opts.successUrl ?? '/', 'cache-control': 'no-store' } }));
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
return {
|
|
467
|
+
clientId,
|
|
468
|
+
apiUrl,
|
|
469
|
+
dashboardUrl,
|
|
470
|
+
authorizeEndpoint,
|
|
471
|
+
tokenStore,
|
|
472
|
+
authorizeUrl,
|
|
473
|
+
handleCallback,
|
|
474
|
+
api,
|
|
475
|
+
accessToken: async (project) => (await validTokens(project)).accessToken,
|
|
476
|
+
refresh: (project) => refresh(project),
|
|
477
|
+
revoke,
|
|
478
|
+
forget,
|
|
479
|
+
verifyWebhook: verify,
|
|
480
|
+
oauthHandlers,
|
|
481
|
+
webhookHandler,
|
|
482
|
+
jwks,
|
|
483
|
+
verifyIdToken: (token, opts = {}) => verifyIdTokenWith(token, { ...tokenOptions(), ...opts }),
|
|
484
|
+
verifyLaunchToken: (token) => verifyLaunchTokenWith(token, { ...tokenOptions(), replayGuard }),
|
|
485
|
+
provisionHandler: (provision, opts = {}) => makeProvisionHandler({ webhookSecret: options.webhookSecret, provision, idempotency: opts.idempotency, clock }),
|
|
486
|
+
ssoHandler: (opts) => makeSsoHandler({ ...tokenOptions(), replayGuard, ...opts }),
|
|
487
|
+
uiHandler: (opts) => makeUiHandler({
|
|
488
|
+
webhookSecret: options.webhookSecret,
|
|
489
|
+
pages: opts.pages,
|
|
490
|
+
actions: opts.actions,
|
|
491
|
+
log: opts.log,
|
|
492
|
+
clock,
|
|
493
|
+
// `api` only when asked for: a fields extension has no tokens, and most pages don't need them.
|
|
494
|
+
extend: (ctx) => Object.defineProperty(ctx, 'api', { get: () => api(ctx.project.ref), enumerable: false }),
|
|
495
|
+
}),
|
|
496
|
+
};
|
|
497
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export type FetchHandler = (request: Request) => Promise<Response>;
|
|
2
|
+
/** The parts of Node's IncomingMessage the adapter uses (Express requests are these too). */
|
|
3
|
+
export interface NodeRequestLike {
|
|
4
|
+
method?: string;
|
|
5
|
+
url?: string;
|
|
6
|
+
originalUrl?: string;
|
|
7
|
+
headers: Record<string, string | string[] | undefined>;
|
|
8
|
+
/** Set by body parsers: a Buffer/string from express.raw()/text() works; a parsed object is re-serialized. */
|
|
9
|
+
body?: unknown;
|
|
10
|
+
rawBody?: unknown;
|
|
11
|
+
readableEnded?: boolean;
|
|
12
|
+
/** A TLS socket has `encrypted: true`. */
|
|
13
|
+
socket?: unknown;
|
|
14
|
+
on(event: string, listener: (...args: any[]) => void): unknown;
|
|
15
|
+
}
|
|
16
|
+
/** The parts of Node's ServerResponse the adapter uses. */
|
|
17
|
+
export interface NodeResponseLike {
|
|
18
|
+
statusCode: number;
|
|
19
|
+
headersSent?: boolean;
|
|
20
|
+
setHeader(name: string, value: string | string[]): unknown;
|
|
21
|
+
end(chunk?: Uint8Array | string): unknown;
|
|
22
|
+
}
|
|
23
|
+
export type NodeHandler = (req: NodeRequestLike, res: NodeResponseLike, next?: (err?: unknown) => void) => Promise<void>;
|
|
24
|
+
/** Bodies the adapter reads itself are capped (webhooks are a few KB; nothing else here takes a body). */
|
|
25
|
+
export declare const MAX_BODY_BYTES: number;
|
|
26
|
+
/** Node's IncomingMessage (or an Express request) as a fetch Request. */
|
|
27
|
+
export declare function toFetchRequest(req: NodeRequestLike): Promise<Request>;
|
|
28
|
+
/** Write a fetch Response to Node's ServerResponse. */
|
|
29
|
+
export declare function writeFetchResponse(response: Response, res: NodeResponseLike): Promise<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Run a fetch-style handler in node:http or Express:
|
|
32
|
+
* app.post('/webhooks/usebecky', toNodeHandler(ext.webhookHandler({ ... })))
|
|
33
|
+
* The webhook route needs the raw body: mount it before express.json(), or use express.raw() on it.
|
|
34
|
+
*/
|
|
35
|
+
export declare function toNodeHandler(handler: FetchHandler): NodeHandler;
|
|
36
|
+
export declare function jsonResponse(status: number, body: unknown, headers?: Record<string, string>): Response;
|
|
37
|
+
export declare function escapeHtml(s: string): string;
|
|
38
|
+
/** The plain page the OAuth callback shows when something went wrong (override it with `onError`). */
|
|
39
|
+
export declare function errorPage(status: number, title: string, message: string, retryHref?: string): Response;
|
package/dist/handlers.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Fetch-style handlers ((Request) => Response) run as they are in Hono (`c.req.raw`), Next.js route
|
|
2
|
+
// handlers, Bun, Deno and Cloudflare. toNodeHandler() turns one into a node:http / Express handler.
|
|
3
|
+
/** Bodies the adapter reads itself are capped (webhooks are a few KB; nothing else here takes a body). */
|
|
4
|
+
export const MAX_BODY_BYTES = 1024 * 1024;
|
|
5
|
+
class BodyTooLarge extends Error {
|
|
6
|
+
}
|
|
7
|
+
function readStream(req) {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
const chunks = [];
|
|
10
|
+
let size = 0;
|
|
11
|
+
req.on('data', (c) => {
|
|
12
|
+
const bytes = typeof c === 'string' ? new TextEncoder().encode(c) : c;
|
|
13
|
+
size += bytes.length;
|
|
14
|
+
if (size > MAX_BODY_BYTES)
|
|
15
|
+
reject(new BodyTooLarge());
|
|
16
|
+
else
|
|
17
|
+
chunks.push(bytes);
|
|
18
|
+
});
|
|
19
|
+
req.on('end', () => {
|
|
20
|
+
const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
21
|
+
let at = 0;
|
|
22
|
+
for (const c of chunks) {
|
|
23
|
+
out.set(c, at);
|
|
24
|
+
at += c.length;
|
|
25
|
+
}
|
|
26
|
+
resolve(out);
|
|
27
|
+
});
|
|
28
|
+
req.on('error', reject);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async function bodyOf(req) {
|
|
32
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
33
|
+
if (method === 'GET' || method === 'HEAD')
|
|
34
|
+
return undefined;
|
|
35
|
+
for (const b of [req.rawBody, req.body]) {
|
|
36
|
+
if (typeof b === 'string' || b instanceof Uint8Array)
|
|
37
|
+
return b;
|
|
38
|
+
}
|
|
39
|
+
if (!req.readableEnded)
|
|
40
|
+
return readStream(req);
|
|
41
|
+
// express.json() already consumed and parsed it. usebecky signs compact JSON, so this usually gives the
|
|
42
|
+
// same bytes back; if verification fails, mount the webhook route before express.json().
|
|
43
|
+
if (req.body !== undefined && req.body !== null)
|
|
44
|
+
return JSON.stringify(req.body);
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
/** Node's IncomingMessage (or an Express request) as a fetch Request. */
|
|
48
|
+
export async function toFetchRequest(req) {
|
|
49
|
+
const proto = String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim() || (req.socket?.encrypted ? 'https' : 'http');
|
|
50
|
+
const host = String(req.headers['x-forwarded-host'] ?? req.headers.host ?? 'localhost').split(',')[0].trim();
|
|
51
|
+
const url = new URL(req.originalUrl ?? req.url ?? '/', `${proto}://${host}`);
|
|
52
|
+
const headers = new Headers();
|
|
53
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
54
|
+
if (v === undefined || k.startsWith(':'))
|
|
55
|
+
continue;
|
|
56
|
+
if (Array.isArray(v))
|
|
57
|
+
for (const x of v)
|
|
58
|
+
headers.append(k, x);
|
|
59
|
+
else
|
|
60
|
+
headers.set(k, String(v));
|
|
61
|
+
}
|
|
62
|
+
const body = await bodyOf(req);
|
|
63
|
+
return new Request(url, { method: req.method ?? 'GET', headers, body: body });
|
|
64
|
+
}
|
|
65
|
+
/** Write a fetch Response to Node's ServerResponse. */
|
|
66
|
+
export async function writeFetchResponse(response, res) {
|
|
67
|
+
res.statusCode = response.status;
|
|
68
|
+
const cookies = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : [];
|
|
69
|
+
response.headers.forEach((value, key) => {
|
|
70
|
+
if (key.toLowerCase() !== 'set-cookie')
|
|
71
|
+
res.setHeader(key, value);
|
|
72
|
+
});
|
|
73
|
+
if (cookies.length)
|
|
74
|
+
res.setHeader('set-cookie', cookies);
|
|
75
|
+
res.end(new Uint8Array(await response.arrayBuffer()));
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Run a fetch-style handler in node:http or Express:
|
|
79
|
+
* app.post('/webhooks/usebecky', toNodeHandler(ext.webhookHandler({ ... })))
|
|
80
|
+
* The webhook route needs the raw body: mount it before express.json(), or use express.raw() on it.
|
|
81
|
+
*/
|
|
82
|
+
export function toNodeHandler(handler) {
|
|
83
|
+
return async (req, res, next) => {
|
|
84
|
+
try {
|
|
85
|
+
await writeFetchResponse(await handler(await toFetchRequest(req)), res);
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
if (err instanceof BodyTooLarge)
|
|
89
|
+
return writeFetchResponse(jsonResponse(413, { error: { code: 'payload_too_large', message: 'The request body is too large.' } }), res);
|
|
90
|
+
if (next)
|
|
91
|
+
return next(err);
|
|
92
|
+
if (!res.headersSent) {
|
|
93
|
+
res.statusCode = 500;
|
|
94
|
+
res.setHeader('content-type', 'application/json');
|
|
95
|
+
}
|
|
96
|
+
res.end(JSON.stringify({ error: { code: 'internal_error', message: 'Something went wrong.' } }));
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function jsonResponse(status, body, headers = {}) {
|
|
101
|
+
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers } });
|
|
102
|
+
}
|
|
103
|
+
export function escapeHtml(s) {
|
|
104
|
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
105
|
+
}
|
|
106
|
+
/** The plain page the OAuth callback shows when something went wrong (override it with `onError`). */
|
|
107
|
+
export function errorPage(status, title, message, retryHref) {
|
|
108
|
+
const retry = retryHref ? `<p><a href="${escapeHtml(retryHref)}">Try again</a></p>` : '';
|
|
109
|
+
const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title>
|
|
110
|
+
<style>:root{color-scheme:light dark}body{font:16px/1.5 system-ui,sans-serif;margin:0;padding:48px 20px;background:Canvas;color:CanvasText}main{max-width:560px;margin:0 auto}h1{font-size:22px;margin:0 0 8px}a{color:#b8420f}@media (prefers-color-scheme:dark){a{color:#ff6a2c}}</style></head>
|
|
111
|
+
<body><main><h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>${retry}</main></body></html>`;
|
|
112
|
+
return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } });
|
|
113
|
+
}
|