@pexis/auth 0.0.0-stage → 0.1.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,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Intelligant AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ The spec text in packages/spec/actions.md is licensed under CC BY 4.0.
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # @pexis/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Pexis plugin: sign-in with Google, Microsoft, GitHub, Apple or any OpenID Connect provider.
4
+
5
+ ```bash
6
+ npm install @pexis/auth
7
+ ```
8
+
9
+ ```tsx
10
+ import { auth, google, requireUser, SignInLink } from '@pexis/auth';
11
+ import { sessions } from '@pexis/kit/plugins';
12
+
13
+ createApp({
14
+ plugins: [sessions(), auth({ providers: [google({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! })] })],
15
+ });
16
+
17
+ // A page for signed-in people: load: (ctx) => requireUser(ctx) ?? loadAccount(ctx.user!)
18
+ // A link: <SignInLink provider="google">Sign in with Google</SignInLink>
19
+ ```
20
+
21
+ Before something sensitive, `requireRecentSignIn(ctx, 300)` sends people whose sign-in is older than five minutes to sign in again; the provider is asked for credentials, and OpenID Connect providers must prove it with a recent `auth_time`. Guard the action itself with `signedInWithin` from `@pexis/sessions`.
22
+
23
+ `oauthServer()` from `@pexis/auth/server` (experimental) lets MCP clients sign in as a person through OAuth 2.1: only clients you list, consent on your site, PKCE, tokens checked only at `/pexis/mcp`, rotating refresh tokens, and a connected-apps page where people remove apps. Pass `loadUser` (checked again on every request) and `store: oauthStore(db)` from `@pexis/data` for several servers.
24
+
25
+ PKCE, single-use state bound to the browser, nonces, and verified ID tokens. Secrets come from environment variables. Sign-out is a POST, so other sites cannot sign people out.
26
+
27
+ ## More
28
+
29
+ - The guide for building with Pexis: [`AGENTS.md` in the `@pexis/kit` package](https://github.com/pexis-dev/pexis/blob/main/packages/pexis/AGENTS.md)
30
+ - Source, issues and the other packages: https://github.com/pexis-dev/pexis
31
+
32
+ MIT licensed. Part of [Pexis](https://github.com/pexis-dev/pexis/blob/main/README.md), by Intelligant AI. Not published to npm yet.
@@ -0,0 +1,52 @@
1
+ import { type Child, type Context, type Markup, type Plugin, type Redirect } from '@pexis/core';
2
+ import { type User } from '@pexis/sessions';
3
+ import type { Profile, Provider } from './providers.js';
4
+ export { apple, github, google, microsoft, oidc, type AppleOptions, type OidcOptions, type Profile, type Provider, type TokenResponse } from './providers.js';
5
+ export { decodeJwt, verifyJwt, KeySet, JwtError, signEs256, base64urlEncode, type Claims, type Jwk } from './jwt.js';
6
+ export interface AuthOptions {
7
+ providers: Provider[];
8
+ /**
9
+ * Turns a provider profile into your user, or returns null to refuse the
10
+ * sign-in. Use it to find or create the user in your database. Default: a
11
+ * user whose id is "<provider>:<subject>".
12
+ */
13
+ onSignIn?: (profile: Profile & {
14
+ provider: string;
15
+ }, ctx: Context) => User | null | Promise<User | null>;
16
+ /** Where the auth routes live. Default /auth. */
17
+ basePath?: string;
18
+ /** For tests: the fetch used to reach providers. */
19
+ fetch?: typeof fetch;
20
+ }
21
+ /** Only paths on this site: never another origin, never "//host". */
22
+ export declare function safeReturnTo(value: string | null | undefined, fallback?: string): string;
23
+ /** A link that starts signing in with a provider. */
24
+ export declare function SignInLink({ provider, returnTo, fresh, children }: {
25
+ provider: string;
26
+ returnTo?: string;
27
+ fresh?: boolean;
28
+ children?: Child;
29
+ }): Markup;
30
+ /** A sign-out button. Signing out is a POST, so other sites cannot sign people out. */
31
+ export declare function SignOutButton({ children }: {
32
+ children?: Child;
33
+ }): Markup;
34
+ /**
35
+ * For a page's load(): sends visitors who are not signed in to the sign-in
36
+ * page, and back here afterwards.
37
+ *
38
+ * load: (ctx) => requireUser(ctx) ?? loadAccount(ctx.user!)
39
+ */
40
+ export declare function requireUser(ctx?: Context): Redirect | null;
41
+ /**
42
+ * For the page in front of something sensitive (changing an email, deleting
43
+ * an account): sends people who signed in more than `seconds` ago (default
44
+ * five minutes) to sign in again, and back here afterwards. The provider is
45
+ * asked to make them enter their credentials again, and providers that speak
46
+ * OpenID Connect must prove it. Guard the action itself too, with
47
+ * permission: (ctx) => signedInWithin(ctx, 300) from @pexis/sessions.
48
+ *
49
+ * load: (ctx) => requireRecentSignIn(ctx) ?? loadSettings(ctx.user!)
50
+ */
51
+ export declare function requireRecentSignIn(ctx?: Context, seconds?: number): Redirect | null;
52
+ export declare function auth(options: AuthOptions): Plugin;
package/dist/index.js ADDED
@@ -0,0 +1,363 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "@pexis/core/jsx-runtime";
2
+ // Sign-in with external providers, on top of @pexis/sessions.
3
+ //
4
+ // The flow is the OAuth 2.0 authorization code flow with PKCE, plus OpenID
5
+ // Connect where the provider supports it:
6
+ // 1. /auth/<provider>/start puts the state, the PKCE verifier and the nonce
7
+ // in an HttpOnly cookie on this browser (not in server memory, so any
8
+ // instance can finish the sign-in) and sends the person to the provider.
9
+ // 2. /auth/<provider>/callback checks the state against that cookie, exchanges
10
+ // the code (with the PKCE verifier), verifies the ID token's signature and
11
+ // claims, signs the person in (a new session ID), and sends them back to a
12
+ // page on this site.
13
+ import { definePage, definePlugin, getContext, rateLimiter, redirect, } from '@pexis/core';
14
+ import { parseCookies, randomToken, sha256, signedInWithin } from '@pexis/sessions';
15
+ import { base64urlDecode, base64urlEncode, KeySet, verifyJwt } from './jwt.js';
16
+ export { apple, github, google, microsoft, oidc } from './providers.js';
17
+ export { decodeJwt, verifyJwt, KeySet, JwtError, signEs256, base64urlEncode } from './jwt.js';
18
+ function encodeFlow(flow) {
19
+ return base64urlEncode(JSON.stringify(flow));
20
+ }
21
+ /** Reads the flow cookie, or null when it is missing or not one this code wrote. */
22
+ function decodeFlow(value) {
23
+ if (!value)
24
+ return null;
25
+ try {
26
+ const f = JSON.parse(new TextDecoder().decode(base64urlDecode(value)));
27
+ const strings = ['state', 'provider', 'verifier', 'nonce', 'returnTo'];
28
+ if (!strings.every((k) => typeof f[k] === 'string' && f[k]))
29
+ return null;
30
+ if (typeof f.expiresAt !== 'number' || typeof f.startedAt !== 'number' || typeof f.fresh !== 'boolean')
31
+ return null;
32
+ return { ...f, returnTo: safeReturnTo(f.returnTo) };
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ const FLOW_TTL_MS = 10 * 60 * 1000;
39
+ // A provider's form_post callback carries a code, a state and perhaps an ID
40
+ // token and a user object: a few kilobytes.
41
+ const MAX_CALLBACK_BYTES = 64_000;
42
+ const START_LIMIT = { limit: 20, windowSeconds: 10 * 60 };
43
+ /** Reads a request body as text, or returns null once it passes max bytes, without reading the rest. */
44
+ async function readLimited(request, max) {
45
+ const declared = Number(request.headers.get('content-length') ?? '0');
46
+ if (declared > max)
47
+ return null;
48
+ if (!request.body)
49
+ return '';
50
+ const reader = request.body.getReader();
51
+ const chunks = [];
52
+ let size = 0;
53
+ for (;;) {
54
+ const { done, value } = await reader.read();
55
+ if (done)
56
+ break;
57
+ size += value.byteLength;
58
+ if (size > max) {
59
+ await reader.cancel();
60
+ return null;
61
+ }
62
+ chunks.push(value);
63
+ }
64
+ const bytes = new Uint8Array(size);
65
+ let offset = 0;
66
+ for (const c of chunks) {
67
+ bytes.set(c, offset);
68
+ offset += c.byteLength;
69
+ }
70
+ return new TextDecoder().decode(bytes);
71
+ }
72
+ /** Only paths on this site: never another origin, never "//host". */
73
+ export function safeReturnTo(value, fallback = '/') {
74
+ if (!value || value.length > 2000)
75
+ return fallback;
76
+ if (!value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\'))
77
+ return fallback;
78
+ // eslint-disable-next-line no-control-regex
79
+ if (/[\u0000-\u001f\\]/.test(value))
80
+ return fallback;
81
+ return value;
82
+ }
83
+ const MESSAGES = {
84
+ denied: 'Sign-in was canceled.',
85
+ expired: 'That sign-in took too long or was already used. Please try again.',
86
+ failed: 'Sign-in could not be completed. Please try again.',
87
+ refused: 'This account cannot sign in here.',
88
+ stale: 'The sign-in provider did not ask for your password again. Please try again.',
89
+ };
90
+ let base = '/auth';
91
+ /** A link that starts signing in with a provider. */
92
+ export function SignInLink({ provider, returnTo, fresh, children }) {
93
+ const params = new URLSearchParams();
94
+ if (returnTo)
95
+ params.set('returnTo', safeReturnTo(returnTo));
96
+ if (fresh)
97
+ params.set('fresh', '1');
98
+ const query = params.size ? `?${params}` : '';
99
+ return _jsx("a", { href: `${base}/${encodeURIComponent(provider)}/start${query}`, children: children ?? 'Sign in' });
100
+ }
101
+ /** A sign-out button. Signing out is a POST, so other sites cannot sign people out. */
102
+ export function SignOutButton({ children }) {
103
+ return (_jsx("form", { method: "post", action: `${base}/sign-out`, children: _jsx("button", { type: "submit", children: children ?? 'Sign out' }) }));
104
+ }
105
+ /**
106
+ * For a page's load(): sends visitors who are not signed in to the sign-in
107
+ * page, and back here afterwards.
108
+ *
109
+ * load: (ctx) => requireUser(ctx) ?? loadAccount(ctx.user!)
110
+ */
111
+ export function requireUser(ctx = getContext()) {
112
+ if (ctx.user)
113
+ return null;
114
+ return redirect(`${base}/sign-in?returnTo=${encodeURIComponent(ctx.url.pathname + ctx.url.search)}`);
115
+ }
116
+ /**
117
+ * For the page in front of something sensitive (changing an email, deleting
118
+ * an account): sends people who signed in more than `seconds` ago (default
119
+ * five minutes) to sign in again, and back here afterwards. The provider is
120
+ * asked to make them enter their credentials again, and providers that speak
121
+ * OpenID Connect must prove it. Guard the action itself too, with
122
+ * permission: (ctx) => signedInWithin(ctx, 300) from @pexis/sessions.
123
+ *
124
+ * load: (ctx) => requireRecentSignIn(ctx) ?? loadSettings(ctx.user!)
125
+ */
126
+ export function requireRecentSignIn(ctx = getContext(), seconds = 300) {
127
+ const notSignedIn = requireUser(ctx);
128
+ if (notSignedIn)
129
+ return notSignedIn;
130
+ if (signedInWithin(ctx, seconds))
131
+ return null;
132
+ return redirect(`${base}/sign-in?fresh=1&returnTo=${encodeURIComponent(ctx.url.pathname + ctx.url.search)}`);
133
+ }
134
+ export function auth(options) {
135
+ const providers = new Map();
136
+ for (const p of options.providers) {
137
+ if (providers.has(p.id))
138
+ throw new Error(`auth(): two providers are named "${p.id}".`);
139
+ if (!p.clientId)
140
+ throw new Error(`auth(): the ${p.name} provider needs a clientId.`);
141
+ if (!p.issuer && (!p.authorizationEndpoint || !p.tokenEndpoint))
142
+ throw new Error(`auth(): ${p.name} needs an issuer, or authorization and token endpoints.`);
143
+ providers.set(p.id, p);
144
+ }
145
+ const basePath = (options.basePath ?? '/auth').replace(/\/$/, '');
146
+ if (!/^\/[a-z0-9/_-]*$/.test(basePath))
147
+ throw new Error('auth(): basePath must be a simple path such as /auth.');
148
+ const doFetch = options.fetch ?? fetch;
149
+ const startLimiter = rateLimiter(START_LIMIT);
150
+ const discovered = new Map();
151
+ async function endpoints(p) {
152
+ let pending = discovered.get(p.id);
153
+ if (!pending) {
154
+ pending = (async () => {
155
+ let found;
156
+ if (p.issuer && (!p.authorizationEndpoint || !p.tokenEndpoint || (p.oidc && !p.jwksUri))) {
157
+ const res = await doFetch(`${p.issuer.replace(/\/$/, '')}/.well-known/openid-configuration`, { headers: { accept: 'application/json' } });
158
+ if (!res.ok)
159
+ throw new Error(`${p.name}: discovery failed (${res.status}).`);
160
+ const doc = (await res.json());
161
+ // A fixed issuer must match exactly; multi-tenant providers check per token.
162
+ if (!p.issuerCheck && doc.issuer !== p.issuer)
163
+ throw new Error(`${p.name}: discovery issuer ${String(doc.issuer)} does not match ${p.issuer}.`);
164
+ for (const url of [doc.authorization_endpoint, doc.token_endpoint, doc.jwks_uri]) {
165
+ if (url !== undefined && !/^https:\/\//.test(url) && !p.issuer.startsWith('http://localhost'))
166
+ throw new Error(`${p.name}: endpoints must use https.`);
167
+ }
168
+ found = {
169
+ authorizationEndpoint: p.authorizationEndpoint ?? doc.authorization_endpoint ?? '',
170
+ tokenEndpoint: p.tokenEndpoint ?? doc.token_endpoint ?? '',
171
+ ...((p.jwksUri ?? doc.jwks_uri) ? { jwksUri: (p.jwksUri ?? doc.jwks_uri) } : {}),
172
+ };
173
+ }
174
+ else {
175
+ found = { authorizationEndpoint: p.authorizationEndpoint, tokenEndpoint: p.tokenEndpoint, ...(p.jwksUri ? { jwksUri: p.jwksUri } : {}) };
176
+ }
177
+ if (!found.authorizationEndpoint || !found.tokenEndpoint)
178
+ throw new Error(`${p.name}: missing endpoints.`);
179
+ if (found.jwksUri)
180
+ found.keys = new KeySet(found.jwksUri, doFetch);
181
+ return found;
182
+ })();
183
+ // Do not cache a failure: try discovery again next time.
184
+ pending.catch(() => discovered.delete(p.id));
185
+ discovered.set(p.id, pending);
186
+ }
187
+ return pending;
188
+ }
189
+ return definePlugin({
190
+ name: 'auth',
191
+ requires: ['sessions'],
192
+ setup(api) {
193
+ base = basePath;
194
+ // Starting a sign-in has an effect, so browsers must not prefetch it.
195
+ api.noPrefetch(`${basePath}/`);
196
+ const origin = api.config.origin;
197
+ const secure = origin.startsWith('https://');
198
+ const bindingName = secure ? '__Host-pexis_auth' : 'pexis_auth';
199
+ const callbackUrl = (p) => `${origin}${basePath}/${p.id}/callback`;
200
+ // Apple posts its callback from its own origin; allow that one form post.
201
+ if ([...providers.values()].some((p) => p.responseMode === 'form_post'))
202
+ api.trustOrigin('https://appleid.apple.com');
203
+ const bindingCookie = (value, maxAge, crossSitePost) => [
204
+ `${bindingName}=${value}`,
205
+ 'Path=/',
206
+ 'HttpOnly',
207
+ // A form_post callback is a cross-site POST, which only carries SameSite=None cookies.
208
+ crossSitePost && secure ? 'SameSite=None' : 'SameSite=Lax',
209
+ `Max-Age=${maxAge}`,
210
+ secure ? 'Secure' : '',
211
+ ]
212
+ .filter(Boolean)
213
+ .join('; ');
214
+ const failWith = (code, returnTo = '/') => new Response(null, {
215
+ status: 303,
216
+ headers: { location: `${basePath}/sign-in?error=${code}&returnTo=${encodeURIComponent(returnTo)}`, 'cache-control': 'no-store' },
217
+ });
218
+ api.route('GET', `${basePath}/:provider/start`, async (ctx) => {
219
+ const p = providers.get(ctx.params.provider ?? '');
220
+ if (!p)
221
+ return new Response('Unknown sign-in provider.', { status: 404 });
222
+ // Each start sends this app's client to the provider; one visitor
223
+ // should not be able to do that without limit.
224
+ const limited = await startLimiter.hit(ctx.clientAddress, 'sign-in-start');
225
+ if (!limited.allowed)
226
+ return new Response('Too many sign-in attempts. Try again shortly.', { status: 429, headers: { 'retry-after': String(limited.retryAfter) } });
227
+ const found = await endpoints(p);
228
+ const state = randomToken();
229
+ const verifier = randomToken(48);
230
+ const nonce = randomToken();
231
+ const returnTo = safeReturnTo(ctx.url.searchParams.get('returnTo'));
232
+ const fresh = ctx.url.searchParams.get('fresh') === '1';
233
+ const flow = encodeFlow({ state, provider: p.id, verifier, nonce, returnTo, expiresAt: Date.now() + FLOW_TTL_MS, fresh, startedAt: Date.now() });
234
+ const challenge = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
235
+ const url = new URL(found.authorizationEndpoint);
236
+ const params = {
237
+ response_type: 'code',
238
+ client_id: p.clientId,
239
+ redirect_uri: callbackUrl(p),
240
+ scope: p.scopes.join(' '),
241
+ state,
242
+ code_challenge: btoa(String.fromCharCode(...challenge)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''),
243
+ code_challenge_method: 'S256',
244
+ ...(p.oidc ? { nonce } : {}),
245
+ ...(p.responseMode === 'form_post' ? { response_mode: 'form_post' } : {}),
246
+ ...p.authorizationParams,
247
+ // Signing in again: ask the provider for credentials, not a remembered session.
248
+ ...(fresh ? { prompt: 'login', ...(p.oidc ? { max_age: '0' } : {}) } : {}),
249
+ };
250
+ for (const [k, v] of Object.entries(params))
251
+ url.searchParams.set(k, v);
252
+ return new Response(null, {
253
+ status: 303,
254
+ headers: { location: url.href, 'set-cookie': bindingCookie(flow, FLOW_TTL_MS / 1000, p.responseMode === 'form_post'), 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' },
255
+ });
256
+ });
257
+ const callback = async (ctx) => {
258
+ const p = providers.get(ctx.params.provider ?? '');
259
+ if (!p)
260
+ return new Response('Unknown sign-in provider.', { status: 404 });
261
+ let fields;
262
+ if (ctx.request.method === 'POST') {
263
+ const text = await readLimited(ctx.request, MAX_CALLBACK_BYTES);
264
+ if (text === null)
265
+ return new Response('Request body too large.', { status: 413 });
266
+ fields = Object.fromEntries(new URLSearchParams(text));
267
+ }
268
+ else {
269
+ fields = Object.fromEntries(ctx.url.searchParams);
270
+ }
271
+ const state = fields.state ?? '';
272
+ // Cleared whatever happens next, so the browser holds a flow only once.
273
+ const clear = bindingCookie('', 0, p.responseMode === 'form_post');
274
+ const done = (res) => {
275
+ res.headers.append('set-cookie', clear);
276
+ return res;
277
+ };
278
+ const flow = decodeFlow(parseCookies(ctx.request.headers.get('cookie'))[bindingName]);
279
+ // The state must come back to the same browser that started it.
280
+ if (!flow || !state || (await sha256(flow.state)) !== (await sha256(state)))
281
+ return done(failWith('expired', flow?.returnTo));
282
+ if (flow.expiresAt < Date.now() || flow.provider !== p.id)
283
+ return done(failWith('expired', flow.returnTo));
284
+ if (fields.error)
285
+ return done(failWith(fields.error === 'access_denied' ? 'denied' : 'failed', flow.returnTo));
286
+ if (!fields.code)
287
+ return done(failWith('failed', flow.returnTo));
288
+ try {
289
+ const found = await endpoints(p);
290
+ const secret = typeof p.clientSecret === 'function' ? await p.clientSecret() : p.clientSecret;
291
+ const body = new URLSearchParams({
292
+ grant_type: 'authorization_code',
293
+ code: fields.code,
294
+ redirect_uri: callbackUrl(p),
295
+ client_id: p.clientId,
296
+ code_verifier: flow.verifier,
297
+ });
298
+ const headers = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };
299
+ if (secret && p.tokenAuth === 'basic')
300
+ headers.authorization = `Basic ${btoa(`${encodeURIComponent(p.clientId)}:${encodeURIComponent(secret)}`)}`;
301
+ else if (secret)
302
+ body.set('client_secret', secret);
303
+ const res = await doFetch(found.tokenEndpoint, { method: 'POST', headers, body });
304
+ if (!res.ok)
305
+ throw new Error(`${p.name} token request failed (${res.status}).`);
306
+ const tokens = (await res.json());
307
+ let claims;
308
+ if (p.oidc) {
309
+ if (!tokens.id_token || !found.keys)
310
+ throw new Error(`${p.name} returned no ID token.`);
311
+ claims = await verifyJwt(tokens.id_token, found.keys, { issuer: p.issuerCheck ?? p.issuer, audience: p.clientId, nonce: flow.nonce });
312
+ // A provider that skipped the credentials (an old session) has not
313
+ // proved the person is here now: auth_time must be after the start.
314
+ if (flow.fresh) {
315
+ const authTime = typeof claims.auth_time === 'number' ? claims.auth_time * 1000 : 0;
316
+ if (authTime < flow.startedAt - 60_000)
317
+ return done(failWith('stale', flow.returnTo));
318
+ }
319
+ }
320
+ const profile = await p.profile({ ...(claims ? { claims } : {}), tokens, fetch: doFetch, form: fields });
321
+ const user = options.onSignIn
322
+ ? await options.onSignIn({ ...profile, provider: p.id }, ctx)
323
+ : {
324
+ id: `${p.id}:${profile.subject}`,
325
+ provider: p.id,
326
+ emailVerified: profile.emailVerified,
327
+ ...(profile.email ? { email: profile.email } : {}),
328
+ ...(profile.name ? { name: profile.name } : {}),
329
+ ...(profile.picture ? { picture: profile.picture } : {}),
330
+ };
331
+ if (!user)
332
+ return done(failWith('refused', flow.returnTo));
333
+ ctx.session.signIn(user);
334
+ return done(new Response(null, { status: 303, headers: { location: flow.returnTo, 'cache-control': 'no-store' } }));
335
+ }
336
+ catch (error) {
337
+ // Details stay in the server log; the person sees a plain message.
338
+ console.error(`[pexis] ${p.name} sign-in failed:`, error);
339
+ return done(failWith('failed', flow.returnTo));
340
+ }
341
+ };
342
+ api.route('GET', `${basePath}/:provider/callback`, callback);
343
+ api.route('POST', `${basePath}/:provider/callback`, callback);
344
+ api.route('POST', `${basePath}/sign-out`, (ctx) => {
345
+ ctx.session.signOut();
346
+ return new Response(null, { status: 303, headers: { location: '/', 'cache-control': 'no-store' } });
347
+ });
348
+ api.page(definePage({
349
+ path: `${basePath}/sign-in`,
350
+ index: false,
351
+ load: (ctx) => ({
352
+ returnTo: safeReturnTo(ctx.url.searchParams.get('returnTo')),
353
+ error: MESSAGES[ctx.url.searchParams.get('error') ?? ''] ?? null,
354
+ user: ctx.user,
355
+ fresh: ctx.url.searchParams.get('fresh') === '1',
356
+ }),
357
+ head: { title: 'Sign in', description: 'Sign in to continue.' },
358
+ render: ({ data }) => (_jsxs(_Fragment, { children: [_jsx("h1", { children: "Sign in" }), data.error ? _jsx("p", { role: "alert", children: data.error }) : null, data.fresh ? _jsx("p", { children: "For your security, sign in again to continue." }) : null, data.user && !data.fresh ? (_jsxs(_Fragment, { children: [_jsxs("p", { children: ["You are signed in", data.user.name ? ` as ${data.user.name}` : '', "."] }), _jsx(SignOutButton, {})] })) : (_jsx("ul", { children: [...providers.values()].map((p) => (_jsx("li", { children: _jsxs(SignInLink, { provider: p.id, returnTo: data.returnTo, fresh: data.fresh, children: ["Continue with ", p.name] }) }))) }))] })),
359
+ }));
360
+ },
361
+ });
362
+ }
363
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,EAAE;AACF,2EAA2E;AAC3E,0CAA0C;AAC1C,4EAA4E;AAC5E,yEAAyE;AACzE,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,wBAAwB;AAExB,OAAO,EACL,UAAU,EAEV,YAAY,EACZ,UAAU,EACV,WAAW,EACX,QAAQ,GAKT,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,cAAc,EAAa,MAAM,iBAAiB,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,EAAE,SAAS,EAAe,MAAM,UAAU,CAAC;AAG5F,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAwF,MAAM,gBAAgB,CAAC;AAC9J,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAyB,MAAM,UAAU,CAAC;AAoCrH,SAAS,UAAU,CAAC,IAAU;IAC5B,OAAO,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,oFAAoF;AACpF,SAAS,UAAU,CAAC,KAAyB;IAC3C,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,IAAI,CAAC;QACH,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAA4B,CAAC;QAClG,MAAM,OAAO,GAAG,CAAC,OAAO,EAAE,UA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CAAC,CAClC,uBACE,MAAC,UAAU,IAAC,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,+BACrD,CAAC,CAAC,IAAI,IACV,GACV,CACN,CAAC,GACC,CACN,IACA,CACJ;aACF,CAAC,CACH,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
package/dist/jwt.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ export type Claims = Record<string, unknown> & {
2
+ iss?: string;
3
+ sub?: string;
4
+ aud?: string | string[];
5
+ azp?: string;
6
+ exp?: number;
7
+ iat?: number;
8
+ nbf?: number;
9
+ nonce?: string;
10
+ };
11
+ export interface JoseHeader {
12
+ alg: string;
13
+ kid?: string;
14
+ typ?: string;
15
+ }
16
+ export interface Jwk {
17
+ kty: string;
18
+ kid?: string;
19
+ alg?: string;
20
+ use?: string;
21
+ n?: string;
22
+ e?: string;
23
+ crv?: string;
24
+ x?: string;
25
+ y?: string;
26
+ }
27
+ export declare class JwtError extends Error {
28
+ }
29
+ export declare function base64urlEncode(bytes: Uint8Array | string): string;
30
+ export declare function base64urlDecode(text: string): Uint8Array<ArrayBuffer>;
31
+ export declare function decodeJwt(token: string): {
32
+ header: JoseHeader;
33
+ claims: Claims;
34
+ signingInput: string;
35
+ signature: Uint8Array<ArrayBuffer>;
36
+ };
37
+ /** Fetches and caches a provider's signing keys. */
38
+ export declare class KeySet {
39
+ private keys;
40
+ private fetchedAt;
41
+ private readonly url;
42
+ private readonly fetch;
43
+ constructor(url: string, fetcher?: typeof fetch);
44
+ private loading;
45
+ private load;
46
+ private fetchKeys;
47
+ get(kid: string): Promise<Jwk>;
48
+ }
49
+ export interface Expectations {
50
+ /** Exact issuer, or a check for providers whose issuer varies (Microsoft). */
51
+ issuer: string | string[] | ((iss: string, claims: Claims) => boolean);
52
+ audience: string;
53
+ nonce?: string;
54
+ /** Allowed clock difference. Default 60 seconds. */
55
+ skewSeconds?: number;
56
+ now?: number;
57
+ }
58
+ export declare function verifyJwt(token: string, keys: {
59
+ get(kid: string): Promise<Jwk>;
60
+ }, expect: Expectations): Promise<Claims>;
61
+ /** Signs an ES256 token with a PKCS#8 PEM private key, for Apple's client secret. */
62
+ export declare function signEs256(header: Record<string, unknown>, claims: Record<string, unknown>, pem: string): Promise<string>;