mirror of
https://github.com/appwrite/console.git
synced 2026-11-18 20:47:21 +00:00
Merge pull request #3110 from appwrite/feat-oauth2-par-login-redirect
Resume OAuth2 authorize requests through PAR handles across login
This commit is contained in:
11 files changed
+253
-135
No files matched your search
@@ -6,7 +6,7 @@
|
||||
"name": "@appwrite/console",
|
||||
"dependencies": {
|
||||
"@ai-sdk/svelte": "^1.1.24",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@0fcb4f2",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@4b3ae78",
|
||||
"@appwrite.io/pink-icons": "0.25.0",
|
||||
"@appwrite.io/pink-icons-svelte": "https://pkg.vc/-/@appwrite/@appwrite.io/pink-icons-svelte@bfe7ce3",
|
||||
"@appwrite.io/pink-legacy": "^1.0.3",
|
||||
@@ -126,7 +126,7 @@
|
||||
|
||||
"@analytics/type-utils": ["@analytics/type-utils@0.6.4", "", {}, "sha512-Ou1gQxFakOWLcPnbFVsrPb8g1wLLUZYYJXDPjHkG07+5mustGs5yqACx42UAu4A6NszNN6Z5gGxhyH45zPWRxw=="],
|
||||
|
||||
"@appwrite.io/console": ["@appwrite.io/console@https://pkg.vc/-/@appwrite/@appwrite.io/console@0fcb4f2", { "dependencies": { "json-bigint": "1.0.0" } }],
|
||||
"@appwrite.io/console": ["@appwrite.io/console@https://pkg.vc/-/@appwrite/@appwrite.io/console@4b3ae78", { "dependencies": { "json-bigint": "1.0.0" } }],
|
||||
|
||||
"@appwrite.io/pink-icons": ["@appwrite.io/pink-icons@0.25.0", "", {}, "sha512-0O3i2oEuh5mWvjO80i+X6rbzrWLJ1m5wmv2/M3a1p2PyBJsFxN8xQMTEmTn3Wl/D26SsM7SpzbdW6gmfgoVU9Q=="],
|
||||
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/svelte": "^1.1.24",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@0fcb4f2",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@4b3ae78",
|
||||
"@appwrite.io/pink-icons": "0.25.0",
|
||||
"@appwrite.io/pink-icons-svelte": "https://pkg.vc/-/@appwrite/@appwrite.io/pink-icons-svelte@bfe7ce3",
|
||||
"@appwrite.io/pink-legacy": "^1.0.3",
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
|
||||
export let show = false;
|
||||
export let locale: Models.Locale;
|
||||
export let locale: Models.CloudLocale;
|
||||
export let organization: string = null;
|
||||
export let countryList: Models.CountryList;
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
export let data: PageData;
|
||||
|
||||
const locale: Models.Locale = data.locale;
|
||||
const locale: Models.CloudLocale = data.locale;
|
||||
const countryList: Models.CountryList = data.countryList;
|
||||
|
||||
let show = false;
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
|
||||
export let show = false;
|
||||
export let locale: Models.Locale;
|
||||
export let locale: Models.CloudLocale;
|
||||
export let countryList: Models.CountryList;
|
||||
export let selectedAddress: Models.BillingAddress;
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
} from '@appwrite.io/pink-icons-svelte';
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
|
||||
export let locale: Models.Locale;
|
||||
export let locale: Models.CloudLocale;
|
||||
export let countryList: Models.CountryList;
|
||||
export let organization: Models.Organization;
|
||||
export let billingAddress: Models.BillingAddress;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
|
||||
export let show = false;
|
||||
export let locale: Models.Locale;
|
||||
export let locale: Models.CloudLocale;
|
||||
export let countryList: Models.CountryList;
|
||||
|
||||
let loading = true;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
|
||||
let show = false;
|
||||
export let locale: Models.Locale;
|
||||
export let locale: Models.CloudLocale;
|
||||
export let countryList: Models.CountryList;
|
||||
</script>
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
|
||||
export let show = false;
|
||||
export let locale: Models.Locale;
|
||||
export let locale: Models.CloudLocale;
|
||||
export let countryList: Models.CountryList;
|
||||
|
||||
let email = '';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { base } from '$app/paths';
|
||||
import { resolve } from '$app/paths';
|
||||
import { page } from '$app/state';
|
||||
import { AppwriteException, type Models } from '@appwrite.io/console';
|
||||
import { Card, Layout, Typography, Icon, Spinner } from '@appwrite.io/pink-svelte';
|
||||
@@ -10,13 +10,15 @@
|
||||
import { isWebRedirect } from '$lib/helpers/oauth2-redirect';
|
||||
import OAuth2ConsentCard, { type OAuth2Outcome } from '../consent-card.svelte';
|
||||
import OAuth2OutcomeCard from '../outcome-card.svelte';
|
||||
import { OAuth2ErrorMessage, OAuth2ErrorType } from '../errors';
|
||||
|
||||
type Phase = 'loading' | 'ready' | 'approved' | 'denied' | 'error';
|
||||
type Account = Models.User<Models.Preferences>;
|
||||
|
||||
let phase = $state<Phase>('loading');
|
||||
let grant = $state<Models.Oauth2Grant | null>(null);
|
||||
let app = $state<Models.App | null>(null);
|
||||
let account = $state<Models.User<Models.Preferences> | null>(null);
|
||||
let account = $state<Account | null>(null);
|
||||
let error = $state<string | null>(null);
|
||||
let completedRedirectUrl = $state<string | undefined>(undefined);
|
||||
|
||||
@@ -28,144 +30,242 @@
|
||||
return Number.isInteger(value) && value >= 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function getAccount(): Promise<Account | null> {
|
||||
return sdk.forConsole.account.get().catch(() => null) as Promise<Account | null>;
|
||||
}
|
||||
|
||||
// The authorize-request fields shared verbatim between createPAR (pre-login
|
||||
// push) and authorize (authenticated direct path).
|
||||
function readAuthorizeParams(params: URLSearchParams) {
|
||||
const resources = params.getAll('resource');
|
||||
return {
|
||||
redirectUri: params.get('redirect_uri') ?? '',
|
||||
responseType: params.get('response_type') ?? 'code',
|
||||
scope: params.get('scope') ?? '',
|
||||
state: params.get('state') ?? undefined,
|
||||
nonce: params.get('nonce') ?? undefined,
|
||||
codeChallenge: params.get('code_challenge') ?? undefined,
|
||||
codeChallengeMethod: params.get('code_challenge_method') ?? undefined,
|
||||
prompt: params.get('prompt') ?? undefined,
|
||||
maxAge: parseMaxAge(params.get('max_age')),
|
||||
authorizationDetails: params.get('authorization_details') ?? undefined,
|
||||
resource: resources.length > 0 ? (resources as unknown as string) : undefined
|
||||
};
|
||||
}
|
||||
|
||||
function goSignIn(resumeUrl?: string) {
|
||||
const target = resumeUrl ?? window.location.pathname + window.location.search;
|
||||
void goto(resolve(`/login?redirect=${encodeURIComponent(target)}`), {
|
||||
replaceState: true
|
||||
});
|
||||
}
|
||||
|
||||
function fail(e: unknown, fallback: string) {
|
||||
error = (e as Error)?.message ?? fallback;
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
// Load a grant + its app branding and render the consent card.
|
||||
async function loadConsent(
|
||||
grantId: string,
|
||||
cancelled: () => boolean,
|
||||
knownAccount?: Account | null
|
||||
): Promise<void> {
|
||||
const loadedGrant = await sdk.forConsole.oauth2.getGrant({ grantId });
|
||||
const [loadedApp, loadedAccount] = await Promise.all([
|
||||
sdk.forConsole.apps.get({ appId: loadedGrant.appId }),
|
||||
knownAccount !== undefined ? Promise.resolve(knownAccount) : getAccount()
|
||||
]);
|
||||
if (cancelled()) return;
|
||||
grant = loadedGrant;
|
||||
app = loadedApp;
|
||||
account = loadedAccount;
|
||||
phase = 'ready';
|
||||
}
|
||||
|
||||
async function resumeFromGrant(grantId: string, cancelled: () => boolean): Promise<void> {
|
||||
try {
|
||||
await loadConsent(grantId, cancelled);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled()) return;
|
||||
if (e instanceof AppwriteException && e.code === 401) {
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
fail(e, OAuth2ErrorMessage.GRANT_INVALID);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAuthorizeResult(
|
||||
result: Models.Oauth2Authorize,
|
||||
loggedInAccount: Account,
|
||||
clientId: string | null,
|
||||
fromRequestUri: boolean,
|
||||
cancelled: () => boolean
|
||||
): Promise<void> {
|
||||
if (result.redirectUrl) {
|
||||
// Already consented — go straight back to the client.
|
||||
window.location.href = result.redirectUrl;
|
||||
if (!isWebRedirect(result.redirectUrl)) {
|
||||
completedRedirectUrl = result.redirectUrl;
|
||||
account = loggedInAccount;
|
||||
app = clientId
|
||||
? await sdk.forConsole.apps.get({ appId: clientId }).catch(() => null)
|
||||
: null;
|
||||
if (cancelled()) return;
|
||||
phase = 'approved';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (result.grantId) {
|
||||
if (fromRequestUri) {
|
||||
// The handle is now consumed — rewrite to the grant URL so
|
||||
// reloads resume via getGrant instead of a dead request_uri.
|
||||
await goto(resolve(`/oauth2/consent?grant_id=${result.grantId}`), {
|
||||
replaceState: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
await loadConsent(result.grantId, cancelled, loggedInAccount);
|
||||
return;
|
||||
}
|
||||
error = OAuth2ErrorMessage.AUTHORIZE_FAILED;
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
async function resumeFromRequestUri(
|
||||
clientId: string | null,
|
||||
requestUri: string,
|
||||
cancelled: () => boolean
|
||||
): Promise<void> {
|
||||
const loggedInAccount = await getAccount();
|
||||
if (cancelled()) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
// Dereferencing while logged out can only 401; keep the
|
||||
// single-use handle untouched and go straight to login.
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// The server rejects request_uri combined with any other
|
||||
// authorization param; only client_id may accompany it.
|
||||
const result = await sdk.forConsole.oauth2.authorize({
|
||||
clientId: clientId ?? undefined,
|
||||
requestUri
|
||||
});
|
||||
if (cancelled()) return;
|
||||
await handleAuthorizeResult(result, loggedInAccount, clientId, true, cancelled);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled()) return;
|
||||
// Since only the handle is sent, oauth2_invalid_request can only
|
||||
// mean the handle is unusable.
|
||||
if (e instanceof AppwriteException && e.type === OAuth2ErrorType.INVALID_REQUEST) {
|
||||
error = OAuth2ErrorMessage.HANDLE_EXPIRED;
|
||||
phase = 'error';
|
||||
return;
|
||||
}
|
||||
fail(e, OAuth2ErrorMessage.AUTHORIZE_FAILED);
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-login entry with raw authorize params in the URL.
|
||||
async function startAuthorize(
|
||||
clientId: string,
|
||||
params: URLSearchParams,
|
||||
cancelled: () => boolean
|
||||
): Promise<void> {
|
||||
const loggedInAccount = await getAccount();
|
||||
if (cancelled()) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
// Carry only a short request_uri through login — the full
|
||||
// consent URL travels inside the OAuth provider's `state`
|
||||
// during GitHub sign-in and can exceed its size limits.
|
||||
try {
|
||||
const par = await sdk.forConsole.oauth2.createPAR({
|
||||
clientId,
|
||||
...readAuthorizeParams(params)
|
||||
});
|
||||
if (cancelled()) return;
|
||||
goSignIn(
|
||||
`${resolve('/oauth2/consent')}?client_id=${encodeURIComponent(clientId)}&request_uri=${encodeURIComponent(par.request_uri)}`
|
||||
);
|
||||
} catch {
|
||||
if (cancelled()) return;
|
||||
// PAR unavailable (older server) or invalid request —
|
||||
// fall back to the legacy full-URL redirect.
|
||||
goSignIn();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Authenticated: ask the server to create a grant (or detect an
|
||||
// existing approved identity), then render consent or redirect.
|
||||
try {
|
||||
const result = await sdk.forConsole.oauth2.authorize({
|
||||
clientId,
|
||||
...readAuthorizeParams(params)
|
||||
});
|
||||
if (cancelled()) return;
|
||||
await handleAuthorizeResult(result, loggedInAccount, clientId, false, cancelled);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled()) return;
|
||||
fail(e, OAuth2ErrorMessage.AUTHORIZE_FAILED);
|
||||
}
|
||||
}
|
||||
|
||||
async function init(params: URLSearchParams, cancelled: () => boolean): Promise<void> {
|
||||
const grantId = params.get('grant_id');
|
||||
if (grantId) {
|
||||
await resumeFromGrant(grantId, cancelled);
|
||||
return;
|
||||
}
|
||||
|
||||
const clientId = params.get('client_id');
|
||||
const requestUri = params.get('request_uri');
|
||||
if (requestUri) {
|
||||
await resumeFromRequestUri(clientId, requestUri, cancelled);
|
||||
return;
|
||||
}
|
||||
if (clientId) {
|
||||
await startAuthorize(clientId, params, cancelled);
|
||||
return;
|
||||
}
|
||||
|
||||
error = OAuth2ErrorMessage.MISSING_REQUEST;
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
function onDone(outcome: OAuth2Outcome, redirectUrl?: string) {
|
||||
completedRedirectUrl = redirectUrl;
|
||||
phase = outcome === 'approved' ? 'approved' : 'denied';
|
||||
}
|
||||
|
||||
// A $derived string so identity-only replacements of page.url (e.g. login
|
||||
// calling invalidate(ACCOUNT) right after goto) don't restart the flow —
|
||||
// a restart would cancel an in-flight authorize and re-dereference an
|
||||
// already-consumed single-use request_uri.
|
||||
const authorizeQuery = $derived(page.url.searchParams.toString());
|
||||
|
||||
let currentRun = 0;
|
||||
|
||||
// Re-runs when the authorize params change (this route can stay mounted as
|
||||
// the router moves between requests). Reset to loading so a previously
|
||||
// loaded grant can never be approved against a different request.
|
||||
$effect(() => {
|
||||
// Depend on the ENTIRE query string so the effect re-runs whenever any
|
||||
// part of the authorize request changes — not just grant_id/client_id,
|
||||
// but also redirect_uri, scope, state, nonce, PKCE fields, prompt,
|
||||
// max_age and authorization_details.
|
||||
page.url.searchParams.toString();
|
||||
const params = new URLSearchParams(authorizeQuery);
|
||||
const run = ++currentRun;
|
||||
|
||||
let cancelled = false;
|
||||
phase = 'loading';
|
||||
error = null;
|
||||
completedRedirectUrl = undefined;
|
||||
|
||||
const currentRelativeUrl = () => window.location.pathname + window.location.search;
|
||||
|
||||
const goSignIn = () => {
|
||||
void goto(`${base}/login?redirect=${encodeURIComponent(currentRelativeUrl())}`, {
|
||||
replaceState: true
|
||||
});
|
||||
};
|
||||
|
||||
// Load a grant + its app branding and render the consent card.
|
||||
async function loadConsent(
|
||||
grantId: string,
|
||||
knownAccount?: Models.User<Models.Preferences> | null
|
||||
): Promise<void> {
|
||||
const loadedGrant = await sdk.forConsole.oauth2.getGrant({ grantId });
|
||||
const [loadedApp, loadedAccount] = await Promise.all([
|
||||
sdk.forConsole.apps.get({ appId: loadedGrant.appId }),
|
||||
knownAccount !== undefined
|
||||
? Promise.resolve(knownAccount)
|
||||
: (sdk.forConsole.account
|
||||
.get()
|
||||
.catch(() => null) as Promise<Models.User<Models.Preferences> | null>)
|
||||
]);
|
||||
if (cancelled) return;
|
||||
grant = loadedGrant;
|
||||
app = loadedApp;
|
||||
account = loadedAccount;
|
||||
phase = 'ready';
|
||||
}
|
||||
|
||||
async function init(): Promise<void> {
|
||||
const params = page.url.searchParams;
|
||||
const grantId = params.get('grant_id');
|
||||
|
||||
if (grantId) {
|
||||
try {
|
||||
await loadConsent(grantId);
|
||||
} catch (e: unknown) {
|
||||
if (cancelled) return;
|
||||
if (e instanceof AppwriteException && e.code === 401) {
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
error =
|
||||
(e as Error)?.message ??
|
||||
'This authorization request is invalid or has expired.';
|
||||
phase = 'error';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// No grant yet: this is the pre-login entry with raw authorize params.
|
||||
const clientId = params.get('client_id');
|
||||
if (clientId) {
|
||||
const loggedInAccount = (await sdk.forConsole.account
|
||||
.get()
|
||||
.catch(() => null)) as Models.User<Models.Preferences> | null;
|
||||
if (cancelled) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
goSignIn();
|
||||
return;
|
||||
}
|
||||
|
||||
// Authenticated: ask the server to create a grant (or detect an
|
||||
// existing approved identity) via the SDK, then render consent or
|
||||
// redirect.
|
||||
try {
|
||||
const result = await sdk.forConsole.oauth2.authorize({
|
||||
clientId,
|
||||
redirectUri: params.get('redirect_uri') ?? '',
|
||||
responseType: params.get('response_type') ?? 'code',
|
||||
scope: params.get('scope') ?? '',
|
||||
state: params.get('state') ?? undefined,
|
||||
nonce: params.get('nonce') ?? undefined,
|
||||
codeChallenge: params.get('code_challenge') ?? undefined,
|
||||
codeChallengeMethod: params.get('code_challenge_method') ?? undefined,
|
||||
prompt: params.get('prompt') ?? undefined,
|
||||
maxAge: parseMaxAge(params.get('max_age')),
|
||||
authorizationDetails: params.get('authorization_details') ?? undefined,
|
||||
resource: params.get('resource') ?? undefined
|
||||
});
|
||||
if (cancelled) return;
|
||||
if (result.redirectUrl) {
|
||||
// Already consented — go straight back to the client.
|
||||
window.location.href = result.redirectUrl;
|
||||
if (!isWebRedirect(result.redirectUrl)) {
|
||||
completedRedirectUrl = result.redirectUrl;
|
||||
account = loggedInAccount;
|
||||
app = await sdk.forConsole.apps
|
||||
.get({ appId: clientId })
|
||||
.catch(() => null);
|
||||
if (cancelled) return;
|
||||
phase = 'approved';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (result.grantId) {
|
||||
await loadConsent(result.grantId, loggedInAccount);
|
||||
return;
|
||||
}
|
||||
error = 'Could not start authorization.';
|
||||
phase = 'error';
|
||||
} catch (e: unknown) {
|
||||
if (cancelled) return;
|
||||
error = (e as Error)?.message ?? 'Could not start authorization.';
|
||||
phase = 'error';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
error = 'Missing authorization request. Open this page from an application sign-in.';
|
||||
phase = 'error';
|
||||
}
|
||||
|
||||
void init();
|
||||
void init(params, () => run !== currentRun);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
currentRun++;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
@@ -192,7 +292,7 @@
|
||||
<Typography.Text variant="m-400" align="center">
|
||||
{error}
|
||||
</Typography.Text>
|
||||
<Button on:click={() => goto(base, { replaceState: true })}>
|
||||
<Button on:click={() => goto(resolve('/'), { replaceState: true })}>
|
||||
Go to console
|
||||
</Button>
|
||||
</Layout.Stack>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Exception `type` values returned by the OAuth2 endpoints. The SDK does not
|
||||
* export these, so they are mirrored here.
|
||||
*/
|
||||
export const OAuth2ErrorType = {
|
||||
/**
|
||||
* Covers every dead request_uri handle case (expired, consumed, malformed).
|
||||
*/
|
||||
INVALID_REQUEST: 'oauth2_invalid_request'
|
||||
} as const;
|
||||
|
||||
export const OAuth2ErrorMessage = {
|
||||
AUTHORIZE_FAILED: 'Could not start authorization.',
|
||||
GRANT_INVALID: 'This authorization request is invalid or has expired.',
|
||||
HANDLE_EXPIRED:
|
||||
'This sign-in request has expired. Return to the application and try connecting again.',
|
||||
MISSING_REQUEST: 'Missing authorization request. Open this page from an application sign-in.'
|
||||
} as const;
|
||||
Reference in new issue
Block a user