feat(oauth2): per-project permission selection on the consent screen

Let users approve OAuth2 access at the granularity the new console RAR model
expects: identity + account-tier scopes shown for context, and the project-tier
permissions from `authorization_details` chosen individually.

- New `oauth2-authorization-details.ts` helper: parse the grant's RAR entries,
  build the action catalog from the project/organization scope endpoints, and
  serialize the user's selection back as downscope-only authorization_details.
- New `oauth2-scope-picker.svelte`: actions grouped by category in accordions,
  search, per-category select-all/indeterminate, and a global select/deselect —
  built to scale to the full ~80-90 action catalog.
- `consent-card.svelte`: render one bordered picker section per requested
  project (with its resource context), keep base scopes read-only, and pass the
  consented subset to `oauth2.approve`.
- `+layout.svelte`: let a tall consent card scroll instead of overflowing the
  fixed shell; the picker list is also internally bounded so the actions stay
  visible.
- gitignore the local `.playwright-mcp/` screenshot scratch dir.
This commit is contained in:
Chirag Aggarwal committed 2026-06-26 10:36:35 +05:30
1 parent c1d66e2533
commit 39af2c8f67
4 files changed
+567 -29

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ node_modules
!.env.example
test-results/
playwright-report/
.playwright-mcp/
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
@@ -0,0 +1,202 @@
import { sdk } from '$lib/stores/sdk';
/**
* RFC 9396 Rich Authorization Requests (RAR) helpers for the OAuth2 consent
* screen.
*
* The console OAuth2 server keeps a small set of identity scopes on the
* standard `scope` parameter (`openid`, `profile`, `email`, `account.admin`)
* and moves every granular permission into `authorization_details` entries of
* type `appwrite_console`. The consent screen lets the user approve a *subset*
* of the requested actions; the approved set is sent back to the approve
* endpoint and replaces what the client originally requested. We only ever
* downscope — actions the client did not request are never offered.
*/
/** The single RAR `type` the console OAuth2 server understands. */
export const APPWRITE_CONSOLE_RAR_TYPE = 'appwrite_console';
/** Fields an `appwrite_console` entry may carry, besides `type`/`actions`. */
const RESOURCE_FIELDS = ['projectIds', 'organizationIds', 'locations'] as const;
export interface AuthorizationDetail {
type: string;
actions?: string[];
projectIds?: string[];
organizationIds?: string[];
locations?: string[];
[key: string]: unknown;
}
export interface ActionDescriptor {
/** Scope id, e.g. `databases.write`. */
action: string;
/** Human title derived from the scope id. */
title: string;
/** Catalog description, or a generic fallback. */
description: string;
/** Catalog category used for grouping, e.g. `Databases`. */
category: string;
deprecated: boolean;
}
export type ActionCatalog = Map<string, Omit<ActionDescriptor, 'action' | 'title'>>;
/**
* Account-level scopes are not exposed by the project/organization scope
* endpoints, so we describe them locally. They are few and stable.
*/
const ACCOUNT_SCOPE_CATALOG: ActionCatalog = new Map([
[
'account',
{
category: 'Account',
description: 'Manage your account, organizations, sessions, tokens, and billing.',
deprecated: false
}
],
[
'teams.read',
{
category: 'Account',
description: "Read your account's organizations.",
deprecated: false
}
],
[
'teams.write',
{
category: 'Account',
description: "Create, update, and delete your account's organizations and memberships.",
deprecated: false
}
]
]);
const UNCATEGORIZED = 'Other';
/** Parse the grant's `authorizationDetails` JSON string into entries. */
export function parseAuthorizationDetails(raw: string | null | undefined): AuthorizationDetail[] {
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? (parsed as AuthorizationDetail[]) : [];
} catch {
return [];
}
}
export function isAppwriteConsoleDetail(detail: AuthorizationDetail): boolean {
return detail.type === APPWRITE_CONSOLE_RAR_TYPE;
}
/** Distinct, requested actions for a single `appwrite_console` entry. */
export function actionsOf(detail: AuthorizationDetail): string[] {
if (!Array.isArray(detail.actions)) return [];
const seen = new Set<string>();
const out: string[] = [];
for (const action of detail.actions) {
if (typeof action === 'string' && action !== '' && !seen.has(action)) {
seen.add(action);
out.push(action);
}
}
return out;
}
/** Turn `databases.write` into `Databases write` for a readable title. */
export function titleizeAction(action: string): string {
const cleaned = action.replace(/[._:-]+/g, ' ').trim();
if (!cleaned) return action;
return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);
}
/**
* Build the action catalog from the live project + organization scope
* endpoints, falling back to the local account-scope map. The consent screen
* always runs for a signed-in console user, so these admin-scoped endpoints are
* available; if they fail we still describe actions via the fallback + titleize
* so the screen never breaks.
*/
export async function loadActionCatalog(): Promise<ActionCatalog> {
const catalog: ActionCatalog = new Map(ACCOUNT_SCOPE_CATALOG);
const results = await Promise.allSettled([
sdk.forConsole.console.listProjectScopes(),
sdk.forConsole.console.listOrganizationScopes()
]);
for (const result of results) {
if (result.status !== 'fulfilled') continue;
for (const scope of result.value.scopes) {
// Project + organization scopes can overlap (e.g. `teams.read`);
// first writer wins, which keeps the project description.
if (!catalog.has(scope.$id)) {
catalog.set(scope.$id, {
category: scope.category || UNCATEGORIZED,
description: scope.description,
deprecated: scope.deprecated
});
}
}
}
return catalog;
}
/** Resolve a single action to a descriptor, falling back to a titleized one. */
export function describeAction(action: string, catalog: ActionCatalog): ActionDescriptor {
const entry = catalog.get(action);
return {
action,
title: titleizeAction(action),
description: entry?.description ?? `Access to ${action}.`,
category: entry?.category ?? UNCATEGORIZED,
deprecated: entry?.deprecated ?? false
};
}
/**
* Rebuild the `authorization_details` array from the user's selection, keyed by
* entry index. Only `appwrite_console` entries are filtered to the selected
* actions; entries that end up with no actions are dropped, and entries of
* other types pass through untouched. Returns a JSON string ready for the
* approve endpoint, or `'[]'` when nothing remains (an empty string would tell
* the server to keep the originally requested details, which is never what the
* consent screen wants).
*/
export function serializeGrantedDetails(
requested: AuthorizationDetail[],
selectedByIndex: Record<number, Record<string, boolean>>
): string {
const granted: AuthorizationDetail[] = [];
requested.forEach((detail, index) => {
if (!isAppwriteConsoleDetail(detail)) {
granted.push(detail);
return;
}
const requestedActions = actionsOf(detail);
const selected = selectedByIndex[index] ?? {};
const keptActions = requestedActions.filter((action) => selected[action]);
if (keptActions.length === 0) {
return;
}
const rebuilt: AuthorizationDetail = {
type: APPWRITE_CONSOLE_RAR_TYPE,
actions: keptActions
};
for (const field of RESOURCE_FIELDS) {
const value = detail[field];
if (Array.isArray(value) && value.length > 0) {
rebuilt[field] = value as string[];
}
}
granted.push(rebuilt);
});
return JSON.stringify(granted);
}
+163 -29
View File
@@ -7,24 +7,19 @@
import { sdk } from '$lib/stores/sdk';
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { groupConsentScopes } from '$lib/helpers/oauth2-scopes';
import {
actionsOf,
isAppwriteConsoleDetail,
loadActionCatalog,
parseAuthorizationDetails,
serializeGrantedDetails,
type ActionCatalog,
type AuthorizationDetail
} from '$lib/helpers/oauth2-authorization-details';
import OAuth2ScopePicker from './oauth2-scope-picker.svelte';
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;
@@ -48,13 +43,85 @@
let rejecting = $state(false);
let busy = $derived(approving || rejecting);
// Requested scopes (identity + account/console-tier) are shown read-only,
// grouped by resource. The granular per-project permissions live in
// authorization_details and are chosen individually below.
const scopes = $derived(groupConsentScopes(grant.scopes ?? []));
const details = $derived(parseAuthorizationDetails(grant.authorizationDetails ?? ''));
const details = $derived<AuthorizationDetail[]>(
parseAuthorizationDetails(grant.authorizationDetails)
);
const hasConsoleActions = $derived(
details.some((detail) => isAppwriteConsoleDetail(detail) && actionsOf(detail).length > 0)
);
const redirectHost = $derived(hostnameOf(grant.redirectUri));
const appInitial = $derived((app.name || '?').charAt(0).toUpperCase());
const accountInitial = $derived((accountLabel || '?').charAt(0).toUpperCase());
// Lazily loaded scope metadata (category + descriptions) for grouping the
// requested actions. Never blocks approve/reject — the picker just shows a
// spinner until it resolves.
let catalog = $state<ActionCatalog | null>(null);
$effect(() => {
if (!hasConsoleActions || catalog) return;
let cancelled = false;
void loadActionCatalog().then((loaded) => {
if (!cancelled) catalog = loaded;
});
return () => {
cancelled = true;
};
});
// Per-entry action selection: entryIndex -> { action -> granted }. Requested
// actions start selected (the user opts OUT of what they don't want). Reset
// whenever the grant changes so a stale selection can't leak across requests.
let selection = $state<Record<number, Record<string, boolean>>>({});
$effect(() => {
// Re-init keyed on the grant id + its requested details.
grant.$id;
const next: Record<number, Record<string, boolean>> = {};
details.forEach((detail, index) => {
if (!isAppwriteConsoleDetail(detail)) return;
const actionMap: Record<string, boolean> = {};
for (const action of actionsOf(detail)) {
actionMap[action] = true;
}
next[index] = actionMap;
});
selection = next;
});
/** A short, human context line for an entry's resource scoping. */
function detailContext(detail: AuthorizationDetail): string | null {
const parts: string[] = [];
const projects = detail.projectIds?.length ?? 0;
const orgs = detail.organizationIds?.length ?? 0;
if (projects > 0) parts.push(`${projects} project${projects === 1 ? '' : 's'}`);
if (orgs > 0) parts.push(`${orgs} organization${orgs === 1 ? '' : 's'}`);
if (parts.length === 0) return null;
return `Limited to ${parts.join(' and ')}`;
}
function locationHosts(detail: AuthorizationDetail): string[] {
return (detail.locations ?? [])
.map((location) => hostnameOf(location))
.filter((host): host is string => Boolean(host));
}
// Approving is meaningless if the request offered actions but the user
// unchecked every one and granted no identity scope either.
const grantedActionCount = $derived(
Object.values(selection).reduce(
(total, actionMap) =>
total + Object.values(actionMap).filter((isGranted) => isGranted).length,
0
)
);
const nothingToGrant = $derived(
hasConsoleActions && grantedActionCount === 0 && (grant.scopes ?? []).length === 0
);
async function approve() {
if (busy) return;
// Pin the request we're acting on. If the parent swaps in a different
@@ -65,8 +132,16 @@
error = null;
approving = true;
try {
// When the request carries appwrite_console actions, send back the
// exact subset the user consented to (downscope-only — the picker
// never offers actions the client didn't request). Otherwise omit
// it and keep whatever the client originally requested.
const authorizationDetails = hasConsoleActions
? serializeGrantedDetails(details, selection)
: undefined;
const result = await sdk.forConsole.oauth2.approve({
grantId
grantId,
authorizationDetails
});
if (grant.$id !== grantId) return;
trackEvent(Submit.AccountOAuth2ConsentApprove, {
@@ -176,7 +251,7 @@
{#if scopes.groups.length > 0}
<div class="scope-accordion">
<Accordion title="App permissions" badge={String(scopes.granularCount)}>
<Accordion title="Account access" badge={String(scopes.granularCount)}>
<ul class="scope-group-list">
{#each scopes.groups as group (group.resource)}
<li class="scope-group">
@@ -197,15 +272,46 @@
{/if}
{#if details.length > 0}
<Layout.Stack gap="s">
<Typography.Text variant="m-500" color="--fgcolor-neutral-secondary">
Also requested
</Typography.Text>
<div class="detail-list">
{#each details as detail, i (`${detail.type}-${i}`)}
<span class="detail-tag">{detail.type}</span>
{/each}
</div>
<Layout.Stack gap="m">
<Layout.Stack gap="xxs">
<Typography.Text variant="m-500">Choose what to allow</Typography.Text>
<Typography.Text variant="m-400" color="--fgcolor-neutral-secondary">
{app.name} requested these permissions. Grant only the ones you're comfortable
with — you can turn any of them off.
</Typography.Text>
</Layout.Stack>
{#each details as detail, index (`${detail.type}-${index}`)}
{#if isAppwriteConsoleDetail(detail) && actionsOf(detail).length > 0}
{@const context = detailContext(detail)}
{@const hosts = locationHosts(detail)}
<div class="detail-section">
{#if context || hosts.length > 0}
<div class="detail-context">
{#if context}<span>{context}</span>{/if}
{#if hosts.length > 0}<span>{hosts.join(', ')}</span>{/if}
</div>
{/if}
{#if catalog}
<OAuth2ScopePicker
actions={actionsOf(detail)}
{catalog}
disabled={busy}
bind:selected={selection[index]} />
{:else}
<div class="picker-loading">
<Spinner size="m" />
</div>
{/if}
</div>
{:else}
<!-- Unknown RAR type: surface it read-only so the user
still sees it, but it isn't user-editable here. -->
<div class="detail-list">
<span class="detail-tag">{detail.type}</span>
</div>
{/if}
{/each}
</Layout.Stack>
{/if}
@@ -220,7 +326,7 @@
<Form onSubmit={approve}>
<Layout.Stack gap="s">
<Button fullWidth submit disabled={busy}>
<Button fullWidth submit disabled={busy || nothingToGrant}>
{#if approving}
<Spinner size="s" />
{:else}
@@ -423,7 +529,35 @@
background: var(--bgcolor-neutral-default);
}
/* Rich authorization details — de-emphasized, compact tags. */
/* Rich authorization details — one bordered picker section per requested entry. */
.detail-section {
border: 1px solid var(--border-neutral);
border-radius: 0.75rem;
background: var(--bgcolor-neutral-default);
padding: 0.9rem;
}
.detail-section + .detail-section {
margin-top: 0.5rem;
}
.detail-context {
display: flex;
flex-wrap: wrap;
gap: 0.25rem 0.75rem;
margin-bottom: 0.75rem;
font-size: 0.78rem;
color: var(--fgcolor-neutral-tertiary);
}
.picker-loading {
display: flex;
align-items: center;
justify-content: center;
padding: 1.5rem 0;
}
/* Unknown RAR types fall back to de-emphasized, compact tags. */
.detail-list {
display: flex;
flex-wrap: wrap;
@@ -0,0 +1,201 @@
<script lang="ts">
import {
Accordion,
Badge,
Divider,
Layout,
Selector,
Typography
} from '@appwrite.io/pink-svelte';
import { InputSearch, Button } from '$lib/elements/forms';
import {
describeAction,
type ActionCatalog,
type ActionDescriptor
} from '$lib/helpers/oauth2-authorization-details';
interface Props {
/** Requested actions for a single appwrite_console entry. */
actions: string[];
catalog: ActionCatalog;
/** action -> granted. Two-way bound so the parent reads the selection. */
selected: Record<string, boolean>;
disabled?: boolean;
}
let { actions, catalog, selected = $bindable(), disabled = false }: Props = $props();
let search = $state('');
// Describe + sort every requested action once. Deprecated actions sink to
// the bottom of their category so the common ones lead.
const described = $derived<ActionDescriptor[]>(
actions
.map((action) => describeAction(action, catalog))
.sort((a, b) => {
if (a.category !== b.category) return a.category.localeCompare(b.category);
if (a.deprecated !== b.deprecated) return a.deprecated ? 1 : -1;
return a.action.localeCompare(b.action);
})
);
const visible = $derived.by(() => {
const term = search.trim().toLowerCase();
if (!term) return described;
return described.filter(
(d) =>
d.action.toLowerCase().includes(term) ||
d.title.toLowerCase().includes(term) ||
d.description.toLowerCase().includes(term) ||
d.category.toLowerCase().includes(term)
);
});
const categories = $derived(Array.from(new Set(visible.map((d) => d.category))));
const selectedCount = $derived(actions.filter((action) => selected[action]).length);
function actionsInCategory(category: string): ActionDescriptor[] {
return visible.filter((d) => d.category === category);
}
function categoryState(category: string): boolean | 'indeterminate' {
const inCategory = actionsInCategory(category);
const active = inCategory.filter((d) => selected[d.action]).length;
if (active === 0) return false;
if (active === inCategory.length) return true;
return 'indeterminate';
}
function onCategoryChange(event: CustomEvent<boolean | 'indeterminate'>, category: string) {
if (disabled || event.detail === 'indeterminate') return;
for (const d of actionsInCategory(category)) {
selected[d.action] = event.detail;
}
}
function setAll(value: boolean) {
if (disabled) return;
// Only flips what is currently visible (respects an active search).
for (const d of visible) {
selected[d.action] = value;
}
}
</script>
<Layout.Stack gap="m">
<Layout.Stack
direction="row"
alignItems="center"
justifyContent="space-between"
gap="s"
wrap="wrap">
<Layout.Stack direction="row" alignItems="baseline" gap="xs" inline>
<Typography.Text variant="m-500">Permissions</Typography.Text>
<Typography.Text variant="m-400" color="--fgcolor-neutral-tertiary">
{selectedCount}/{actions.length}
</Typography.Text>
</Layout.Stack>
<Layout.Stack direction="row" alignItems="center" gap="s" inline>
<Button
compact
disabled={disabled || selectedCount === actions.length}
on:click={() => setAll(true)}>
Select all
</Button>
<span style:height="20px"><Divider vertical /></span>
<Button
compact
disabled={disabled || selectedCount === 0}
on:click={() => setAll(false)}>
Deselect all
</Button>
</Layout.Stack>
</Layout.Stack>
{#if actions.length > 6}
<InputSearch bind:value={search} placeholder="Search permissions" {disabled} />
{/if}
{#if categories.length === 0}
<Typography.Text variant="m-400" color="--fgcolor-neutral-tertiary">
No permissions match “{search}”.
</Typography.Text>
{:else}
<!-- Bounded + internally scrollable so the card stays a sensible height
and the Authorize / Cancel actions remain visible no matter how many
permissions are requested. -->
<div class="scope-scroll">
<Layout.Stack gap="none">
<Divider />
{#each categories as category, index (category)}
{@const inCategory = actionsInCategory(category)}
{@const activeCount = inCategory.filter((d) => selected[d.action]).length}
<Accordion
selectable={!disabled}
title={category}
hideDivider={index === categories.length - 1}
badge={`${activeCount}/${inCategory.length}`}
checked={categoryState(category)}
on:change={(event) => onCategoryChange(event, category)}>
<Layout.Stack gap="m">
{#each inCategory as action (action.action)}
<Layout.Stack
inline
direction="row"
alignItems="flex-start"
gap="s">
<Selector.Checkbox
size="s"
id={`rar-${action.action}`}
{disabled}
bind:checked={selected[action.action]} />
<Layout.Stack gap="xxs">
<label for={`rar-${action.action}`}>
<Layout.Stack gap="xxs">
<Layout.Stack
inline
direction="row"
alignItems="center"
gap="xxs">
<Typography.Text variant="m-500">
{action.action}
</Typography.Text>
{#if action.deprecated}
<Badge
size="xs"
variant="secondary"
content="Deprecated" />
{/if}
</Layout.Stack>
<Typography.Text
variant="m-400"
color="--fgcolor-neutral-tertiary">
{action.description}
</Typography.Text>
</Layout.Stack>
</label>
</Layout.Stack>
</Layout.Stack>
{/each}
</Layout.Stack>
</Accordion>
{/each}
</Layout.Stack>
</div>
{/if}
</Layout.Stack>
<style>
.scope-scroll {
max-height: 22rem;
overflow-y: auto;
/* Keep the right edge clear of the scrollbar. */
margin-right: -0.25rem;
padding-right: 0.25rem;
}
label {
cursor: pointer;
}
</style>