mirror of
https://github.com/appwrite/console.git
synced 2026-11-18 20:47:21 +00:00
Merge pull request #3094 from appwrite/feat-oauth2-rar-consent
feat(oauth2): selectable console scopes + named per-project consent
This commit is contained in:
7 files changed
+856
-87
No files matched your search
@@ -11,6 +11,7 @@ node_modules
|
||||
!.env.example
|
||||
test-results/
|
||||
playwright-report/
|
||||
.playwright-mcp/
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"name": "@appwrite/console",
|
||||
"dependencies": {
|
||||
"@ai-sdk/svelte": "^1.1.24",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@4851d03",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@88cc66d",
|
||||
"@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@4851d03", { "dependencies": { "json-bigint": "1.0.0" } }, "sha512-Zhisu5a5Y6yS4MTk3G3ZA205rELJ9BSzp65MKqVmim3ii/tBSoAKiVnhBPDRR5V8Kg7FLGFW+D3dKPMspFHC/g=="],
|
||||
"@appwrite.io/console": ["@appwrite.io/console@https://pkg.vc/-/@appwrite/@appwrite.io/console@88cc66d", { "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@4851d03",
|
||||
"@appwrite.io/console": "https://pkg.vc/-/@appwrite/@appwrite.io/console@88cc66d",
|
||||
"@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",
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import { Query } from '@appwrite.io/console';
|
||||
import { sdk } from '$lib/stores/sdk';
|
||||
import { getTeamOrOrganizationList } from '$lib/stores/organization';
|
||||
|
||||
/**
|
||||
* RFC 9396 Rich Authorization Requests (RAR) helpers for the OAuth2 consent
|
||||
* screen.
|
||||
*
|
||||
* The console OAuth2 server keeps identity + account/console-tier scopes on the
|
||||
* standard `scope` parameter (`openid`, `profile`, `email`, `account.admin`,
|
||||
* plus `teams.*`, `projects.*`, …) and moves every project-tier permission into
|
||||
* `authorization_details` entries of type `appwrite_project`, each bound to the
|
||||
* concrete `projectIds` it applies to. 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_PROJECT_RAR_TYPE = 'appwrite_project';
|
||||
|
||||
/** The reserved internal project id; never a valid RAR target. */
|
||||
const RESERVED_CONSOLE_PROJECT = 'console';
|
||||
|
||||
/** Fields an `appwrite_project` 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 isAppwriteProjectDetail(detail: AuthorizationDetail): boolean {
|
||||
return detail.type === APPWRITE_PROJECT_RAR_TYPE;
|
||||
}
|
||||
|
||||
/** Distinct, requested actions for a single `appwrite_project` 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 (!isAppwriteProjectDetail(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_PROJECT_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);
|
||||
}
|
||||
|
||||
export interface ResolvedProject {
|
||||
id: string;
|
||||
/** Project name, or the raw id when it couldn't be resolved. */
|
||||
name: string;
|
||||
region?: string;
|
||||
/** True when a real project name was found; false means we fell back to id. */
|
||||
resolved: boolean;
|
||||
}
|
||||
|
||||
export type ProjectNameMap = Map<string, ResolvedProject>;
|
||||
|
||||
/** Unique, real project ids referenced across all appwrite_project entries. */
|
||||
export function collectProjectIds(details: AuthorizationDetail[]): string[] {
|
||||
const seen = new Set<string>();
|
||||
for (const detail of details) {
|
||||
if (!isAppwriteProjectDetail(detail)) continue;
|
||||
for (const id of detail.projectIds ?? []) {
|
||||
if (typeof id === 'string' && id !== '' && id !== RESERVED_CONSOLE_PROJECT) {
|
||||
seen.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort resolution of project ids to their display names. A bare project
|
||||
* id can't be fetched directly — projects are reachable only through their
|
||||
* owning organization — so we list the user's organizations and ask each for
|
||||
* the requested ids. Anything we can't find (not owned, or in a non-primary
|
||||
* region the console endpoint doesn't see) falls back to showing the raw id.
|
||||
* Never throws: on any failure the caller still gets an id-only map.
|
||||
*/
|
||||
export async function resolveProjectNames(ids: string[]): Promise<ProjectNameMap> {
|
||||
const map: ProjectNameMap = new Map();
|
||||
for (const id of ids) {
|
||||
map.set(id, { id, name: id, resolved: false });
|
||||
}
|
||||
if (ids.length === 0) return map;
|
||||
|
||||
try {
|
||||
const orgs = await getTeamOrOrganizationList([Query.limit(100)]);
|
||||
const results = await Promise.allSettled(
|
||||
orgs.teams.map((org) =>
|
||||
sdk.forConsole.organization(org.$id).listProjects({
|
||||
queries: [
|
||||
Query.equal('$id', ids),
|
||||
Query.select(['$id', 'name', 'region', 'teamId']),
|
||||
Query.limit(ids.length)
|
||||
]
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
for (const result of results) {
|
||||
if (result.status !== 'fulfilled') continue;
|
||||
for (const project of result.value.projects) {
|
||||
map.set(project.$id, {
|
||||
id: project.$id,
|
||||
name: project.name,
|
||||
region: project.region,
|
||||
resolved: true
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Keep the id-only fallback map.
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
@@ -2,6 +2,10 @@ import type { ComponentType } from 'svelte';
|
||||
import {
|
||||
IconShieldCheck,
|
||||
IconUser,
|
||||
IconUserCircle,
|
||||
IconUserGroup,
|
||||
IconViewGrid,
|
||||
IconGlobe,
|
||||
IconMail,
|
||||
IconIdentification,
|
||||
IconKey
|
||||
@@ -43,6 +47,53 @@ const BUILTIN_SCOPES: Record<string, Omit<ScopeDescriptor, 'id'>> = {
|
||||
title: ACCOUNT_ADMIN_DESCRIPTOR.title,
|
||||
description: ACCOUNT_ADMIN_DESCRIPTOR.description,
|
||||
icon: ACCOUNT_ADMIN_DESCRIPTOR.icon
|
||||
},
|
||||
// Account/console-tier scopes (carried on the `scope` param). These read as
|
||||
// console-level actions — managing your account, organizations, projects.
|
||||
account: {
|
||||
title: 'Manage your account',
|
||||
description: 'Manage your account, sessions, tokens, and billing.',
|
||||
icon: IconUserCircle
|
||||
},
|
||||
'teams.read': {
|
||||
title: 'View your organizations',
|
||||
description: 'Read the organizations you belong to.',
|
||||
icon: IconUserGroup
|
||||
},
|
||||
'teams.write': {
|
||||
title: 'Manage your organizations',
|
||||
description: 'Create, update, and delete your organizations and their members.',
|
||||
icon: IconUserGroup
|
||||
},
|
||||
'projects.read': {
|
||||
title: 'View your projects',
|
||||
description: 'List the projects in your organizations.',
|
||||
icon: IconViewGrid
|
||||
},
|
||||
'projects.write': {
|
||||
title: 'Manage your projects',
|
||||
description: 'Create, update, and delete projects in your organizations.',
|
||||
icon: IconViewGrid
|
||||
},
|
||||
'organization.keys.read': {
|
||||
title: 'View organization API keys',
|
||||
description: "Read your organizations' API keys.",
|
||||
icon: IconKey
|
||||
},
|
||||
'organization.keys.write': {
|
||||
title: 'Manage organization API keys',
|
||||
description: "Create, update, and delete your organizations' API keys.",
|
||||
icon: IconKey
|
||||
},
|
||||
'domains.read': {
|
||||
title: 'View organization domains',
|
||||
description: "Read your organizations' domains.",
|
||||
icon: IconGlobe
|
||||
},
|
||||
'domains.write': {
|
||||
title: 'Manage organization domains',
|
||||
description: "Create, update, and delete your organizations' domains.",
|
||||
icon: IconGlobe
|
||||
}
|
||||
};
|
||||
|
||||
@@ -99,6 +150,49 @@ export function describeConsentScopes(scopes: string[]): ScopeDescriptor[] {
|
||||
return described;
|
||||
}
|
||||
|
||||
export interface SelectableConsentScopes {
|
||||
/** `account.admin` full-access descriptor, when requested (read-only). */
|
||||
admin: ScopeDescriptor | null;
|
||||
/** OIDC identity scopes (profile/email), always granted (read-only). */
|
||||
identity: ScopeDescriptor[];
|
||||
/** Account/console-tier scopes the user can individually toggle. */
|
||||
selectable: ScopeDescriptor[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the requested `scope`-param scopes for the consent screen into the
|
||||
* read-only rows (full-access `account.admin`, identity scopes) and the
|
||||
* individually-selectable account/console-tier scopes. Anything that isn't
|
||||
* `openid`, an identity scope, or `account.admin` is treated as a selectable
|
||||
* console-tier scope — the `scope` param only ever carries console-tier scopes
|
||||
* (project-tier permissions travel in `authorization_details`). Request order
|
||||
* is preserved.
|
||||
*/
|
||||
export function splitSelectableScopes(scopes: string[]): SelectableConsentScopes {
|
||||
const requested = new Set(scopes);
|
||||
const admin = requested.has(ACCOUNT_ADMIN_SCOPE) ? ACCOUNT_ADMIN_DESCRIPTOR : null;
|
||||
const identity = CONSENT_IDENTITY_SCOPES.filter((scope) => requested.has(scope)).map(
|
||||
describeScope
|
||||
);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const selectable: ScopeDescriptor[] = [];
|
||||
for (const scope of scopes) {
|
||||
if (
|
||||
scope === 'openid' ||
|
||||
scope === ACCOUNT_ADMIN_SCOPE ||
|
||||
(CONSENT_IDENTITY_SCOPES as readonly string[]).includes(scope) ||
|
||||
seen.has(scope)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
seen.add(scope);
|
||||
selectable.push(describeScope(scope));
|
||||
}
|
||||
|
||||
return { admin, identity, selectable };
|
||||
}
|
||||
|
||||
export interface ScopeAction {
|
||||
/** Full scope id, e.g. `teams.write`. */
|
||||
id: string;
|
||||
|
||||
@@ -1,29 +1,38 @@
|
||||
<script lang="ts">
|
||||
import type { Models } from '@appwrite.io/console';
|
||||
import { Accordion, Card, Layout, Typography, Icon, Spinner } from '@appwrite.io/pink-svelte';
|
||||
import {
|
||||
Badge,
|
||||
Card,
|
||||
Layout,
|
||||
Typography,
|
||||
Icon,
|
||||
Selector,
|
||||
Spinner
|
||||
} from '@appwrite.io/pink-svelte';
|
||||
import { IconCheck, IconExclamation } 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 { groupConsentScopes } from '$lib/helpers/oauth2-scopes';
|
||||
import { splitSelectableScopes } from '$lib/helpers/oauth2-scopes';
|
||||
import {
|
||||
actionsOf,
|
||||
collectProjectIds,
|
||||
isAppwriteProjectDetail,
|
||||
loadActionCatalog,
|
||||
parseAuthorizationDetails,
|
||||
resolveProjectNames,
|
||||
serializeGrantedDetails,
|
||||
type ActionCatalog,
|
||||
type AuthorizationDetail,
|
||||
type ResolvedProject
|
||||
} 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 [];
|
||||
}
|
||||
}
|
||||
/** How many project chips to show in an entry header before collapsing. */
|
||||
const MAX_PROJECT_CHIPS = 5;
|
||||
|
||||
function hostnameOf(uri: string): string | null {
|
||||
try {
|
||||
@@ -48,13 +57,125 @@
|
||||
let rejecting = $state(false);
|
||||
let busy = $derived(approving || rejecting);
|
||||
|
||||
const scopes = $derived(groupConsentScopes(grant.scopes ?? []));
|
||||
const details = $derived(parseAuthorizationDetails(grant.authorizationDetails ?? ''));
|
||||
// The `scope` param carries identity + account/console-tier scopes. Identity
|
||||
// and full-access (`account.admin`) are shown read-only; the rest are
|
||||
// individually selectable. Project-tier permissions live in
|
||||
// authorization_details and are chosen per project below.
|
||||
const scopes = $derived(splitSelectableScopes(grant.scopes ?? []));
|
||||
const details = $derived<AuthorizationDetail[]>(
|
||||
parseAuthorizationDetails(grant.authorizationDetails)
|
||||
);
|
||||
const hasProjectActions = $derived(
|
||||
details.some((detail) => isAppwriteProjectDetail(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 the per-project
|
||||
// pickers. Never blocks approve/reject — the picker shows a spinner until it
|
||||
// resolves.
|
||||
let catalog = $state<ActionCatalog | null>(null);
|
||||
$effect(() => {
|
||||
if (!hasProjectActions || catalog) return;
|
||||
let cancelled = false;
|
||||
void loadActionCatalog().then((loaded) => {
|
||||
if (!cancelled) catalog = loaded;
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
});
|
||||
|
||||
// Selectable console-scope state: scopeId -> granted. Starts all-on (opt-out).
|
||||
// Re-initialised whenever the grant changes so a stale selection can't leak.
|
||||
let scopeSelection = $state<Record<string, boolean>>({});
|
||||
$effect(() => {
|
||||
grant.$id;
|
||||
const next: Record<string, boolean> = {};
|
||||
for (const descriptor of scopes.selectable) {
|
||||
next[descriptor.id] = true;
|
||||
}
|
||||
scopeSelection = next;
|
||||
});
|
||||
|
||||
// Per-entry project-action selection: entryIndex -> { action -> granted }.
|
||||
let selection = $state<Record<number, Record<string, boolean>>>({});
|
||||
$effect(() => {
|
||||
grant.$id;
|
||||
const next: Record<number, Record<string, boolean>> = {};
|
||||
details.forEach((detail, index) => {
|
||||
if (!isAppwriteProjectDetail(detail)) return;
|
||||
const actionMap: Record<string, boolean> = {};
|
||||
for (const action of actionsOf(detail)) {
|
||||
actionMap[action] = true;
|
||||
}
|
||||
next[index] = actionMap;
|
||||
});
|
||||
selection = next;
|
||||
});
|
||||
|
||||
// Best-effort id -> project resolution. Fills in asynchronously; until then
|
||||
// (and for anything unresolved) headers fall back to the raw project id.
|
||||
let projectNames = $state<Record<string, ResolvedProject>>({});
|
||||
$effect(() => {
|
||||
grant.$id;
|
||||
const ids = collectProjectIds(details);
|
||||
if (ids.length === 0) {
|
||||
projectNames = {};
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void resolveProjectNames(ids).then((map) => {
|
||||
if (!cancelled) projectNames = Object.fromEntries(map);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
});
|
||||
|
||||
function projectsForDetail(detail: AuthorizationDetail): ResolvedProject[] {
|
||||
return (detail.projectIds ?? [])
|
||||
.filter((id): id is string => typeof id === 'string' && id !== '')
|
||||
.map((id) => projectNames[id] ?? { id, name: id, resolved: false });
|
||||
}
|
||||
|
||||
const grantedActionCount = $derived(
|
||||
Object.values(selection).reduce(
|
||||
(total, actionMap) => total + Object.values(actionMap).filter(Boolean).length,
|
||||
0
|
||||
)
|
||||
);
|
||||
const grantedConsoleScopeCount = $derived(
|
||||
scopes.selectable.filter((descriptor) => scopeSelection[descriptor.id]).length
|
||||
);
|
||||
// Authorize stays enabled as long as SOMETHING is granted — a project action,
|
||||
// a console scope, an identity scope, or full access.
|
||||
const nothingToGrant = $derived(
|
||||
grantedActionCount === 0 &&
|
||||
grantedConsoleScopeCount === 0 &&
|
||||
scopes.identity.length === 0 &&
|
||||
!scopes.admin &&
|
||||
!(grant.scopes ?? []).includes('openid')
|
||||
);
|
||||
|
||||
/** The downscoped `scope` string the user consented to (identity always kept). */
|
||||
function buildGrantedScope(): string {
|
||||
const requested = grant.scopes ?? [];
|
||||
const granted: string[] = [];
|
||||
const add = (scope: string) => {
|
||||
if (!granted.includes(scope)) granted.push(scope);
|
||||
};
|
||||
if (requested.includes('openid')) add('openid');
|
||||
for (const descriptor of scopes.identity) add(descriptor.id);
|
||||
if (scopes.admin) add(scopes.admin.id);
|
||||
for (const descriptor of scopes.selectable) {
|
||||
if (scopeSelection[descriptor.id]) add(descriptor.id);
|
||||
}
|
||||
return granted.join(' ');
|
||||
}
|
||||
|
||||
async function approve() {
|
||||
if (busy) return;
|
||||
// Pin the request we're acting on. If the parent swaps in a different
|
||||
@@ -65,8 +186,15 @@
|
||||
error = null;
|
||||
approving = true;
|
||||
try {
|
||||
// Send back exactly what the user consented to (downscope-only): the
|
||||
// selected console scopes via `scope`, and the selected project
|
||||
// actions via `authorization_details` (when any were requested).
|
||||
const result = await sdk.forConsole.oauth2.approve({
|
||||
grantId
|
||||
grantId,
|
||||
scope: buildGrantedScope(),
|
||||
authorizationDetails: hasProjectActions
|
||||
? serializeGrantedDetails(details, selection)
|
||||
: undefined
|
||||
});
|
||||
if (grant.$id !== grantId) return;
|
||||
trackEvent(Submit.AccountOAuth2ConsentApprove, {
|
||||
@@ -168,44 +296,99 @@
|
||||
</span>
|
||||
<span class="scope-text">
|
||||
<span class="scope-title">{scope.title}</span>
|
||||
<span class="scope-desc">{scope.description}</span>
|
||||
</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
{#if scopes.groups.length > 0}
|
||||
<div class="scope-accordion">
|
||||
<Accordion title="App permissions" badge={String(scopes.granularCount)}>
|
||||
<ul class="scope-group-list">
|
||||
{#each scopes.groups as group (group.resource)}
|
||||
<li class="scope-group">
|
||||
<span class="scope-icon">
|
||||
<Icon icon={group.icon} size="s" />
|
||||
</span>
|
||||
<span class="scope-group-title">{group.title}</span>
|
||||
<span class="scope-group-actions">
|
||||
{#each group.actions as action (action.id)}
|
||||
<span class="scope-action-tag">{action.label}</span>
|
||||
{/each}
|
||||
</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Accordion>
|
||||
</div>
|
||||
{#if scopes.selectable.length > 0}
|
||||
<Layout.Stack gap="s">
|
||||
<Typography.Text variant="m-500">Console access</Typography.Text>
|
||||
<ul class="scope-list">
|
||||
{#each scopes.selectable as scope (scope.id)}
|
||||
<li class="scope-item">
|
||||
<span class="scope-check">
|
||||
<Selector.Checkbox
|
||||
size="s"
|
||||
id={`scope-${scope.id}`}
|
||||
disabled={busy || !!scopes.admin}
|
||||
bind:checked={scopeSelection[scope.id]} />
|
||||
</span>
|
||||
<label class="scope-text" for={`scope-${scope.id}`}>
|
||||
<span class="scope-title">{scope.title}</span>
|
||||
<span class="scope-desc">{scope.description}</span>
|
||||
</label>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{#if scopes.admin}
|
||||
<Typography.Text variant="m-400" color="--fgcolor-neutral-tertiary">
|
||||
Full access is granted, so these are included.
|
||||
</Typography.Text>
|
||||
{/if}
|
||||
</Layout.Stack>
|
||||
{/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">Project access</Typography.Text>
|
||||
<Typography.Text variant="m-400" color="--fgcolor-neutral-secondary">
|
||||
{app.name} requested access to these projects. Grant only the permissions you're
|
||||
comfortable with — you can turn any of them off.
|
||||
</Typography.Text>
|
||||
</Layout.Stack>
|
||||
|
||||
{#each details as detail, index (`${detail.type}-${index}`)}
|
||||
{#if isAppwriteProjectDetail(detail) && actionsOf(detail).length > 0}
|
||||
{@const projects = projectsForDetail(detail)}
|
||||
<div class="detail-section">
|
||||
{#if projects.length > 0}
|
||||
<div class="project-header">
|
||||
{#each projects.slice(0, MAX_PROJECT_CHIPS) as project (project.id)}
|
||||
<span class="project-chip">
|
||||
<span
|
||||
class="project-name"
|
||||
class:mono={!project.resolved}>
|
||||
{project.name}
|
||||
</span>
|
||||
{#if project.region}
|
||||
<Badge
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
content={project.region} />
|
||||
{/if}
|
||||
</span>
|
||||
{/each}
|
||||
{#if projects.length > MAX_PROJECT_CHIPS}
|
||||
<span class="project-more">
|
||||
+{projects.length - MAX_PROJECT_CHIPS} more
|
||||
</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 +403,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}
|
||||
@@ -334,7 +517,8 @@
|
||||
border-top: 1px solid var(--border-neutral);
|
||||
}
|
||||
|
||||
.scope-icon {
|
||||
.scope-icon,
|
||||
.scope-check {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -354,6 +538,10 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
label.scope-text {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.scope-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
@@ -371,59 +559,64 @@
|
||||
color: var(--fgcolor-neutral-secondary);
|
||||
}
|
||||
|
||||
/* Collapsed bucket of granular console scopes, grouped by resource. */
|
||||
.scope-accordion {
|
||||
/* Rich authorization details — one bordered picker section per requested entry. */
|
||||
.detail-section {
|
||||
border: 1px solid var(--border-neutral);
|
||||
border-radius: 0.75rem;
|
||||
overflow: hidden;
|
||||
background: var(--bgcolor-neutral-default);
|
||||
padding: 0.9rem;
|
||||
}
|
||||
|
||||
.scope-group-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding-block-start: 0.25rem;
|
||||
padding-inline-end: 0.25rem;
|
||||
.detail-section + .detail-section {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.scope-group {
|
||||
/* Project name(s) this entry's permissions apply to. */
|
||||
.project-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.8rem 0;
|
||||
gap: 0.4rem 0.6rem;
|
||||
margin-bottom: 0.85rem;
|
||||
}
|
||||
|
||||
.scope-group + .scope-group {
|
||||
border-top: 1px solid var(--border-neutral);
|
||||
}
|
||||
|
||||
.scope-group-title {
|
||||
flex: 1;
|
||||
.project-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
min-width: 0;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.project-name {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.3;
|
||||
color: var(--fgcolor-neutral-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.scope-group-actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.scope-action-tag {
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.4;
|
||||
.project-name.mono {
|
||||
font-family: var(--font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 400;
|
||||
color: var(--fgcolor-neutral-secondary);
|
||||
border: 1px solid var(--border-neutral-strong);
|
||||
border-radius: 0.4rem;
|
||||
padding: 0.1rem 0.4rem;
|
||||
background: var(--bgcolor-neutral-default);
|
||||
}
|
||||
|
||||
/* Rich authorization details — de-emphasized, compact tags. */
|
||||
.project-more {
|
||||
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>
|
||||
Reference in new issue
Block a user