Repository navigation
feat: account 0.1 #67
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
85ac5fe
feat: server-side portion of github oauth
PhilipTrauner 931a9a6
Merge branch 'main' into feat/account-0.1
pierosavi 0435f88
Clear the browser cache when the GitHub session changes
pierosavi e9921e5
Fix GitHub routes without a configured app and after declining sign-in
pierosavi d813146
Keep the GitHub session through timeouts and outages
pierosavi 66f5520
Check the account name before using up the refresh token
pierosavi e7cc245
Revoke the GitHub token on sign-out before the cookie is cleared
pierosavi 4b39d13
Accept token responses without expires_in
pierosavi e5bdf31
Check the sign-in state before showing GitHub's error
pierosavi 62bc00e
Merge branch 'main' into feat/account-0.1
pierosavi 2697e30
Fix declined sign-in test
pierosavi fe9bbd8
Keep session when sign-out fails
pierosavi 552cd51
Add sign-in menu
pierosavi 599a7cf
Add account page
pierosavi ac6f618
Put account behind feature flag
pierosavi e343803
Update src/pages/vendor/github/callback.ts
pierosavi 2ce826e
Fix account-provider visited state style
pierosavi 18b64df
Update src/styles/account.css
pierosavi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| --- | ||
| import GitHubMark from "../assets/github-mark.svg"; | ||
|
|
||
| import Message from "./Message.astro"; | ||
|
|
||
| import { GITHUB_AUTHORIZE_PATH } from "../io/vendor/github/routes"; | ||
| import { m } from "../paraglide/messages.js"; | ||
| import { localizeHref } from "../paraglide/runtime.js"; | ||
| import { generic, render } from "../utilities/presentation"; | ||
| import { PresentationRenderPresetRoleIcon } from "../utilities/presentation/preset"; | ||
|
|
||
| // TODO: point to /terms and /privacy once the legal copy is written | ||
| const termsLink = { href: localizeHref("/") }; | ||
| const privacyLink = { href: localizeHref("/") }; | ||
|
|
||
| const signInHref = `${GITHUB_AUTHORIZE_PATH}?${new URLSearchParams({ | ||
| "return-to": Astro.url.pathname + Astro.url.search, | ||
| })}`; | ||
| --- | ||
|
|
||
| <div class="account"> | ||
| <button | ||
| type="button" | ||
| class="account-trigger" | ||
| popovertarget="account-sign-in" | ||
| aria-label={m.account_sign_in()} | ||
| > | ||
| <Fragment | ||
| set:html={render( | ||
| generic("logIn"), | ||
| PresentationRenderPresetRoleIcon.withSize(18), | ||
| )} | ||
| /> | ||
| <span class="account-trigger-label">{m.account_sign_in()}</span> | ||
| </button> | ||
| <div id="account-sign-in" class="account-popover" popover> | ||
| <p class="account-popover-title">{m.account_sign_in_required()}</p> | ||
| <p class="account-popover-consent"> | ||
| <Message message={m.account_sign_in_consent}> | ||
| <fragment slot="termsLink"> | ||
| {(children: unknown[]) => <a {...termsLink}>{children}</a>} | ||
| </fragment> | ||
| <fragment slot="privacyLink"> | ||
| {(children: unknown[]) => <a {...privacyLink}>{children}</a>} | ||
| </fragment> | ||
| </Message> | ||
| </p> | ||
| <p class="account-popover-continue">{m.account_sign_in_continue_with()}</p> | ||
| <a | ||
| class="account-provider" | ||
| href={signInHref} | ||
| data-astro-reload | ||
| data-astro-prefetch="false" | ||
| > | ||
| <GitHubMark width="18" height="18" class="icon" aria-hidden="true" /> | ||
| GitHub | ||
| </a> | ||
| </div> | ||
| <a class="account-avatar" href={localizeHref("/account")} data-account-avatar> | ||
| <img alt="" width="32" height="32" decoding="async" /> | ||
| </a> | ||
| </div> | ||
|
|
||
| <script> | ||
| import { | ||
| GITHUB_EVENT_SESSION, | ||
| GitHubSession, | ||
| } from "../io/vendor/github/session"; | ||
| import { m } from "../paraglide/messages.js"; | ||
|
|
||
| // the page may be cached for everyone, so the signed-in state is filled in here | ||
| const sync = () => { | ||
| const login = GitHubSession.login(); | ||
| document.documentElement.toggleAttribute( | ||
| "data-github-session", | ||
| typeof login !== "undefined", | ||
| ); | ||
|
|
||
| const avatar = document.querySelector<HTMLAnchorElement>( | ||
| "[data-account-avatar]", | ||
| ); | ||
| const image = avatar?.querySelector("img"); | ||
| if (!avatar || !image || typeof login === "undefined") { | ||
| return; | ||
| } | ||
|
|
||
| avatar.setAttribute("aria-label", m.account_menu_label({ login })); | ||
| image.src = `https://avatars.githubusercontent.com/${encodeURIComponent(login)}?s=64`; | ||
| }; | ||
|
|
||
| document.addEventListener("astro:page-load", sync); | ||
| window.addEventListener(GITHUB_EVENT_SESSION, sync); | ||
| </script> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| import { z } from "astro/zod"; | ||
| import type { AstroCookieSetOptions } from "astro"; | ||
|
|
||
| // provider-agnostic half of the oauth 2.0 authorization code flow | ||
|
|
||
| export class OAuthError extends Error { | ||
| constructor( | ||
| public code: string, | ||
| public description?: string | undefined, | ||
| ) { | ||
| super( | ||
| typeof description !== "undefined" ? `${code}: ${description}` : code, | ||
| ); | ||
| Object.setPrototypeOf(this, OAuthError.prototype); | ||
| } | ||
| } | ||
|
|
||
| /** the pending authorization: single-use csrf state / the page to return to */ | ||
| export const OAuthState = z.object({ | ||
| state: z.string().min(1), | ||
| returnTo: z.string().startsWith("/"), | ||
| }); | ||
| export type OAuthState = z.infer<typeof OAuthState>; | ||
|
|
||
| const hasControlCharacter = (value: string): boolean => | ||
| [...value].some((character) => { | ||
| const code = character.codePointAt(0) ?? 0; | ||
|
|
||
| return code < 0x20 || code === 0x7f; | ||
| }); | ||
|
|
||
| /** | ||
| * accepts same-origin paths only | ||
| * | ||
| * `//evil.example` and `https://evil.example` would turn the callback into an open redirect | ||
| */ | ||
| export const safeReturnTo = (value: string | null | undefined): string => { | ||
| if (!value || !value.startsWith("/")) { | ||
| return "/"; | ||
| } | ||
|
|
||
| // `//host` and `/\host` are protocol-relative; control characters can smuggle a header break | ||
| if ( | ||
| value.startsWith("//") || | ||
| value.startsWith("/\\") || | ||
| hasControlCharacter(value) | ||
| ) { | ||
| return "/"; | ||
| } | ||
|
|
||
| // a fragment belongs to the browser, not to the `Location` header | ||
| return value.split("#")[0] ?? "/"; | ||
| }; | ||
|
|
||
| /** browsers key their cache on the url alone, so pages cached before signing in or out would outlive it */ | ||
| export const SESSION_CHANGE_HEADERS = { "clear-site-data": '"cache"' } as const; | ||
|
|
||
| export const returnToRedirect = (returnTo: string): Response => | ||
| new Response(null, { | ||
| status: 302, | ||
| headers: { | ||
| location: returnTo, | ||
| // carries Set-Cookie with the token; a cached copy would hand it to the next visitor | ||
| "cache-control": "no-store", | ||
| ...SESSION_CHANGE_HEADERS, | ||
| }, | ||
| }); | ||
|
|
||
| const sharedCookieOptions = (url: URL) => ({ | ||
| // `strict` would prevent the cookie from being sent right after access token exchange | ||
| sameSite: "lax" as const, | ||
| secure: url.protocol === "https:", | ||
| }); | ||
|
|
||
| /** for cookies that scripts don't need access to */ | ||
| export const secretCookieOptions = ( | ||
| url: URL, | ||
| path: string, | ||
| maxAge: number, | ||
| ): AstroCookieSetOptions => ({ | ||
| ...sharedCookieOptions(url), | ||
| httpOnly: true, | ||
| path, | ||
| maxAge, | ||
| }); | ||
|
|
||
| /** for cookies that scripts need access to */ | ||
| export const readableCookieOptions = ( | ||
| url: URL, | ||
| maxAge: number, | ||
| ): AstroCookieSetOptions & { maxAge: number } => ({ | ||
| ...sharedCookieOptions(url), | ||
| httpOnly: false, | ||
| path: "/", | ||
| maxAge, | ||
| }); | ||
|
|
||
| /** client authentication for the endpoints that act as the app rather than as a user */ | ||
| export const basicAuthorization = ( | ||
| clientId: string, | ||
| clientSecret: string, | ||
| ): string => `Basic ${btoa(`${clientId}:${clientSecret}`)}`; | ||
|
|
||
| export const authorizeUrl = (params: { | ||
| endpoint: string; | ||
| clientId: string; | ||
| redirectUri: string; | ||
| scope: string; | ||
| state: string; | ||
| }): string => { | ||
| const url = new URL(params.endpoint); | ||
| url.searchParams.set("client_id", params.clientId); | ||
| url.searchParams.set("redirect_uri", params.redirectUri); | ||
| url.searchParams.set("scope", params.scope); | ||
| url.searchParams.set("state", params.state); | ||
|
|
||
| return url.toString(); | ||
| }; | ||
|
|
||
| const TokenResponse = z.object({ | ||
| access_token: z.string().min(1), | ||
| scope: z.string().optional(), | ||
| expires_in: z.number().optional(), | ||
| refresh_token: z.string().optional(), | ||
| refresh_token_expires_in: z.number().optional(), | ||
| }); | ||
|
|
||
| // rfc 6749 answers errors with 400, github answers them with 200 | ||
| const TokenErrorResponse = z.object({ | ||
| error: z.string().min(1), | ||
| error_description: z.string().optional(), | ||
| }); | ||
|
|
||
| export type OAuthToken = { | ||
| accessToken: string; | ||
| scope?: string | undefined; | ||
| expiresIn: number | undefined; | ||
| refreshToken?: string | undefined; | ||
| refreshTokenExpiresIn?: number | undefined; | ||
| }; | ||
|
|
||
| /** helper for token endpoint call */ | ||
| export const requestToken = async ( | ||
| endpoint: string, | ||
| body: Record<string, string>, | ||
| options: { userAgent: string; timeoutMs: number }, | ||
| ): Promise<OAuthToken> => { | ||
| const response = await fetch(endpoint, { | ||
| method: "POST", | ||
| headers: { | ||
| accept: "application/json", | ||
| "content-type": "application/json", | ||
| "user-agent": options.userAgent, | ||
| }, | ||
| body: JSON.stringify(body), | ||
| signal: AbortSignal.timeout(options.timeoutMs), | ||
| }); | ||
|
|
||
| const payload: unknown = await response.json().catch(() => undefined); | ||
|
|
||
| const rejected = TokenErrorResponse.safeParse(payload); | ||
| if (rejected.success) { | ||
| throw new OAuthError(rejected.data.error, rejected.data.error_description); | ||
| } | ||
|
|
||
| if (!response.ok) { | ||
| throw new OAuthError( | ||
| "exchange_failed", | ||
| `the provider answered <${response.status}>`, | ||
| ); | ||
| } | ||
|
|
||
| const parsed = TokenResponse.safeParse(payload); | ||
| if (!parsed.success) { | ||
| throw new OAuthError("exchange_failed", "unexpected token response"); | ||
| } | ||
|
|
||
| return { | ||
| accessToken: parsed.data.access_token, | ||
| scope: parsed.data.scope, | ||
| expiresIn: parsed.data.expires_in, | ||
| refreshToken: parsed.data.refresh_token, | ||
| refreshTokenExpiresIn: parsed.data.refresh_token_expires_in, | ||
| }; | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
text is currently not visible until hovering 😅
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure how I missed this! Fixed