mirror of
https://github.com/appwrite/console.git
synced 2026-11-18 20:47:21 +00:00
feat: OAuth2 server consent & device verification screens
Adds the 'Sign in with Appwrite' identity-provider UI for the Console OAuth2 server — the two user-facing screens behind the new server env vars: - _APP_CONSOLE_OAUTH2_AUTHORIZATION_URL -> /oauth2/consent - _APP_CONSOLE_OAUTH2_VERIFICATION_URL -> /oauth2/device Consent (/oauth2/consent): authorization-code flow. Reads the grant, shows the requesting app's branding and what authorizing grants, and lets the user authorize or cancel. Approve redirects back to the client with a code; cancel returns access_denied. The permission list leads with full account access rather than the requested OIDC scopes, since console-project tokens receive the full users (member) role regardless of scopes. Device (/oauth2/device): Device Authorization Grant (RFC 8628). When opened via verification_uri_complete the code is rendered for the user to confirm it matches their device (no silent auto-submit); otherwise they type it in. After confirming, the same consent card is shown (with device-specific copy), then a terminal success state. SDK: bump @appwrite.io/console pin to 1a5604f which adds the Oauth2 grant service and Models.Oauth2Grant; wire Apps + Oauth2 into sdk.forConsole. Login: honor the redirect query param after email login (MFA-safe) so OAuth2 flows resume after sign-in, aligning login with register.
This commit is contained in:
10 files changed
+1071
-3
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@82d2831",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@1a5604f",
|
||||
"@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",
|
||||
@@ -125,7 +125,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@82d2831", { "dependencies": { "json-bigint": "1.0.0" } }],
|
||||
"@appwrite.io/console": ["@appwrite.io/console@https://pkg.vc/-/@appwrite/@appwrite.io/console@1a5604f", { "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@82d2831",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@1a5604f",
|
||||
"@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",
|
||||
|
||||
@@ -225,6 +225,9 @@ export enum Submit {
|
||||
AccountRecoveryCodesCreate = 'submit_account_recovery_codes_create',
|
||||
AccountRecoveryCodesUpdate = 'submit_account_recovery_codes_update',
|
||||
AccountDeleteIdentity = 'submit_account_delete_identity',
|
||||
AccountOAuth2ConsentApprove = 'submit_account_oauth2_consent_approve',
|
||||
AccountOAuth2ConsentDeny = 'submit_account_oauth2_consent_deny',
|
||||
AccountOAuth2DeviceVerify = 'submit_account_oauth2_device_verify',
|
||||
FeedbackSubmit = 'submit_leave_feedback',
|
||||
FilterClear = 'submit_clear_filter',
|
||||
FilterApply = 'submit_filter_apply',
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { ComponentType } from 'svelte';
|
||||
import {
|
||||
IconShieldCheck,
|
||||
IconUser,
|
||||
IconMail,
|
||||
IconIdentification,
|
||||
IconKey
|
||||
} from '@appwrite.io/pink-icons-svelte';
|
||||
|
||||
export interface ScopeDescriptor {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
icon: ComponentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* This consent screen always authorizes against the Appwrite **console**
|
||||
* project. On the server, any OAuth2 access token issued for the console
|
||||
* project is granted the full `users` (member) role — the same access a
|
||||
* signed-in console session has — regardless of the OIDC scopes requested.
|
||||
* The `openid`/`profile`/`email` scopes only shape the OIDC identity claims;
|
||||
* they do NOT limit what the application can do. So the consent screen must
|
||||
* lead with the full-access reality rather than implying read-only access.
|
||||
*/
|
||||
export const FULL_ACCESS_SCOPE: ScopeDescriptor = {
|
||||
id: '__full_access__',
|
||||
title: 'Full access to your account',
|
||||
description: 'Manage your organizations, projects, and all their resources on your behalf.',
|
||||
icon: IconShieldCheck
|
||||
};
|
||||
|
||||
const BUILTIN_SCOPES: Record<string, Omit<ScopeDescriptor, 'id'>> = {
|
||||
openid: {
|
||||
title: 'Verify your identity',
|
||||
description: 'Confirm who you are using your Appwrite account.',
|
||||
icon: IconIdentification
|
||||
},
|
||||
profile: {
|
||||
title: 'View your profile',
|
||||
description: 'Read your name and profile details.',
|
||||
icon: IconUser
|
||||
},
|
||||
email: {
|
||||
title: 'View your email address',
|
||||
description: 'Read the email address associated with your account.',
|
||||
icon: IconMail
|
||||
}
|
||||
};
|
||||
|
||||
function titleizeScope(scope: string): string {
|
||||
const cleaned = scope.replace(/[._:-]+/g, ' ').trim();
|
||||
if (!cleaned) return scope;
|
||||
return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);
|
||||
}
|
||||
|
||||
export function describeScope(scope: string): ScopeDescriptor {
|
||||
const builtin = BUILTIN_SCOPES[scope];
|
||||
if (builtin) {
|
||||
return { id: scope, ...builtin };
|
||||
}
|
||||
return {
|
||||
id: scope,
|
||||
title: titleizeScope(scope),
|
||||
description: `Access to ${scope}.`,
|
||||
icon: IconKey
|
||||
};
|
||||
}
|
||||
|
||||
export function describeScopes(scopes: string[]): ScopeDescriptor[] {
|
||||
return scopes.map(describeScope);
|
||||
}
|
||||
|
||||
// Identity scopes shown (in this order) as secondary detail beneath the
|
||||
// full-access item. `openid` is intentionally omitted — identity verification
|
||||
// is implied by full account access, so listing it separately is redundant.
|
||||
const CONSENT_IDENTITY_SCOPES = ['profile', 'email'] as const;
|
||||
|
||||
/**
|
||||
* Build the permission list for the console OAuth2 consent screen. Always leads
|
||||
* with the full-access item (the true effect of authorizing), followed by the
|
||||
* identity scopes the application actually reads (profile, email) when present.
|
||||
*/
|
||||
export function describeConsentScopes(scopes: string[]): ScopeDescriptor[] {
|
||||
const requested = new Set(scopes);
|
||||
const identity = CONSENT_IDENTITY_SCOPES.filter((scope) => requested.has(scope)).map(
|
||||
describeScope
|
||||
);
|
||||
return [FULL_ACCESS_SCOPE, ...identity];
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { isMultiRegionSupported, VARS } from '$lib/system';
|
||||
import { registerImpersonationClients, restoreImpersonation } from '$lib/appwrite/impersonation';
|
||||
import {
|
||||
Account,
|
||||
Apps,
|
||||
Assistant,
|
||||
Avatars,
|
||||
Backups,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
Locale,
|
||||
Messaging,
|
||||
Migrations,
|
||||
Oauth2,
|
||||
Organization,
|
||||
Project,
|
||||
Project as ProjectApi,
|
||||
@@ -48,6 +50,8 @@ function createConsoleSdk(client: Client) {
|
||||
return {
|
||||
client,
|
||||
account: new Account(client),
|
||||
apps: new Apps(client),
|
||||
oauth2: new Oauth2(client),
|
||||
avatars: new Avatars(client),
|
||||
functions: new Functions(client),
|
||||
health: new Health(client),
|
||||
|
||||
@@ -62,6 +62,34 @@
|
||||
return;
|
||||
}
|
||||
|
||||
// Honor the `redirect` query param so OAuth2 consent/device flows
|
||||
// (and other deep links) resume after email login. MFA-safe: if
|
||||
// additional factors are required, fall through to invalidate(ACCOUNT)
|
||||
// so the root layout routes to /mfa carrying the redirect param from
|
||||
// the current /login URL.
|
||||
const redirect = page.url.searchParams.get('redirect');
|
||||
if (redirect) {
|
||||
try {
|
||||
await sdk.forConsole.account.get();
|
||||
page.url.searchParams.delete('redirect');
|
||||
await goto(`${redirect}${page.url.search}`);
|
||||
await invalidate(Dependencies.ACCOUNT);
|
||||
return;
|
||||
} catch (mfaError) {
|
||||
if (mfaError?.type !== 'user_more_factors_required') {
|
||||
addNotification({
|
||||
type: 'error',
|
||||
message: mfaError.message
|
||||
});
|
||||
trackError(mfaError, Submit.AccountLogin);
|
||||
disabled = false;
|
||||
return;
|
||||
}
|
||||
// MFA required: fall through so the root layout redirects to
|
||||
// /mfa with the redirect param preserved in the URL.
|
||||
}
|
||||
}
|
||||
|
||||
// no specific redirect, so redirect will happen through invalidating the account
|
||||
await invalidate(Dependencies.ACCOUNT);
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
<script lang="ts">
|
||||
import { base } from '$app/paths';
|
||||
import { app } from '$lib/stores/app';
|
||||
import { loading } from '$routes/store';
|
||||
import { Typography } from '@appwrite.io/pink-svelte';
|
||||
|
||||
loading.set(false);
|
||||
</script>
|
||||
|
||||
<div class="auth-bg">
|
||||
<section>
|
||||
<div class="console-container">
|
||||
<slot />
|
||||
</div>
|
||||
</section>
|
||||
<footer>
|
||||
<Typography.Eyebrow color="--fgcolor-neutral-secondary">POWERED BY</Typography.Eyebrow>
|
||||
{#if $app.themeInUse === 'dark'}
|
||||
<img
|
||||
src="{base}/images/appwrite-logo-dark.svg"
|
||||
width="120"
|
||||
height="22"
|
||||
alt="Appwrite Logo" />
|
||||
{:else}
|
||||
<img
|
||||
src="{base}/images/appwrite-logo-light.svg"
|
||||
width="120"
|
||||
height="22"
|
||||
alt="Appwrite Logo" />
|
||||
{/if}
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.auth-bg {
|
||||
position: fixed;
|
||||
background: var(--bgcolor-neutral-primary, #fff);
|
||||
background-size: cover;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
justify-content: space-between;
|
||||
section {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
footer {
|
||||
padding: 2rem 1rem;
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,355 @@
|
||||
<script lang="ts">
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
import { Card, Layout, Typography, Icon, Spinner } from '@appwrite.io/pink-svelte';
|
||||
import {
|
||||
IconCheck,
|
||||
IconExclamation,
|
||||
IconShieldCheck,
|
||||
IconExternalLink
|
||||
} from '@appwrite.io/pink-icons-svelte';
|
||||
import { Button, Form } from '$lib/elements/forms';
|
||||
import { addNotification } from '$lib/stores/notifications';
|
||||
import { sdk } from '$lib/stores/sdk';
|
||||
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
|
||||
import { describeConsentScopes } from '$lib/helpers/oauth2-scopes';
|
||||
|
||||
export type OAuth2Flow = 'authorization' | 'device';
|
||||
|
||||
interface AuthorizationDetail {
|
||||
type: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function parseAuthorizationDetails(raw: string): AuthorizationDetail[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? (parsed as AuthorizationDetail[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function hostnameOf(uri: string): string | null {
|
||||
try {
|
||||
return new URL(uri).hostname;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
grant: Models.Oauth2Grant;
|
||||
app: Models.App;
|
||||
accountLabel?: string;
|
||||
flow: OAuth2Flow;
|
||||
onDeviceDone?: (outcome: 'approved' | 'denied') => void;
|
||||
}
|
||||
|
||||
let { grant, app, accountLabel = undefined, flow, onDeviceDone }: Props = $props();
|
||||
|
||||
let error = $state<string | null>(null);
|
||||
let approving = $state(false);
|
||||
let rejecting = $state(false);
|
||||
let busy = $derived(approving || rejecting);
|
||||
|
||||
const scopes = $derived(describeConsentScopes(grant.scopes ?? []));
|
||||
const details = $derived(parseAuthorizationDetails(grant.authorizationDetails ?? ''));
|
||||
const redirectHost = $derived(hostnameOf(grant.redirectUri));
|
||||
|
||||
const appInitial = $derived((app.name || '?').charAt(0).toUpperCase());
|
||||
|
||||
async function approve() {
|
||||
if (busy) return;
|
||||
error = null;
|
||||
approving = true;
|
||||
try {
|
||||
const result = await sdk.forConsole.oauth2.approve({
|
||||
grantId: grant.$id
|
||||
});
|
||||
trackEvent(Submit.AccountOAuth2ConsentApprove, {
|
||||
app_id: grant.appId,
|
||||
flow
|
||||
});
|
||||
if (flow === 'device' || !result.redirectUrl) {
|
||||
onDeviceDone?.('approved');
|
||||
return;
|
||||
}
|
||||
window.location.href = result.redirectUrl;
|
||||
} catch (e: unknown) {
|
||||
const message = (e as Error)?.message ?? 'Failed to authorize the application';
|
||||
error = message;
|
||||
addNotification({ type: 'error', message });
|
||||
trackError(e as Error, Submit.AccountOAuth2ConsentApprove);
|
||||
} finally {
|
||||
approving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function reject() {
|
||||
if (busy) return;
|
||||
error = null;
|
||||
rejecting = true;
|
||||
try {
|
||||
const result = await sdk.forConsole.oauth2.reject({
|
||||
grantId: grant.$id
|
||||
});
|
||||
trackEvent(Submit.AccountOAuth2ConsentDeny, {
|
||||
app_id: grant.appId,
|
||||
flow
|
||||
});
|
||||
if (flow === 'device' || !result.redirectUrl) {
|
||||
onDeviceDone?.('denied');
|
||||
return;
|
||||
}
|
||||
window.location.href = result.redirectUrl;
|
||||
} catch (e: unknown) {
|
||||
const message = (e as Error)?.message ?? 'Failed to cancel the request';
|
||||
error = message;
|
||||
addNotification({ type: 'error', message });
|
||||
trackError(e as Error, Submit.AccountOAuth2ConsentDeny);
|
||||
} finally {
|
||||
rejecting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Card.Base padding="l" radius="l" style="width: 100%;">
|
||||
<Layout.Stack gap="xl">
|
||||
<Layout.Stack gap="l" alignItems="center" alignContent="center">
|
||||
{#if app.logoUri}
|
||||
<img src={app.logoUri} alt={app.name} class="app-logo" />
|
||||
{:else}
|
||||
<div class="app-logo-placeholder">
|
||||
{appInitial}
|
||||
</div>
|
||||
{/if}
|
||||
<Layout.Stack gap="xs" alignItems="center" alignContent="center">
|
||||
<Typography.Title size="m" align="center">
|
||||
Authorize {app.name}
|
||||
</Typography.Title>
|
||||
<Typography.Text variant="m-400" align="center">
|
||||
{app.tagline || `${app.name} wants to access your Appwrite account.`}
|
||||
</Typography.Text>
|
||||
</Layout.Stack>
|
||||
</Layout.Stack>
|
||||
|
||||
<Layout.Stack gap="m">
|
||||
<Typography.Eyebrow color="--fgcolor-neutral-secondary">
|
||||
This will allow {app.name} to
|
||||
</Typography.Eyebrow>
|
||||
<ul class="scope-list">
|
||||
{#each scopes as scope (scope.id)}
|
||||
<li class="scope-item">
|
||||
<span class="scope-icon">
|
||||
<Icon icon={scope.icon} size="s" />
|
||||
</span>
|
||||
<span class="scope-text">
|
||||
<span class="scope-title">{scope.title}</span>
|
||||
<span class="scope-desc">{scope.description}</span>
|
||||
</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Layout.Stack>
|
||||
|
||||
{#if details.length > 0}
|
||||
<Layout.Stack gap="s">
|
||||
<Typography.Eyebrow color="--fgcolor-neutral-secondary">
|
||||
Requested resources
|
||||
</Typography.Eyebrow>
|
||||
<ul class="detail-list">
|
||||
{#each details as detail, i (`${detail.type}-${i}`)}
|
||||
<li class="detail-item">
|
||||
<Icon
|
||||
icon={IconShieldCheck}
|
||||
size="s"
|
||||
color="--fgcolor-neutral-secondary" />
|
||||
<span class="detail-type">{detail.type}</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Layout.Stack>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<div class="error-box">
|
||||
<Icon icon={IconExclamation} size="s" color="--fgcolor-danger" />
|
||||
<Typography.Text variant="m-400" color="--fgcolor-danger">
|
||||
{error}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<Form onSubmit={approve}>
|
||||
<Layout.Stack gap="s">
|
||||
<Button fullWidth submit disabled={busy}>
|
||||
{#if approving}
|
||||
<Spinner size="s" />
|
||||
{:else}
|
||||
<Icon icon={IconCheck} slot="start" size="s" />
|
||||
{/if}
|
||||
{approving ? 'Authorizing…' : 'Authorize'}
|
||||
</Button>
|
||||
<Button fullWidth secondary disabled={busy} on:click={reject}>
|
||||
{rejecting ? 'Cancelling…' : 'Cancel'}
|
||||
</Button>
|
||||
</Layout.Stack>
|
||||
</Form>
|
||||
|
||||
<Typography.Text variant="m-400" align="center" color="--fgcolor-neutral-secondary">
|
||||
{#if accountLabel}
|
||||
Signed in as <span class="bold">{accountLabel}</span>.{' '}
|
||||
{/if}
|
||||
{#if flow === 'authorization' && redirectHost}
|
||||
You'll be redirected to {redirectHost}.
|
||||
{/if}
|
||||
{#if flow === 'device'}
|
||||
After authorizing, return to your device.
|
||||
{/if}
|
||||
</Typography.Text>
|
||||
|
||||
{#if app.privacyPolicyUrl || app.termsUrl}
|
||||
<Typography.Text variant="m-400" align="center" color="--fgcolor-neutral-secondary">
|
||||
{#if app.privacyPolicyUrl}
|
||||
<a
|
||||
href={app.privacyPolicyUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="footer-link">
|
||||
Privacy Policy
|
||||
<Icon icon={IconExternalLink} size="xs" />
|
||||
</a>
|
||||
{/if}
|
||||
{#if app.privacyPolicyUrl && app.termsUrl}
|
||||
{' · '}
|
||||
{/if}
|
||||
{#if app.termsUrl}
|
||||
<a href={app.termsUrl} target="_blank" rel="noreferrer" class="footer-link">
|
||||
Terms of Service
|
||||
<Icon icon={IconExternalLink} size="xs" />
|
||||
</a>
|
||||
{/if}
|
||||
</Typography.Text>
|
||||
{/if}
|
||||
</Layout.Stack>
|
||||
</Card.Base>
|
||||
|
||||
<style lang="scss">
|
||||
.app-logo {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
border-radius: 0.75rem;
|
||||
object-fit: cover;
|
||||
border: 1px solid var(--border-color-neutral-strong, #e2e2e2);
|
||||
}
|
||||
|
||||
.app-logo-placeholder {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
border-radius: 0.75rem;
|
||||
border: 1px solid var(--border-color-neutral-strong, #e2e2e2);
|
||||
background: var(--bgcolor-neutral-secondary, #f4f4f4);
|
||||
color: var(--fgcolor-neutral-secondary, #6b7280);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scope-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.scope-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.scope-icon {
|
||||
flex-shrink: 0;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border-radius: 0.5rem;
|
||||
background: var(--bgcolor-neutral-secondary, #f4f4f4);
|
||||
color: var(--fgcolor-neutral-secondary, #6b7280);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 0.125rem;
|
||||
}
|
||||
|
||||
.scope-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
}
|
||||
|
||||
.scope-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--fgcolor-neutral-primary, #1f2937);
|
||||
}
|
||||
|
||||
.scope-desc {
|
||||
font-size: 0.75rem;
|
||||
color: var(--fgcolor-neutral-secondary, #6b7280);
|
||||
}
|
||||
|
||||
.detail-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.detail-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
background: var(--bgcolor-neutral-secondary, #f4f4f4);
|
||||
border-radius: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.detail-type {
|
||||
color: var(--fgcolor-neutral-primary, #1f2937);
|
||||
}
|
||||
|
||||
.error-box {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
border: 1px solid var(--border-color-danger, rgba(220, 38, 38, 0.2));
|
||||
background: var(--bgcolor-danger-secondary, rgba(220, 38, 38, 0.1));
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.bold {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.footer-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.footer-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,209 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { base } 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';
|
||||
import { IconExclamation } from '@appwrite.io/pink-icons-svelte';
|
||||
import { Button } from '$lib/elements/forms';
|
||||
import { sdk } from '$lib/stores/sdk';
|
||||
import OAuth2ConsentCard from '../consent-card.svelte';
|
||||
|
||||
type Phase = 'loading' | 'ready' | 'error';
|
||||
|
||||
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 error = $state<string | null>(null);
|
||||
|
||||
// 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(() => {
|
||||
// Touch the search params so the effect re-runs on URL change.
|
||||
page.url.searchParams.get('grant_id');
|
||||
page.url.searchParams.get('client_id');
|
||||
|
||||
let cancelled = false;
|
||||
phase = 'loading';
|
||||
error = null;
|
||||
|
||||
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: params.get('max_age') ? Number(params.get('max_age')) : undefined,
|
||||
authorizationDetails: params.get('authorization_details') ?? undefined
|
||||
});
|
||||
if (cancelled) return;
|
||||
if (result.redirectUrl) {
|
||||
// Already consented — go straight back to the client.
|
||||
window.location.href = result.redirectUrl;
|
||||
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();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Authorize application - Appwrite</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="consent-page">
|
||||
<div class="consent-card-wrapper">
|
||||
{#if phase === 'loading'}
|
||||
<div class="spinner-wrap">
|
||||
<Spinner size="l" />
|
||||
</div>
|
||||
{:else if phase === 'error'}
|
||||
<Card.Base padding="l" radius="l" style="width: 100%;">
|
||||
<Layout.Stack gap="l" alignItems="center" alignContent="center">
|
||||
<div class="error-icon-wrap">
|
||||
<Icon icon={IconExclamation} size="l" color="--fgcolor-danger" />
|
||||
</div>
|
||||
<Typography.Title size="m" align="center">
|
||||
Authorization failed
|
||||
</Typography.Title>
|
||||
<Typography.Text variant="m-400" align="center">
|
||||
{error}
|
||||
</Typography.Text>
|
||||
<Button on:click={() => goto(base, { replaceState: true })}>
|
||||
Go to console
|
||||
</Button>
|
||||
</Layout.Stack>
|
||||
</Card.Base>
|
||||
{:else if phase === 'ready' && grant && app}
|
||||
<OAuth2ConsentCard
|
||||
{grant}
|
||||
{app}
|
||||
accountLabel={account?.email || account?.name || undefined}
|
||||
flow="authorization" />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.consent-page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.consent-card-wrapper {
|
||||
width: 100%;
|
||||
max-width: 28rem;
|
||||
}
|
||||
|
||||
.spinner-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 16rem;
|
||||
}
|
||||
|
||||
.error-icon-wrap {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 50%;
|
||||
background: var(--bgcolor-danger-secondary, rgba(220, 38, 38, 0.1));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,317 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { base } from '$app/paths';
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/state';
|
||||
import { AppwriteException, type Models } from '@appwrite.io/console';
|
||||
import { Card, Layout, Typography, Icon, Spinner } from '@appwrite.io/pink-svelte';
|
||||
import {
|
||||
IconDesktopComputer,
|
||||
IconCheckCircle,
|
||||
IconXCircle
|
||||
} from '@appwrite.io/pink-icons-svelte';
|
||||
import { Button, Form, Label } from '$lib/elements/forms';
|
||||
import { addNotification } from '$lib/stores/notifications';
|
||||
import { sdk } from '$lib/stores/sdk';
|
||||
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
|
||||
import OAuth2ConsentCard, { type OAuth2Flow } from '../consent-card.svelte';
|
||||
|
||||
type Phase = 'loading' | 'enter-code' | 'consent' | 'approved' | 'denied';
|
||||
|
||||
const DEVICE_FLOW: OAuth2Flow = 'device';
|
||||
|
||||
/** Keep only the characters the device user codes are built from. */
|
||||
function normalizeUserCode(value: string): string {
|
||||
return value.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
}
|
||||
|
||||
let phase = $state<Phase>('loading');
|
||||
let account = $state<Models.User<Models.Preferences> | null>(null);
|
||||
let code = $state(normalizeUserCode(page.url.searchParams.get('user_code') ?? ''));
|
||||
let grant = $state<Models.Oauth2Grant | null>(null);
|
||||
let app = $state<Models.App | null>(null);
|
||||
let error = $state<string | null>(null);
|
||||
let submitting = $state(false);
|
||||
let hasPrefilledCode = $state(
|
||||
Boolean(normalizeUserCode(page.url.searchParams.get('user_code') ?? ''))
|
||||
);
|
||||
|
||||
onMount(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function init() {
|
||||
const loggedInAccount = (await sdk.forConsole.account
|
||||
.get()
|
||||
.catch(() => null)) as Models.User<Models.Preferences> | null;
|
||||
if (cancelled) return;
|
||||
|
||||
if (!loggedInAccount) {
|
||||
void goto(
|
||||
`${base}/login?redirect=${encodeURIComponent(
|
||||
window.location.pathname + window.location.search
|
||||
)}`,
|
||||
{ replaceState: true }
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
account = loggedInAccount;
|
||||
// Always show the code (prefilled from the URL or typed) so the user
|
||||
// can confirm it matches their device before exchanging it — never
|
||||
// auto-submit.
|
||||
phase = 'enter-code';
|
||||
}
|
||||
|
||||
void init();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
});
|
||||
|
||||
// Keep the shown code in sync when a new `user_code` arrives in the URL
|
||||
// (e.g. the user follows a fresh `verification_uri_complete` link while this
|
||||
// route stays mounted). A different code means a different request, so drop
|
||||
// any loaded grant and return to confirmation rather than approving the old
|
||||
// one.
|
||||
$effect(() => {
|
||||
page.url.searchParams.get('user_code');
|
||||
const next = normalizeUserCode(page.url.searchParams.get('user_code') ?? '');
|
||||
if (!next || next === code) return;
|
||||
code = next;
|
||||
grant = null;
|
||||
app = null;
|
||||
error = null;
|
||||
hasPrefilledCode = Boolean(next);
|
||||
phase = phase === 'loading' ? phase : 'enter-code';
|
||||
});
|
||||
|
||||
async function handleSubmit() {
|
||||
const normalized = normalizeUserCode(code);
|
||||
if (!normalized) return;
|
||||
error = null;
|
||||
submitting = true;
|
||||
try {
|
||||
const loadedGrant = await sdk.forConsole.oauth2.createGrant({
|
||||
userCode: normalized
|
||||
});
|
||||
const loadedApp = await sdk.forConsole.apps.get({
|
||||
appId: loadedGrant.appId
|
||||
});
|
||||
trackEvent(Submit.AccountOAuth2DeviceVerify, {
|
||||
app_id: loadedGrant.appId
|
||||
});
|
||||
grant = loadedGrant;
|
||||
app = loadedApp;
|
||||
error = null;
|
||||
phase = 'consent';
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof AppwriteException && e.type === 'oauth2_invalid_user_code') {
|
||||
error = 'That code is invalid or has expired. Check your device and try again.';
|
||||
} else {
|
||||
error = (e as Error)?.message ?? 'Could not verify that code.';
|
||||
addNotification({ type: 'error', message: error });
|
||||
trackError(e as Error, Submit.AccountOAuth2DeviceVerify);
|
||||
}
|
||||
phase = 'enter-code';
|
||||
} finally {
|
||||
submitting = false;
|
||||
}
|
||||
}
|
||||
|
||||
function onDeviceDone(outcome: 'approved' | 'denied') {
|
||||
phase = outcome === 'approved' ? 'approved' : 'denied';
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Connect a device - Appwrite</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="device-page">
|
||||
<div class="device-card-wrapper">
|
||||
{#if phase === 'loading'}
|
||||
<div class="spinner-wrap">
|
||||
<Spinner size="l" />
|
||||
</div>
|
||||
{:else if phase === 'enter-code'}
|
||||
<Card.Base padding="l" radius="l" style="width: 100%;">
|
||||
<Form onSubmit={handleSubmit}>
|
||||
<Layout.Stack gap="xl">
|
||||
<Layout.Stack gap="l" alignItems="center" alignContent="center">
|
||||
<div class="header-icon-wrap">
|
||||
<Icon icon={IconDesktopComputer} size="l" />
|
||||
</div>
|
||||
<Layout.Stack gap="xs" alignItems="center" alignContent="center">
|
||||
<Typography.Title size="m" align="center">
|
||||
{hasPrefilledCode ? 'Confirm your code' : 'Connect a device'}
|
||||
</Typography.Title>
|
||||
<Typography.Text variant="m-400" align="center">
|
||||
{hasPrefilledCode
|
||||
? 'Make sure this matches the code shown on your device, then continue.'
|
||||
: 'Enter the code shown on your device to continue.'}
|
||||
</Typography.Text>
|
||||
</Layout.Stack>
|
||||
</Layout.Stack>
|
||||
|
||||
<Layout.Stack gap="s">
|
||||
<Label for="user-code">Device code</Label>
|
||||
<input
|
||||
id="user-code"
|
||||
type="text"
|
||||
value={code}
|
||||
oninput={(e) => {
|
||||
code = normalizeUserCode(e.currentTarget.value);
|
||||
error = null;
|
||||
}}
|
||||
placeholder="XXXXXXXX"
|
||||
autofocus
|
||||
autocomplete="off"
|
||||
autocapitalize="characters"
|
||||
spellcheck="false"
|
||||
maxlength={12}
|
||||
disabled={submitting}
|
||||
class="code-input" />
|
||||
{#if error}
|
||||
<Typography.Text variant="m-400" color="--fgcolor-danger">
|
||||
{error}
|
||||
</Typography.Text>
|
||||
{/if}
|
||||
</Layout.Stack>
|
||||
|
||||
<Button fullWidth submit disabled={code.length === 0 || submitting}>
|
||||
{submitting ? 'Verifying…' : 'Continue'}
|
||||
</Button>
|
||||
|
||||
{#if account}
|
||||
<Typography.Text
|
||||
variant="m-400"
|
||||
align="center"
|
||||
color="--fgcolor-neutral-secondary">
|
||||
Signed in as
|
||||
<span class="bold">{account.email || account.name}</span>.
|
||||
</Typography.Text>
|
||||
{/if}
|
||||
</Layout.Stack>
|
||||
</Form>
|
||||
</Card.Base>
|
||||
{:else if phase === 'consent' && grant && app}
|
||||
<OAuth2ConsentCard
|
||||
{grant}
|
||||
{app}
|
||||
accountLabel={account?.email || account?.name || undefined}
|
||||
flow={DEVICE_FLOW}
|
||||
{onDeviceDone} />
|
||||
{:else if phase === 'approved'}
|
||||
<Card.Base padding="l" radius="l" style="width: 100%;">
|
||||
<Layout.Stack gap="l" alignItems="center" alignContent="center">
|
||||
<div class="success-icon-wrap">
|
||||
<Icon icon={IconCheckCircle} size="l" color="--fgcolor-success" />
|
||||
</div>
|
||||
<Typography.Title size="m" align="center">Device connected</Typography.Title>
|
||||
<Typography.Text variant="m-400" align="center">
|
||||
You've authorized {app?.name ?? 'the application'}. You can return to your
|
||||
device — it will continue automatically.
|
||||
</Typography.Text>
|
||||
</Layout.Stack>
|
||||
</Card.Base>
|
||||
{:else if phase === 'denied'}
|
||||
<Card.Base padding="l" radius="l" style="width: 100%;">
|
||||
<Layout.Stack gap="l" alignItems="center" alignContent="center">
|
||||
<div class="denied-icon-wrap">
|
||||
<Icon icon={IconXCircle} size="l" color="--fgcolor-neutral-secondary" />
|
||||
</div>
|
||||
<Typography.Title size="m" align="center">Request cancelled</Typography.Title>
|
||||
<Typography.Text variant="m-400" align="center">
|
||||
No access was granted. You can close this page.
|
||||
</Typography.Text>
|
||||
</Layout.Stack>
|
||||
</Card.Base>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.device-page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.device-card-wrapper {
|
||||
width: 100%;
|
||||
max-width: 28rem;
|
||||
}
|
||||
|
||||
.spinner-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 16rem;
|
||||
}
|
||||
|
||||
.header-icon-wrap {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 0.75rem;
|
||||
background: var(--bgcolor-neutral-secondary, #f4f4f4);
|
||||
color: var(--fgcolor-neutral-secondary, #6b7280);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.code-input {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
font-family: var(
|
||||
--font-family-mono,
|
||||
ui-monospace,
|
||||
SFMono-Regular,
|
||||
Menlo,
|
||||
Monaco,
|
||||
Consolas,
|
||||
monospace
|
||||
);
|
||||
font-size: 1.5rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.3em;
|
||||
padding: 0.625rem 0.75rem;
|
||||
border: 1px solid var(--border-color-neutral-strong, #d0d0d0);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--bgcolor-neutral-primary, #fff);
|
||||
color: var(--fgcolor-neutral-primary, #1f2937);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.code-input:focus {
|
||||
border-color: var(--border-color-focus, #2563eb);
|
||||
}
|
||||
|
||||
.code-input:disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.success-icon-wrap {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 50%;
|
||||
background: var(--bgcolor-success-secondary, rgba(16, 185, 129, 0.1));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.denied-icon-wrap {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 50%;
|
||||
background: var(--bgcolor-neutral-secondary, #f4f4f4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.bold {
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user