From 39af2c8f673ca821efeb6a617d862f1da9fec2d5 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Fri, 26 Jun 2026 10:25:21 +0530 Subject: [PATCH 01/42] feat(oauth2): per-project permission selection on the consent screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .gitignore | 1 + .../helpers/oauth2-authorization-details.ts | 202 ++++++++++++++++++ .../(public)/oauth2/consent-card.svelte | 192 ++++++++++++++--- .../oauth2/oauth2-scope-picker.svelte | 201 +++++++++++++++++ 4 files changed, 567 insertions(+), 29 deletions(-) create mode 100644 src/lib/helpers/oauth2-authorization-details.ts create mode 100644 src/routes/(public)/oauth2/oauth2-scope-picker.svelte diff --git a/.gitignore b/.gitignore index acc78571f..69a75d2cc 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ node_modules !.env.example test-results/ playwright-report/ +.playwright-mcp/ vite.config.js.timestamp-* vite.config.ts.timestamp-* diff --git a/src/lib/helpers/oauth2-authorization-details.ts b/src/lib/helpers/oauth2-authorization-details.ts new file mode 100644 index 000000000..e18cb71ac --- /dev/null +++ b/src/lib/helpers/oauth2-authorization-details.ts @@ -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>; + +/** + * 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(); + 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 { + 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> +): 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); +} diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index 1738a3d15..4e7aafcab 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -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( + 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(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>>({}); + $effect(() => { + // Re-init keyed on the grant id + its requested details. + grant.$id; + const next: Record> = {}; + details.forEach((detail, index) => { + if (!isAppwriteConsoleDetail(detail)) return; + const actionMap: Record = {}; + 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}
- +
    {#each scopes.groups as group (group.resource)}
  • @@ -197,15 +272,46 @@ {/if} {#if details.length > 0} - - - Also requested - -
    - {#each details as detail, i (`${detail.type}-${i}`)} - {detail.type} - {/each} -
    + + + Choose what to allow + + {app.name} requested these permissions. Grant only the ones you're comfortable + with — you can turn any of them off. + + + + {#each details as detail, index (`${detail.type}-${index}`)} + {#if isAppwriteConsoleDetail(detail) && actionsOf(detail).length > 0} + {@const context = detailContext(detail)} + {@const hosts = locationHosts(detail)} +
    + {#if context || hosts.length > 0} +
    + {#if context}{context}{/if} + {#if hosts.length > 0}{hosts.join(', ')}{/if} +
    + {/if} + {#if catalog} + + {:else} +
    + +
    + {/if} +
    + {:else} + +
    + {detail.type} +
    + {/if} + {/each}
    {/if} @@ -220,7 +326,7 @@
    - + + + + + + {#if actions.length > 6} + + {/if} + + {#if categories.length === 0} + + No permissions match “{search}”. + + {:else} + +
    + + + {#each categories as category, index (category)} + {@const inCategory = actionsInCategory(category)} + {@const activeCount = inCategory.filter((d) => selected[d.action]).length} + onCategoryChange(event, category)}> + + {#each inCategory as action (action.action)} + + + + + + + {/each} + + + {/each} + +
    + {/if} + + + From 13416cd6a7ab8f162d7433b78c13eaf34ebf2149 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Fri, 26 Jun 2026 11:43:19 +0530 Subject: [PATCH 02/42] feat(oauth2): selectable console scopes + named per-project sections on consent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor the consent screen for the per-project RAR model: - Console access is now individually selectable: each account-tier scope (teams.*, projects.*, organization.keys.*, domains.*) renders as a checkbox with a real description; identity and account.admin stay read-only. The chosen subset is sent as a downscoped `scope` to oauth2.approve (RFC 6749 §3.3) — bumps the @appwrite.io/console SDK to a build that exposes the param. - Project access shows the actual project name + avatar + region per RAR entry (resolved client-side via the user's orgs → listProjects), so the user can tell which project each grant refers to. Unresolved ids fall back to the raw id. Multi-project entries list all names (truncated past five). - Sync the RAR type to the renamed `appwrite_project` (was `appwrite_console`) and add splitSelectableScopes + project-name resolution helpers. Authorize stays enabled whenever anything is granted (incl. identity-only). --- bun.lock | 4 +- package.json | 2 +- .../helpers/oauth2-authorization-details.ts | 106 +++++- src/lib/helpers/oauth2-scopes.ts | 94 +++++ .../(public)/oauth2/consent-card.svelte | 329 +++++++++++------- 5 files changed, 384 insertions(+), 151 deletions(-) diff --git a/bun.lock b/bun.lock index 2bf9dabc9..0ce5ad51e 100644 --- a/bun.lock +++ b/bun.lock @@ -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=="], diff --git a/package.json b/package.json index ab65c9235..f8fbe4302 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/lib/helpers/oauth2-authorization-details.ts b/src/lib/helpers/oauth2-authorization-details.ts index e18cb71ac..f8be6dfa6 100644 --- a/src/lib/helpers/oauth2-authorization-details.ts +++ b/src/lib/helpers/oauth2-authorization-details.ts @@ -1,22 +1,28 @@ +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 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 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_CONSOLE_RAR_TYPE = 'appwrite_console'; +export const APPWRITE_PROJECT_RAR_TYPE = 'appwrite_project'; -/** Fields an `appwrite_console` entry may carry, besides `type`/`actions`. */ +/** 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 { @@ -86,11 +92,11 @@ export function parseAuthorizationDetails(raw: string | null | undefined): Autho } } -export function isAppwriteConsoleDetail(detail: AuthorizationDetail): boolean { - return detail.type === APPWRITE_CONSOLE_RAR_TYPE; +export function isAppwriteProjectDetail(detail: AuthorizationDetail): boolean { + return detail.type === APPWRITE_PROJECT_RAR_TYPE; } -/** Distinct, requested actions for a single `appwrite_console` entry. */ +/** 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(); @@ -172,7 +178,7 @@ export function serializeGrantedDetails( const granted: AuthorizationDetail[] = []; requested.forEach((detail, index) => { - if (!isAppwriteConsoleDetail(detail)) { + if (!isAppwriteProjectDetail(detail)) { granted.push(detail); return; } @@ -186,7 +192,7 @@ export function serializeGrantedDetails( } const rebuilt: AuthorizationDetail = { - type: APPWRITE_CONSOLE_RAR_TYPE, + type: APPWRITE_PROJECT_RAR_TYPE, actions: keptActions }; for (const field of RESOURCE_FIELDS) { @@ -200,3 +206,75 @@ export function serializeGrantedDetails( 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; + +/** Unique, real project ids referenced across all appwrite_project entries. */ +export function collectProjectIds(details: AuthorizationDetail[]): string[] { + const seen = new Set(); + 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 { + 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; +} diff --git a/src/lib/helpers/oauth2-scopes.ts b/src/lib/helpers/oauth2-scopes.ts index 373d1da5d..cea1196af 100644 --- a/src/lib/helpers/oauth2-scopes.ts +++ b/src/lib/helpers/oauth2-scopes.ts @@ -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> = { 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(); + 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; diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index 4e7aafcab..266ba42f1 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -1,25 +1,40 @@ + + + + + { + e.preventDefault(); + e.stopPropagation(); + toggle(); + }}> + + + + +{#if open} +
    + + {#if !variable?.secret} + { hide(); onUpdate(); }}> + Update + + {/if} + {#if !variable?.secret} + { hide(); onSecret(); }}> + Secret + + {/if} + { hide(); onDelete(); }}> + Delete + + +
    +{/if} From de34d5e130dfef36e540bbf93bfe8b2cfa38c405 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 29 Jun 2026 17:17:30 +0530 Subject: [PATCH 17/42] fix: add background, border and shadow to floating action menu --- src/lib/components/variables/variableActionMenu.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/components/variables/variableActionMenu.svelte b/src/lib/components/variables/variableActionMenu.svelte index 3ee56f8f4..8c6aee2fd 100644 --- a/src/lib/components/variables/variableActionMenu.svelte +++ b/src/lib/components/variables/variableActionMenu.svelte @@ -80,7 +80,7 @@ {#if open}
    {#if !variable?.secret} From e1e5ce4eec1f0841c8647240dd288079342f4718 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 29 Jun 2026 17:21:39 +0530 Subject: [PATCH 18/42] fix: portal menu div to document.body to prevent table cell layout breakage on mobile --- src/lib/components/variables/variableActionMenu.svelte | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/lib/components/variables/variableActionMenu.svelte b/src/lib/components/variables/variableActionMenu.svelte index 8c6aee2fd..d33153765 100644 --- a/src/lib/components/variables/variableActionMenu.svelte +++ b/src/lib/components/variables/variableActionMenu.svelte @@ -30,6 +30,15 @@ open = !open; } + function portalToBody(node: HTMLElement) { + document.body.appendChild(node); + return { + destroy() { + node.parentNode?.removeChild(node); + } + }; + } + $effect(() => { if (open && triggerEl && menuEl) { cleanup = autoUpdate(triggerEl, menuEl, () => { @@ -79,6 +88,7 @@ {#if open}
    From 7160ccbe5564247e37e87956851af8591f2ec0a5 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 29 Jun 2026 17:25:20 +0530 Subject: [PATCH 19/42] fix: reduce min column widths on small viewport to prevent table overflow --- .../components/variables/environmentVariables.svelte | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib/components/variables/environmentVariables.svelte b/src/lib/components/variables/environmentVariables.svelte index e6f50738a..f91e1b5a4 100644 --- a/src/lib/components/variables/environmentVariables.svelte +++ b/src/lib/components/variables/environmentVariables.svelte @@ -60,14 +60,14 @@ const tableColumns = $derived( $isSmallViewport ? [ - { id: 'key', width: { min: 420 } }, - { id: 'value', width: { min: 240 } }, - { id: 'actions', width: 40 } + { id: 'key', width: { min: 380, max: 520 } }, + { id: 'value', width: { min: 200, max: 320 } }, + { id: 'actions', width: 50 } ] : [ - { id: 'key', width: { min: 300 } }, - { id: 'value', width: { min: 280 } }, - { id: 'actions', width: 40 } + { id: 'key', width: { min: 280, max: 420 } }, + { id: 'value', width: { min: 200, max: 400 } }, + { id: 'actions', width: 50 } ] ); From d86ad4ec24dccd9a096a612ac4ef411893ccffbb Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 29 Jun 2026 17:27:09 +0530 Subject: [PATCH 20/42] fix: use small min widths on mobile so table fits inside wizard container --- src/lib/components/variables/environmentVariables.svelte | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/components/variables/environmentVariables.svelte b/src/lib/components/variables/environmentVariables.svelte index f91e1b5a4..f4926cbf6 100644 --- a/src/lib/components/variables/environmentVariables.svelte +++ b/src/lib/components/variables/environmentVariables.svelte @@ -60,9 +60,9 @@ const tableColumns = $derived( $isSmallViewport ? [ - { id: 'key', width: { min: 380, max: 520 } }, - { id: 'value', width: { min: 200, max: 320 } }, - { id: 'actions', width: 50 } + { id: 'key', width: { min: 120, max: 300 } }, + { id: 'value', width: { min: 100, max: 200 } }, + { id: 'actions', width: 40 } ] : [ { id: 'key', width: { min: 280, max: 420 } }, From 7193390c2feb629bc1820d251c44a13b8af32081 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 29 Jun 2026 17:29:05 +0530 Subject: [PATCH 21/42] fix: show icon-only create variable button on mobile to save horizontal space --- src/lib/components/variables/environmentVariables.svelte | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/lib/components/variables/environmentVariables.svelte b/src/lib/components/variables/environmentVariables.svelte index f4926cbf6..21a93dbdc 100644 --- a/src/lib/components/variables/environmentVariables.svelte +++ b/src/lib/components/variables/environmentVariables.svelte @@ -105,13 +105,15 @@ {/if} From c58a082c2aafe2157794116507b18bffb90d1133 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 29 Jun 2026 17:31:42 +0530 Subject: [PATCH 22/42] fix: add strategy fixed, return autoUpdate cleanup from effect, use onclick --- .../variables/variableActionMenu.svelte | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/src/lib/components/variables/variableActionMenu.svelte b/src/lib/components/variables/variableActionMenu.svelte index d33153765..f8f2bea5b 100644 --- a/src/lib/components/variables/variableActionMenu.svelte +++ b/src/lib/components/variables/variableActionMenu.svelte @@ -20,7 +20,6 @@ let open = $state(false); let triggerEl = $state(null); let menuEl = $state(null); - let cleanup: (() => void) | null = null; function hide() { open = false; @@ -40,21 +39,21 @@ } $effect(() => { - if (open && triggerEl && menuEl) { - cleanup = autoUpdate(triggerEl, menuEl, () => { - computePosition(triggerEl, menuEl, { - placement: 'bottom-end', - middleware: [offset(2), flip(), shift()] - }).then(({ x, y }) => { - if (menuEl) { - Object.assign(menuEl.style, { left: `${x}px`, top: `${y}px` }); - } - }); + if (!open || !triggerEl || !menuEl) return; + + const stop = autoUpdate(triggerEl, menuEl, () => { + computePosition(triggerEl, menuEl, { + placement: 'bottom-end', + strategy: 'fixed', + middleware: [offset(2), flip(), shift()] + }).then(({ x, y }) => { + if (menuEl) { + Object.assign(menuEl.style, { left: `${x}px`, top: `${y}px` }); + } }); - } else { - cleanup?.(); - cleanup = null; - } + }); + + return stop; }); function handleWindowClick(e: MouseEvent) { @@ -96,21 +95,21 @@ {#if !variable?.secret} { hide(); onUpdate(); }}> + onclick={() => { hide(); onUpdate(); }}> Update {/if} {#if !variable?.secret} { hide(); onSecret(); }}> + onclick={() => { hide(); onSecret(); }}> Secret {/if} { hide(); onDelete(); }}> + onclick={() => { hide(); onDelete(); }}> Delete From d73328c315c2d0f805e79c63740093337e4f91bf Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 29 Jun 2026 17:33:15 +0530 Subject: [PATCH 23/42] format --- .../variables/environmentVariables.svelte | 6 +---- .../variables/variableActionMenu.svelte | 22 +++++++++++++++---- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/lib/components/variables/environmentVariables.svelte b/src/lib/components/variables/environmentVariables.svelte index 21a93dbdc..595cc08ac 100644 --- a/src/lib/components/variables/environmentVariables.svelte +++ b/src/lib/components/variables/environmentVariables.svelte @@ -11,11 +11,7 @@ Table, Tooltip } from '@appwrite.io/pink-svelte'; - import { - IconCode, - IconUpload, - IconPlus - } from '@appwrite.io/pink-icons-svelte'; + import { IconCode, IconUpload, IconPlus } from '@appwrite.io/pink-icons-svelte'; import VariableActionMenu from './variableActionMenu.svelte'; import type { Models } from '@appwrite.io/console'; import VariableEditorModal from './variableEditorModal.svelte'; diff --git a/src/lib/components/variables/variableActionMenu.svelte b/src/lib/components/variables/variableActionMenu.svelte index f8f2bea5b..1d9caa178 100644 --- a/src/lib/components/variables/variableActionMenu.svelte +++ b/src/lib/components/variables/variableActionMenu.svelte @@ -1,7 +1,12 @@ @@ -24,12 +25,14 @@ dictionaryPolicy={data.passwordDictionaryPolicy} historyPolicy={data.passwordHistoryPolicy} personalDataPolicy={data.passwordPersonalDataPolicy} /> - + {#if isCloud} + + {/if} Date: Wed, 1 Jul 2026 10:29:56 +0530 Subject: [PATCH 27/42] fix: guard payments page on self-hosted, fix billingPlanDetails optional chain --- src/lib/layout/containerButton.svelte | 2 +- src/routes/(console)/account/payments/+page.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/lib/layout/containerButton.svelte b/src/lib/layout/containerButton.svelte index 370abfe34..e70816f68 100644 --- a/src/lib/layout/containerButton.svelte +++ b/src/lib/layout/containerButton.svelte @@ -10,7 +10,7 @@ export let title: string; export let tooltipContent = - $organization?.billingPlanDetails.group === BillingPlanGroup.Starter + $organization?.billingPlanDetails?.group === BillingPlanGroup.Starter ? `Upgrade to add more ${title.toLocaleLowerCase()}` : `You've reached the ${title.toLocaleLowerCase()} limit for the ${ $organization?.billingPlanDetails.name diff --git a/src/routes/(console)/account/payments/+page.ts b/src/routes/(console)/account/payments/+page.ts index fb0cb2d96..d1f05465f 100644 --- a/src/routes/(console)/account/payments/+page.ts +++ b/src/routes/(console)/account/payments/+page.ts @@ -1,8 +1,12 @@ +import { redirect } from '@sveltejs/kit'; import { Dependencies } from '$lib/constants'; import { sdk } from '$lib/stores/sdk'; +import { isCloud } from '$lib/system'; import type { PageLoad } from './$types'; export const load: PageLoad = async ({ depends }) => { + if (!isCloud) redirect(302, '/'); + depends(Dependencies.PAYMENT_METHODS); depends(Dependencies.ADDRESS); From 85dd10185cdf9d65614e7613f1055cc5e0726d6b Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 1 Jul 2026 10:38:55 +0530 Subject: [PATCH 28/42] fix: add missing optional chain on billingPlanDetails.name --- src/lib/layout/containerButton.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/layout/containerButton.svelte b/src/lib/layout/containerButton.svelte index e70816f68..df3aca4b5 100644 --- a/src/lib/layout/containerButton.svelte +++ b/src/lib/layout/containerButton.svelte @@ -13,7 +13,7 @@ $organization?.billingPlanDetails?.group === BillingPlanGroup.Starter ? `Upgrade to add more ${title.toLocaleLowerCase()}` : `You've reached the ${title.toLocaleLowerCase()} limit for the ${ - $organization?.billingPlanDetails.name + $organization?.billingPlanDetails?.name } plan`; export let disabled: boolean; From 8db59c814ba47c47eee921db5c4e1ef4fd5e5a45 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Wed, 1 Jul 2026 16:23:59 +0530 Subject: [PATCH 29/42] feat(oauth2): redesign cloud consent screen with RAR resource binding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rework the OAuth2 consent screen for the cloud RAR (RFC 9396) flow. Scopes now carry every requested privilege; authorization_details binds the project/organization tiers to concrete resources, and the resource binding is the only thing the user narrows on the screen. UI/UX: - Grouped surface panels, app-to-account handshake header, and a clearer permission list (replaces the old scope picker). - Supabase-style permission rows: resource-name titles, an access chip (READ / WRITE / READ + WRITE, amber when write is involved), and a one-line description per resource. Rows ordered by access strength. - Console-authored copy for every scope Cloud exposes (drops the terse live scope catalog + its network calls); sensible fallback for unknown scopes. Raw scope tokens are no longer shown inline — a hover copy button yields the exact token. - Resource selector: segmented All/Specific control, searchable chips, clearer Change/Done toggle, and an amber "needs selection" state that blocks Authorize until each requested tier is bound. Delete the standalone oauth2-scope-picker in favour of the read-only permission summary + resource selector. --- .../helpers/oauth2-authorization-details.ts | 356 +++--- src/lib/helpers/oauth2-scopes.ts | 720 ++++++++---- .../(public)/oauth2/consent-card.svelte | 1029 ++++++++++------- .../oauth2/oauth2-scope-picker.svelte | 201 ---- .../(public)/oauth2/resource-selector.svelte | 452 ++++++++ 5 files changed, 1743 insertions(+), 1015 deletions(-) delete mode 100644 src/routes/(public)/oauth2/oauth2-scope-picker.svelte create mode 100644 src/routes/(public)/oauth2/resource-selector.svelte diff --git a/src/lib/helpers/oauth2-authorization-details.ts b/src/lib/helpers/oauth2-authorization-details.ts index f8be6dfa6..d26f05179 100644 --- a/src/lib/helpers/oauth2-authorization-details.ts +++ b/src/lib/helpers/oauth2-authorization-details.ts @@ -3,84 +3,38 @@ import { sdk } from '$lib/stores/sdk'; import { getTeamOrOrganizationList } from '$lib/stores/organization'; /** - * RFC 9396 Rich Authorization Requests (RAR) helpers for the OAuth2 consent - * screen. + * RFC 9396 Rich Authorization Requests (RAR) helpers for the console OAuth2 + * consent screen (contract v2). * - * 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. + * In v2 the `scope` parameter carries every privilege the client requests (see + * `oauth2-scopes.ts`). `authorization_details` only binds those privileges to + * concrete resources, as entries of two types: + * + * { "type": "project", "identifiers": ["", …] | ["*"] } + * { "type": "organization", "identifiers": ["", …] | ["*"] } + * + * `identifiers` is the only field besides `type`; `*` is a wildcard that binds + * the tier's scopes to every project / organization the user owns (present and + * future). The consent screen lets the user narrow the requested identifiers to + * a subset and sends the result back to the approve endpoint, which replaces the + * client's requested details. */ -/** The single RAR `type` the console OAuth2 server understands. */ -export const APPWRITE_PROJECT_RAR_TYPE = 'appwrite_project'; +export const PROJECT_RAR_TYPE = 'project'; +export const ORGANIZATION_RAR_TYPE = 'organization'; + +/** Wildcard identifier — binds a tier's scopes to every owned resource. */ +export const WILDCARD_IDENTIFIER = '*'; /** 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[]; + identifiers?: 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>; - -/** - * 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 []; @@ -92,144 +46,92 @@ export function parseAuthorizationDetails(raw: string | null | undefined): Autho } } -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 []; +/** Distinct, non-empty identifiers for a single entry. */ +export function identifiersOf(detail: AuthorizationDetail): string[] { + if (!Array.isArray(detail.identifiers)) return []; const seen = new Set(); const out: string[] = []; - for (const action of detail.actions) { - if (typeof action === 'string' && action !== '' && !seen.has(action)) { - seen.add(action); - out.push(action); + for (const identifier of detail.identifiers) { + if (typeof identifier === 'string' && identifier !== '' && !seen.has(identifier)) { + seen.add(identifier); + out.push(identifier); } } 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. + * Union of identifiers across every entry of the given type, request order + * preserved. Keeps the `*` wildcard; drops the reserved `console` project id + * from `project` entries (the server rejects it anyway). */ -export async function loadActionCatalog(): Promise { - 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 - }); - } +export function mergeIdentifiers(details: AuthorizationDetail[], type: string): string[] { + const seen = new Set(); + const out: string[] = []; + for (const detail of details) { + if (detail.type !== type) continue; + for (const identifier of identifiersOf(detail)) { + if (type === PROJECT_RAR_TYPE && identifier === RESERVED_CONSOLE_PROJECT) continue; + if (seen.has(identifier)) continue; + seen.add(identifier); + out.push(identifier); } } - - return catalog; + return out; } -/** 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 - }; +export function hasWildcard(identifiers: string[]): boolean { + return identifiers.includes(WILDCARD_IDENTIFIER); +} + +/** Concrete (non-wildcard) ids among a set of identifiers. */ +export function concreteIdentifiers(identifiers: string[]): string[] { + return identifiers.filter((identifier) => identifier !== WILDCARD_IDENTIFIER); } /** - * 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). + * Rebuild the `authorization_details` array from the user's granted selection. + * Emits a `project` / `organization` entry only when that tier ends up bound to + * at least one identifier. 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> -): 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 function serializeGrantedDetails(granted: { + project?: string[]; + organization?: string[]; +}): string { + const out: AuthorizationDetail[] = []; + if (granted.project && granted.project.length > 0) { + out.push({ type: PROJECT_RAR_TYPE, identifiers: granted.project }); + } + if (granted.organization && granted.organization.length > 0) { + out.push({ type: ORGANIZATION_RAR_TYPE, identifiers: granted.organization }); + } + return JSON.stringify(out); } -export interface ResolvedProject { +/* -------------------------------------------------------------------------- */ +/* Resource name resolution — turn identifiers into display names */ +/* -------------------------------------------------------------------------- */ + +export interface ResolvedResource { id: string; - /** Project name, or the raw id when it couldn't be resolved. */ + /** Display 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. */ + /** True when a real name was found; false means we fell back to the id. */ resolved: boolean; } -export type ProjectNameMap = Map; +export type ResourceNameMap = Map; -/** Unique, real project ids referenced across all appwrite_project entries. */ -export function collectProjectIds(details: AuthorizationDetail[]): string[] { - const seen = new Set(); - 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); - } - } +function idOnlyMap(ids: string[]): ResourceNameMap { + const map: ResourceNameMap = new Map(); + for (const id of ids) { + map.set(id, { id, name: id, resolved: false }); } - return [...seen]; + return map; } /** @@ -240,11 +142,8 @@ export function collectProjectIds(details: AuthorizationDetail[]): string[] { * 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 { - const map: ProjectNameMap = new Map(); - for (const id of ids) { - map.set(id, { id, name: id, resolved: false }); - } +export async function resolveProjectNames(ids: string[]): Promise { + const map = idOnlyMap(ids); if (ids.length === 0) return map; try { @@ -278,3 +177,96 @@ export async function resolveProjectNames(ids: string[]): Promise { + const map = idOnlyMap(ids); + if (ids.length === 0) return map; + + try { + const orgs = await getTeamOrOrganizationList([Query.limit(100)]); + for (const org of orgs.teams) { + if (map.has(org.$id)) { + map.set(org.$id, { id: org.$id, name: org.name, resolved: true }); + } + } + } catch { + // Keep the id-only fallback map. + } + + return map; +} + +/* -------------------------------------------------------------------------- */ +/* Type-to-search — narrowing a wildcard grant to specific resources */ +/* -------------------------------------------------------------------------- */ + +/** How many results a resource search returns. Keeps the dropdown bounded and + * sidesteps pagination — the user types to narrow rather than scrolling. */ +const SEARCH_LIMIT = 8; +/** Cap on organizations swept per project search, to bound the request fan-out. */ +const SEARCH_ORG_SCAN = 20; + +/** + * Search the user's projects by name for the resource picker. Projects are only + * reachable through their owning organization, so we sweep the user's orgs and + * ask each for name matches, merge, and cap. An empty term returns the first + * projects found (so the picker can show something before the user types). + * Never throws: returns an empty list on failure. + */ +export async function searchProjects(term: string): Promise { + try { + const orgs = await getTeamOrOrganizationList([Query.limit(SEARCH_ORG_SCAN)]); + const trimmed = term.trim(); + const results = await Promise.allSettled( + orgs.teams.map((org) => { + const queries = [ + Query.select(['$id', 'name', 'region', 'teamId']), + Query.limit(SEARCH_LIMIT) + ]; + if (trimmed !== '') { + queries.unshift(Query.startsWith('name', trimmed)); + } + return sdk.forConsole.organization(org.$id).listProjects({ queries }); + }) + ); + + const seen = new Set(); + const out: ResolvedResource[] = []; + for (const result of results) { + if (result.status !== 'fulfilled') continue; + for (const project of result.value.projects) { + if (project.$id === RESERVED_CONSOLE_PROJECT || seen.has(project.$id)) continue; + seen.add(project.$id); + out.push({ + id: project.$id, + name: project.name, + region: project.region, + resolved: true + }); + if (out.length >= SEARCH_LIMIT) return out; + } + } + return out; + } catch { + return []; + } +} + +/** + * Load the user's organizations as resources for the org picker. Organizations + * are few enough to load once and filter client-side, so this returns the full + * list; the picker searches within it. Never throws. + */ +export async function listOrganizationResources(): Promise { + try { + const orgs = await getTeamOrOrganizationList([Query.limit(100)]); + return orgs.teams.map((org) => ({ id: org.$id, name: org.name, resolved: true })); + } catch { + return []; + } +} diff --git a/src/lib/helpers/oauth2-scopes.ts b/src/lib/helpers/oauth2-scopes.ts index cea1196af..e4d5c6e10 100644 --- a/src/lib/helpers/oauth2-scopes.ts +++ b/src/lib/helpers/oauth2-scopes.ts @@ -1,16 +1,41 @@ import type { ComponentType } from 'svelte'; import { - IconShieldCheck, - IconUser, - IconUserCircle, - IconUserGroup, - IconViewGrid, - IconGlobe, - IconMail, IconIdentification, + IconUser, + IconMail, + IconDeviceMobile, + IconShieldCheck, IconKey } from '@appwrite.io/pink-icons-svelte'; +/** + * Scope helpers for the console OAuth2 consent screen (RAR contract v2). + * + * The `scope` parameter now carries *every* privilege the client is asking for. + * `authorization_details` only binds those privileges to concrete resources + * (see `oauth2-authorization-details.ts`). A requested scope reads as one of: + * + * - an OIDC identity scope: `openid`, `profile`, `email`, `phone` + * - `all` — console-wide full access (replaces the old `account.admin`) + * - `project:all` / `project:` — project-tier permissions + * - `organization:all` / `organization:` — organization-tier permissions + * + * The consent screen only ever downscopes: it offers the requested scopes and + * sends back the subset the user consented to. + */ + +/** Console-wide full-access scope; grants everything when present. */ +export const ALL_SCOPE = 'all'; +/** Grants every project-tier scope for the bound projects. */ +export const PROJECT_ALL_SCOPE = 'project:all'; +/** Grants every organization-tier scope for the bound organizations. */ +export const ORGANIZATION_ALL_SCOPE = 'organization:all'; +export const PROJECT_SCOPE_PREFIX = 'project:'; +export const ORGANIZATION_SCOPE_PREFIX = 'organization:'; + +/** OIDC identity scopes — always granted, never toggleable, order preserved. */ +const IDENTITY_SCOPES = ['openid', 'profile', 'email', 'phone'] as const; + export interface ScopeDescriptor { id: string; title: string; @@ -18,15 +43,11 @@ export interface ScopeDescriptor { icon: ComponentType; } -export const ACCOUNT_ADMIN_SCOPE = 'account.admin'; - -export const ACCOUNT_ADMIN_DESCRIPTOR: ScopeDescriptor = { - id: ACCOUNT_ADMIN_SCOPE, - title: 'Full access to your account', - description: 'Manage your organizations, projects, and all their resources on your behalf.', - icon: IconShieldCheck -}; - +/** + * Identity + full-access scopes are described locally: they're stable and are + * not returned by the project/organization scope endpoints. Everything else is + * a project/organization scope, described from the authored resource catalog below. + */ const BUILTIN_SCOPES: Record> = { openid: { title: 'Verify your identity', @@ -40,60 +61,18 @@ const BUILTIN_SCOPES: Record> = { }, email: { title: 'View your email address', - description: 'Read the email address associated with your account.', + description: "Read your account's email address.", icon: IconMail }, - [ACCOUNT_ADMIN_SCOPE]: { - title: ACCOUNT_ADMIN_DESCRIPTOR.title, - description: ACCOUNT_ADMIN_DESCRIPTOR.description, - icon: ACCOUNT_ADMIN_DESCRIPTOR.icon + phone: { + title: 'View your phone number', + description: "Read your account's phone number.", + icon: IconDeviceMobile }, - // 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 + [ALL_SCOPE]: { + title: 'Full access to your account', + description: 'Manage all your organizations, projects, and their resources on your behalf.', + icon: IconShieldCheck } }; @@ -116,171 +95,492 @@ export function describeScope(scope: string): ScopeDescriptor { }; } -export function describeScopes(scopes: string[]): ScopeDescriptor[] { - return scopes.map(describeScope); +/** Per-tier (project / organization) requested scopes, prefix already stripped. */ +export interface TierScopes { + /** `:all` was requested — the tier's full-access toggle. */ + all: boolean; + /** Bare scope ids (prefix stripped, `all` excluded), request order preserved. */ + scopes: string[]; } -const CONSENT_IDENTITY_SCOPES = ['profile', 'email'] as const; - -/** - * Build the permission list for the console OAuth2 consent screen. The server - * enforces scope-based access, so this maps 1:1 to the issued token: full access - * only for `account.admin`, then identity scopes, then any granular scopes. - * Falls back to the lone `openid` "Verify your identity" row so a minimal OIDC - * request is never empty. - */ -export function describeConsentScopes(scopes: string[]): ScopeDescriptor[] { - const requested = new Set(scopes); - const admin = requested.has(ACCOUNT_ADMIN_SCOPE) ? [ACCOUNT_ADMIN_DESCRIPTOR] : []; - const identity = CONSENT_IDENTITY_SCOPES.filter((scope) => requested.has(scope)).map( - describeScope - ); - const remaining = scopes.filter( - (scope) => - scope !== 'openid' && - scope !== ACCOUNT_ADMIN_SCOPE && - !(CONSENT_IDENTITY_SCOPES as readonly string[]).includes(scope) - ); - - const described = [...admin, ...identity, ...remaining.map(describeScope)]; - if (described.length === 0 && requested.has('openid')) { - return [describeScope('openid')]; - } - - 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). */ +export interface ConsentScopeModel { + /** OIDC identity scopes, read-only, always granted. */ identity: ScopeDescriptor[]; - /** Account/console-tier scopes the user can individually toggle. */ - selectable: ScopeDescriptor[]; + /** Console-wide `all` full access, read-only, subsumes everything else. */ + all: ScopeDescriptor | null; + project: TierScopes; + organization: TierScopes; } -/** - * 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 - ); - +function collectTier(scopes: string[], prefix: string, allScope: string): TierScopes { const seen = new Set(); - const selectable: ScopeDescriptor[] = []; + const out: string[] = []; + let all = false; for (const scope of scopes) { - if ( - scope === 'openid' || - scope === ACCOUNT_ADMIN_SCOPE || - (CONSENT_IDENTITY_SCOPES as readonly string[]).includes(scope) || - seen.has(scope) - ) { + if (scope === allScope) { + all = true; continue; } - seen.add(scope); - selectable.push(describeScope(scope)); + if (!scope.startsWith(prefix)) continue; + const bare = scope.slice(prefix.length); + if (bare === '' || seen.has(bare)) continue; + seen.add(bare); + out.push(bare); } - - return { admin, identity, selectable }; -} - -export interface ScopeAction { - /** Full scope id, e.g. `teams.write`. */ - id: string; - /** Trailing verb, e.g. `read` / `write`. */ - action: string; - /** Display label for the verb, e.g. `Read` / `Write`. */ - label: string; -} - -export interface ScopeResourceGroup { - /** Resource prefix, e.g. `teams` or `backups.policies`. */ - resource: string; - /** Display title for the resource, e.g. `Teams`. */ - title: string; - icon: ComponentType; - actions: ScopeAction[]; -} - -export interface GroupedConsentScopes { - /** `account.admin` full-access descriptor, when requested. */ - admin: ScopeDescriptor | null; - /** OIDC identity scopes (openid/profile/email), always shown in full. */ - identity: ScopeDescriptor[]; - /** Every other granular scope, bucketed by resource for collapsing. */ - groups: ScopeResourceGroup[]; - /** Total count of granular scopes across all groups. */ - granularCount: number; + return { all, scopes: out }; } /** - * Split a granular scope into its resource prefix and trailing action verb. - * `teams.read` -> { resource: 'teams', action: 'read' }, and - * `backups.policies.write` -> { resource: 'backups.policies', action: 'write' }. - * Scopes without a `.` fall back to the whole scope as the resource. + * Split the requested `scope` values into the shape the consent screen renders: + * identity (read-only), console-wide `all` (read-only), and the project / + * organization tiers with their `all` flag and individual scopes. */ -function splitScope(scope: string): { resource: string; action: string } { - const lastDot = scope.lastIndexOf('.'); - if (lastDot <= 0) { - return { resource: scope, action: '' }; - } - return { resource: scope.slice(0, lastDot), action: scope.slice(lastDot + 1) }; -} - -/** - * Group the consent scopes for the OAuth2 consent screen. `account.admin` and the - * OIDC identity scopes stay as full, always-visible rows; everything else is - * bucketed by resource (`teams`, `projects`, …) so the granular console scopes can - * be tucked into a single collapsible section rather than a long flat list. - * Resource and action order follow first appearance in the requested scopes. - */ -export function groupConsentScopes(scopes: string[]): GroupedConsentScopes { +export function splitConsentScopes(scopes: string[]): ConsentScopeModel { 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 - ); + return { + identity: IDENTITY_SCOPES.filter((scope) => requested.has(scope)).map(describeScope), + all: requested.has(ALL_SCOPE) ? describeScope(ALL_SCOPE) : null, + project: collectTier(scopes, PROJECT_SCOPE_PREFIX, PROJECT_ALL_SCOPE), + organization: collectTier(scopes, ORGANIZATION_SCOPE_PREFIX, ORGANIZATION_ALL_SCOPE) + }; +} + +/* -------------------------------------------------------------------------- */ +/* Resource catalog — console-authored copy for every scope Cloud exposes */ +/* -------------------------------------------------------------------------- */ + +/** + * Console-authored copy per resource (the part of a scope before the last dot, + * e.g. `tables` in `tables.read`). The server's own scope descriptions are terse + * ("Access to read database tables") and read/write pairs arrive as two lines; + * this catalog gives each resource a clean title plus a description. + * + * The read/write signal lives in the row *title* ("Read Tables" / "Write Tables" + * / "Read and write Tables"), generated from the requested actions. The + * description just says what the resource is — `noun` supplies it as a sentence + * ("database tables and their structure" → "Database tables and their structure."). + * Provide an explicit `read` / `write` / `both` description only when a noun + * phrase misses nuance (read-only services, the organization tier's project + * metadata, execute-style scopes). Resources not listed fall back to a titleized + * name with no description, so future scopes still render a sensible title. + */ +interface ResourceCopy { + /** Row title — just the resource name, e.g. "Tables". */ + name: string; + /** One full-line description of what the resource covers. */ + desc?: string; +} + +const PROJECT_RESOURCE_COPY: Record = { + project: { + name: 'Project settings', + desc: "This project's general settings, name, and configuration." + }, + keys: { + name: 'API keys', + desc: "API keys that grant server-side access to this project's resources." + }, + platforms: { + name: 'Platforms', + desc: 'The web, mobile, and native app platforms registered with this project.' + }, + mocks: { + name: 'Mock numbers', + desc: 'Mock phone numbers used to test phone authentication flows.' + }, + 'project.policies': { + name: 'Project policies', + desc: "This project's security and access policies." + }, + templates: { + name: 'Templates', + desc: "The project's customizable email and SMS message templates." + }, + stages: { + name: 'Stages', + desc: 'Deployment stages used to promote changes across environments.' + }, + oauth2: { + name: 'OAuth2', + desc: "This project's OAuth2 provider configuration and token introspection." + }, + users: { + name: 'Users', + desc: 'End-user accounts, including their profiles, preferences, and identifiers.' + }, + sessions: { + name: 'Sessions', + desc: "Active login sessions belonging to this project's users." + }, + teams: { + name: 'Teams', + desc: 'Teams and their memberships, used to group and organize users.' + }, + databases: { + name: 'Databases', + desc: 'Databases and their overall configuration within this project.' + }, + tables: { + name: 'Tables', + desc: 'Database tables along with their columns, indexes, and structure.' + }, + columns: { + name: 'Columns', + desc: 'The columns that define the structure of your database tables.' + }, + indexes: { + name: 'Indexes', + desc: 'The indexes that speed up queries against your database tables.' + }, + rows: { + name: 'Rows', + desc: 'The individual rows of data stored inside your database tables.' + }, + buckets: { + name: 'Storage buckets', + desc: 'Storage buckets and their file-level permission and security settings.' + }, + files: { + name: 'Files', + desc: 'Files stored in your buckets, including uploads, downloads, and previews.' + }, + tokens: { + name: 'File tokens', + desc: 'Access tokens that grant shareable links to individual storage files.' + }, + functions: { + name: 'Functions', + desc: 'Serverless functions along with their code deployments and configuration.' + }, + executions: { + name: 'Executions', + desc: 'The execution history and logs of your serverless functions.' + }, + sites: { + name: 'Sites', + desc: 'Hosted sites and their deployments, builds, and configuration.' + }, + log: { name: 'Site logs', desc: 'Runtime and build logs produced by your sites.' }, + providers: { + name: 'Messaging providers', + desc: 'Messaging providers used to send email, SMS, and push notifications.' + }, + topics: { + name: 'Topics', + desc: 'Messaging topics that group subscribers for targeted broadcasts.' + }, + subscribers: { + name: 'Subscribers', + desc: 'Subscribers enrolled in your messaging topics.' + }, + targets: { + name: 'Targets', + desc: 'The delivery targets (email, phone, or device) attached to your users.' + }, + messages: { + name: 'Messages', + desc: 'Email, SMS, and push messages, including drafts and delivery status.' + }, + rules: { + name: 'Proxy rules', + desc: "Proxy rules that route custom domains to this project's resources." + }, + webhooks: { + name: 'Webhooks', + desc: 'Webhooks that notify external services when project events occur.' + }, + locale: { + name: 'Locale', + desc: 'The Locale service for reading locale, language, and geo information.' + }, + avatars: { + name: 'Avatars', + desc: 'The Avatars service for generating avatars, icons, flags, and QR codes.' + }, + health: { + name: 'Health', + desc: "The health and operational status of this project's services." + }, + assistant: { + name: 'AI Assistant', + desc: 'The AI Assistant that suggests answers and configuration.' + }, + migrations: { + name: 'Migrations', + desc: 'Data migrations that import from or export to other projects.' + }, + schedules: { + name: 'Schedules', + desc: 'Scheduled tasks that run functions or messages at set times.' + }, + vcs: { + name: 'Git', + desc: 'Connected Git repositories used to deploy functions and sites.' + }, + insights: { + name: 'Advisor insights', + desc: 'Advisor insights that surface recommendations for your project.' + }, + reports: { + name: 'Advisor reports', + desc: "Advisor reports generated from your project's activity." + }, + presences: { + name: 'Presence', + desc: 'Realtime presence data showing which users are currently online.' + }, + 'backups.policies': { + name: 'Backup policies', + desc: 'Policies that define when and how your data is backed up.' + }, + archives: { + name: 'Backup archives', + desc: "Backup archives captured from this project's data." + }, + restorations: { + name: 'Restorations', + desc: 'Restore operations that recover data from backup archives.' + }, + dedicatedDatabases: { + name: 'Dedicated SQL', + desc: 'Direct SQL access to run statements against dedicated databases.' + }, + domains: { name: 'Domains', desc: 'Custom domains connected to this project.' }, + events: { + name: 'Events', + desc: 'The realtime and system events emitted by this project.' + }, + apps: { + name: 'OAuth2 apps', + desc: 'OAuth2 applications registered to authorize against this project.' + }, + usage: { + name: 'Usage', + desc: "Usage statistics and metrics for this project's resources." + } +}; + +const ORGANIZATION_RESOURCE_COPY: Record = { + projects: { + name: 'Projects', + // The organization tier grants org-level management of project metadata, + // never the data inside any project — spell that out so it can't be misread. + desc: "The names, IDs, and settings of this organization's projects, but not the data inside them." + }, + 'organization.keys': { + name: 'Organization keys', + desc: 'Organization-level API keys that authorize access across projects.' + }, + domains: { + name: 'Organization domains', + desc: 'Custom domains owned and managed at the organization level.' + } +}; + +/** + * Resolve the row for one resource, given which actions (`read` / `write` / + * `execute` / …) of it were requested. Following Supabase's consent screen, the + * title is just the resource name and the read/write signal lives in a chip + * ("READ" / "WRITE" / "READ + WRITE"); the description says what the resource is. + */ +function describeResource( + resource: string, + actions: string[], + copyMap: Record +): { title: string; description?: string; access: string; accessStrong: boolean } { + const copy = copyMap[resource]; + const title = copy?.name ?? titleizeScope(resource); + const hasRead = actions.includes('read'); + const hasWrite = actions.includes('write'); + + let access: string; + let accessStrong: boolean; + if (hasRead && hasWrite) { + access = 'Read + Write'; + accessStrong = true; + } else if (hasWrite) { + access = 'Write'; + accessStrong = true; + } else if (hasRead) { + access = 'Read'; + accessStrong = false; + } else { + // Non-CRUD actions (e.g. `execute`) — label with the action itself. + access = actions[0] ? titleizeScope(actions[0]) : 'Access'; + accessStrong = true; + } + + return { title, description: copy?.desc, access, accessStrong }; +} + +/* -------------------------------------------------------------------------- */ +/* Read-only permission summary (Railway-style consent list) */ +/* -------------------------------------------------------------------------- */ + +export interface PermissionLine { + /** Row title — the resource name ("Tables"), or a descriptive title for account lines. */ + title: string; + /** One-line description of what the resource covers. */ + description?: string; + /** Raw scope token(s), space-joined, exactly as issued (incl. tier prefix). Never rendered + * inline — surfaced only via the hover copy affordance. */ + token: string; + /** Access-level chip label, e.g. "Read" / "Write" / "Read + Write". Absent on account lines. */ + access?: string; + /** Whether the chip should read as elevated (write access) rather than neutral (read-only). */ + accessStrong?: boolean; +} + +export interface PermissionGroup { + /** Section heading, e.g. `Account`, `Projects`, `Organizations`. */ + heading: string; + /** Contextual note under the heading, e.g. which resources it applies to. */ + note?: string; + lines: PermissionLine[]; +} + +/** Rank actions so `read` sorts before `write`, everything else after. */ +function actionRank(action: string): number { + if (action === 'read') return 0; + if (action === 'write') return 1; + return 2; +} + +function actionOf(scope: string): string { + const dot = scope.lastIndexOf('.'); + return dot === -1 ? scope : scope.slice(dot + 1); +} + +function resourceOf(scope: string): string { + const dot = scope.lastIndexOf('.'); + return dot === -1 ? scope : scope.slice(0, dot); +} + +function tierLines( + tier: TierScopes, + prefix: string, + allScope: string, + copyMap: Record +): PermissionLine[] { + const lines: PermissionLine[] = []; + if (tier.all) { + lines.push({ + title: + prefix === PROJECT_SCOPE_PREFIX + ? 'Full project access' + : 'Full organization access', + description: `Grant every available permission on the selected ${ + prefix === PROJECT_SCOPE_PREFIX ? 'projects' : 'organizations' + }.`, + token: allScope + }); + } + + // Group scopes by resource (everything before the last dot) so that, e.g., + // `tables.read` and `tables.write` collapse into a single "Tables" row with + // one combined description. + const groups = new Map(); + for (const scope of tier.scopes) { + const resource = resourceOf(scope); + const bucket = groups.get(resource); + if (bucket) bucket.push(scope); + else groups.set(resource, [scope]); + } - const remaining = scopes.filter( - (scope) => - scope !== 'openid' && - scope !== ACCOUNT_ADMIN_SCOPE && - !(CONSENT_IDENTITY_SCOPES as readonly string[]).includes(scope) - ); + // Order rows by how much access they grant — Read + Write first, then Write, + // then any other action, and read-only last — so the strongest grants lead. + const accessRank = (actions: string[]): number => { + const hasRead = actions.includes('read'); + const hasWrite = actions.includes('write'); + if (hasRead && hasWrite) return 0; + if (hasWrite) return 1; + if (hasRead) return 3; + return 2; + }; - const byResource = new Map(); - for (const scope of remaining) { - const { resource, action } = splitScope(scope); - let group = byResource.get(resource); - if (!group) { - group = { + const groupLines = [...groups.entries()] + .map(([resource, scopes]) => { + scopes.sort((a, b) => actionRank(actionOf(a)) - actionRank(actionOf(b))); + const actions = scopes.map(actionOf); + const { title, description, access, accessStrong } = describeResource( resource, - title: titleizeScope(resource), - icon: IconKey, - actions: [] + actions, + copyMap + ); + return { + line: { + title, + description, + token: scopes.map((scope) => prefix + scope).join(' '), + access, + accessStrong + }, + rank: accessRank(actions) }; - byResource.set(resource, group); - } - if (!group.actions.some((existing) => existing.id === scope)) { - group.actions.push({ id: scope, action, label: titleizeScope(action || scope) }); - } + }) + // Stable sort: equal ranks keep their requested order. + .sort((a, b) => a.rank - b.rank); + + for (const { line } of groupLines) lines.push(line); + + return lines; +} + +/** + * Build the read-only permission summary the consent screen displays. Scopes are + * not individually selectable — the client decides what it requests — so this is + * purely descriptive: each requested scope becomes a titled line grouped under + * Account / Projects / Organizations, with the raw token shown for transparency. + */ +export function buildConsentPermissions(model: ConsentScopeModel): PermissionGroup[] { + const groups: PermissionGroup[] = []; + + const account: PermissionLine[] = []; + if (model.identity.length > 0) { + account.push({ + title: 'View your identity', + description: 'Confirm who you are and read your basic profile details.', + token: model.identity.map((scope) => scope.id).join(' ') + }); + } + if (model.all) { + account.push({ + title: model.all.title, + description: model.all.description, + token: model.all.id + }); + } + if (account.length > 0) { + groups.push({ heading: 'Account', lines: account }); } - const groups = [...byResource.values()]; + const projectLines = tierLines( + model.project, + PROJECT_SCOPE_PREFIX, + PROJECT_ALL_SCOPE, + PROJECT_RESOURCE_COPY + ); + if (projectLines.length > 0) { + groups.push({ + heading: 'Projects', + note: 'Applies only to the projects you select below.', + lines: projectLines + }); + } - // Keep a non-empty consent screen for a minimal OIDC request. - if (!admin && identity.length === 0 && groups.length === 0 && requested.has('openid')) { - return { admin: null, identity: [describeScope('openid')], groups: [], granularCount: 0 }; + const organizationLines = tierLines( + model.organization, + ORGANIZATION_SCOPE_PREFIX, + ORGANIZATION_ALL_SCOPE, + ORGANIZATION_RESOURCE_COPY + ); + if (organizationLines.length > 0) { + groups.push({ + heading: 'Organizations', + note: 'Applies only to the organizations you select below.', + lines: organizationLines + }); } - return { admin, identity, groups, granularCount: remaining.length }; + return groups; } diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index bcdcd8d4e..b55598f60 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -1,39 +1,40 @@ - - - - {#if app.logoUri} - - {:else} -
    - {appInitial} -
    - {/if} - +{#snippet copyBtn(token: string)} + +{/snippet} + + + + + {#if projectNeedsResource} +
    + + Pick at least one project, or {app.name} gets no project access. +
    + {/if} + + {/if} + + {#if organizationRequested} +
    +
    - + - - {scope.title} - {scope.description} + + Organization access + Choose which organizations {app.name} can access. -
  • - {/each} -
- {/if} +
+ + {#if organizationNeedsResource} +
+ + Pick at least one organization, or {app.name} gets no organization access. +
+ {/if} + + {/if} - {#if scopes.selectable.length > 0} - - Console access -
    - {#each scopes.selectable as scope (scope.id)} -
  • - - - - -
  • - {/each} -
- {#if scopes.admin} - - Full access is granted, so these are included. - - {/if} -
- {/if} + {#if error} +
+ + {error} +
+ {/if} - {#if details.length > 0} - - - Project access - - {app.name} requested access to these projects. Grant only the permissions you're - comfortable with — you can turn any of them off. - + + + + + - {#each details as detail, index (`${detail.type}-${index}`)} - {#if isAppwriteProjectDetail(detail) && actionsOf(detail).length > 0} - {@const projects = projectsForDetail(detail)} -
- {#if projects.length > 0} -
- {#each projects.slice(0, MAX_PROJECT_CHIPS) as project (project.id)} - - - {project.name} - - {#if project.region} - - {/if} - - {/each} - {#if projects.length > MAX_PROJECT_CHIPS} - - +{projects.length - MAX_PROJECT_CHIPS} more - - {/if} -
- {/if} - {#if catalog} - - {:else} -
- -
- {/if} -
+

+ + + {#if flow === 'authorization' && redirectHost} + You'll be returned to {redirectHost} + {:else if flow === 'device'} + After authorizing, return to your device {:else} - -

- {detail.type} -
+ You can revoke access anytime {/if} - {/each} -
- {/if} - - {#if error} -
- - - {error} - -
- {/if} - -
- - - - -
- -

- {#if flow === 'authorization' && redirectHost} - You'll be returned to {redirectHost} - {/if} - {#if flow === 'device'} - After authorizing, return to your device - {/if} - {#if app.privacyPolicyUrl} - - Privacy - - {/if} - {#if app.termsUrl} - - Terms - - {/if} -

-
+ + {#if app.privacyPolicyUrl} + + Privacy + + {/if} + {#if app.termsUrl} + + Terms + + {/if} +

+ + diff --git a/src/routes/(public)/oauth2/oauth2-scope-picker.svelte b/src/routes/(public)/oauth2/oauth2-scope-picker.svelte deleted file mode 100644 index b4f0f6abd..000000000 --- a/src/routes/(public)/oauth2/oauth2-scope-picker.svelte +++ /dev/null @@ -1,201 +0,0 @@ - - - - - - Permissions - - {selectedCount}/{actions.length} - - - - - - - - - - {#if actions.length > 6} - - {/if} - - {#if categories.length === 0} - - No permissions match “{search}”. - - {:else} - -
- - - {#each categories as category, index (category)} - {@const inCategory = actionsInCategory(category)} - {@const activeCount = inCategory.filter((d) => selected[d.action]).length} - onCategoryChange(event, category)}> - - {#each inCategory as action (action.action)} - - - - - - - {/each} - - - {/each} - -
- {/if} -
- - diff --git a/src/routes/(public)/oauth2/resource-selector.svelte b/src/routes/(public)/oauth2/resource-selector.svelte new file mode 100644 index 000000000..c6b6ea103 --- /dev/null +++ b/src/routes/(public)/oauth2/resource-selector.svelte @@ -0,0 +1,452 @@ + + +
+
+ + {#if isEmpty} + + {/if} + {summary} + {#if isDefault} + Default + {/if} + + +
+ + {#if expanded} +
+ {#if wildcard} +
+ + +
+ {/if} + + {#if specificIds.length > 0} +
+ {#each specificIds as id (id)} + {@const r = labelFor(id)} + + {r.name} + {#if r.region} + + {/if} + + + {/each} +
+ {/if} + + {#if searchable} + +
    + {#if searching} +
  • + {:else if suggestions.length === 0} +
  • + {term.trim() + ? `No matching ${pluralLabel}` + : `Type to search ${pluralLabel}`} +
  • + {:else} + {#each suggestions as r (r.id)} +
  • + +
  • + {/each} + {/if} +
+ {/if} +
+ {/if} +
+ + From 11cdeef0fd7a4e7d520854f564cbb389843a08fd Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Wed, 1 Jul 2026 16:35:04 +0530 Subject: [PATCH 30/42] (fix): key oauth2 consent rows by token to avoid title collisions Addresses Greptile review: two resources whose names titleize to the same string would collide when keyed by title. The token is the space-joined raw scopes and is unique per row within a group. --- src/routes/(public)/oauth2/consent-card.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index b55598f60..f1eb0075f 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -310,7 +310,7 @@ {/if}
    - {#each group.lines as line (line.title)} + {#each group.lines as line (line.token)}
  • From 9a4cf75cc70b34bbb5b3826018f0a332d5ed260a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 1 Jul 2026 17:18:34 +0200 Subject: [PATCH 31/42] Fix RAR not showing project selector --- .../(public)/oauth2/consent-card.svelte | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index f1eb0075f..edc30531b 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -28,6 +28,7 @@ resolveOrganizationNames, PROJECT_RAR_TYPE, ORGANIZATION_RAR_TYPE, + WILDCARD_IDENTIFIER, type ResolvedResource, type ResourceNameMap } from '$lib/helpers/oauth2-authorization-details'; @@ -80,18 +81,30 @@ // binding is the only thing the user narrows here. const scopeModel = $derived(splitConsentScopes(grant.scopes ?? [])); const details = $derived(parseAuthorizationDetails(grant.authorizationDetails)); - const projectIdentifiers = $derived(mergeIdentifiers(details, PROJECT_RAR_TYPE)); - const organizationIdentifiers = $derived(mergeIdentifiers(details, ORGANIZATION_RAR_TYPE)); - // A tier is shown only when the client requested both permissions for it AND - // resources to bind them to — either half alone grants nothing. - const projectRequested = $derived( - (scopeModel.project.all || scopeModel.project.scopes.length > 0) && - projectIdentifiers.length > 0 + const projectScopesRequested = $derived( + scopeModel.project.all || scopeModel.project.scopes.length > 0 ); + const organizationScopesRequested = $derived( + scopeModel.organization.all || scopeModel.organization.scopes.length > 0 + ); + + // When a tier's scopes are requested but left unbound, fall back to the + // wildcard so the user still gets the full resource picker. + const projectIdentifiers = $derived.by(() => { + const bound = mergeIdentifiers(details, PROJECT_RAR_TYPE); + if (bound.length > 0) return bound; + return projectScopesRequested ? [WILDCARD_IDENTIFIER] : []; + }); + const organizationIdentifiers = $derived.by(() => { + const bound = mergeIdentifiers(details, ORGANIZATION_RAR_TYPE); + if (bound.length > 0) return bound; + return organizationScopesRequested ? [WILDCARD_IDENTIFIER] : []; + }); + + const projectRequested = $derived(projectScopesRequested && projectIdentifiers.length > 0); const organizationRequested = $derived( - (scopeModel.organization.all || scopeModel.organization.scopes.length > 0) && - organizationIdentifiers.length > 0 + organizationScopesRequested && organizationIdentifiers.length > 0 ); const redirectHost = $derived(hostnameOf(grant.redirectUri)); @@ -179,7 +192,7 @@ // Scopes are not downscoped — omit `scope` so the server keeps what // the client requested. Only the resource binding is narrowed. authorizationDetails: - details.length > 0 + projectRequested || organizationRequested ? serializeGrantedDetails({ project: projectGranted ? projectSelected : undefined, organization: organizationGranted ? organizationSelected : undefined From c61b4dd15aaecd5705acef6b83b66793b7ba1cd5 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 2 Jul 2026 17:53:40 +0530 Subject: [PATCH 32/42] feat: sort users and projects by accessedAt by default --- src/routes/(console)/organization-[organization]/+page.ts | 2 +- src/routes/(console)/project-[region]-[project]/auth/+page.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/routes/(console)/organization-[organization]/+page.ts b/src/routes/(console)/organization-[organization]/+page.ts index d82f803b6..382497b87 100644 --- a/src/routes/(console)/organization-[organization]/+page.ts +++ b/src/routes/(console)/organization-[organization]/+page.ts @@ -64,7 +64,7 @@ export const load: PageLoad = async ({ params, url, route, depends, parent }) => ...projectScopeQueries, Query.offset(offset), Query.limit(limit), - Query.orderDesc(''), + Query.orderDesc('accessedAt'), Query.equal('teamId', params.organization) ] }); diff --git a/src/routes/(console)/project-[region]-[project]/auth/+page.ts b/src/routes/(console)/project-[region]-[project]/auth/+page.ts index 1453b72dd..245993c94 100644 --- a/src/routes/(console)/project-[region]-[project]/auth/+page.ts +++ b/src/routes/(console)/project-[region]-[project]/auth/+page.ts @@ -23,7 +23,7 @@ export const load: PageLoad = async ({ url, route, params, depends }) => { search, page, users: await sdk.forProject(params.region, params.project).users.list({ - queries: [Query.limit(limit), Query.offset(offset), Query.orderDesc('')], + queries: [Query.limit(limit), Query.offset(offset), Query.orderDesc('accessedAt')], search }) }; From daf42ec6062ba227cdc177b2ae6b649788959734 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Fri, 3 Jul 2026 18:08:20 +0530 Subject: [PATCH 33/42] feat: consent-time scope narrowing for MCP grants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MCP clients now request the authorization server's full scope catalog (granular MCP scopes design), making the consent screen the narrowing control point: - oauth2-mcp.ts: isMcpGrant() detects MCP grants via the grant's RFC 8707 resources (exact-match against the hosted MCP resource URI, extendable with PUBLIC_MCP_RESOURCE_URLS); composeGrantedScopes() turns the editor selection into the approve payload — untouched selection omits scope (keeps the consent-skip literal diff empty), any narrowing emits identity + granular tokens, collapses fully-kept tiers to their umbrellas, never includes 'all' (it bypasses RAR), and 'Read + Write' emits both .read and .write. - consent-card.svelte: narrowing editor gated on isMcpGrant — default full access with a promoted 'Customize access' affordance, per- resource checkboxes with Read / Read + Write levels, a master read-only toggle, and guards (at least one non-identity scope, scope-length mirror of the server cap). Non-MCP grants render exactly as before. - oauth2-scopes.ts: buildTierEditorRows() + exported token helpers, reusing the existing resource catalog copy. - Vitest coverage for detection, normalization, env override, and all grant-composition rules. --- src/lib/helpers/oauth2-mcp.test.ts | 244 ++++++++++ src/lib/helpers/oauth2-mcp.ts | 205 +++++++++ src/lib/helpers/oauth2-scopes.ts | 66 ++- .../(public)/oauth2/consent-card.svelte | 425 +++++++++++++++++- 4 files changed, 932 insertions(+), 8 deletions(-) create mode 100644 src/lib/helpers/oauth2-mcp.test.ts create mode 100644 src/lib/helpers/oauth2-mcp.ts diff --git a/src/lib/helpers/oauth2-mcp.test.ts b/src/lib/helpers/oauth2-mcp.test.ts new file mode 100644 index 000000000..09b6dc93e --- /dev/null +++ b/src/lib/helpers/oauth2-mcp.test.ts @@ -0,0 +1,244 @@ +import { describe, expect, it } from 'vitest'; +import type { Models } from '@appwrite.io/console'; +import { + DEFAULT_MCP_RESOURCE_URLS, + MAX_SCOPE_PARAM_LENGTH, + composeGrantedScopes, + isMcpGrant, + isMcpResource, + mcpResourceUrls, + normalizeResourceUrl +} from './oauth2-mcp'; +import { splitConsentScopes } from './oauth2-scopes'; + +function grantWith(resources: string[]): Models.Oauth2Grant { + return { resources } as unknown as Models.Oauth2Grant; +} + +describe('mcpResourceUrls', () => { + it('defaults to the hosted MCP resource URI', () => { + expect(mcpResourceUrls('')).toEqual(DEFAULT_MCP_RESOURCE_URLS); + }); + + it('parses a comma-separated override', () => { + expect(mcpResourceUrls('http://localhost:8000/mcp, https://mcp.appwrite.io/mcp')).toEqual([ + 'http://localhost:8000/mcp', + 'https://mcp.appwrite.io/mcp' + ]); + }); + + it('normalizes trailing slashes only', () => { + expect(normalizeResourceUrl('https://mcp.appwrite.io/mcp/')).toBe( + 'https://mcp.appwrite.io/mcp' + ); + expect(normalizeResourceUrl('https://MCP.appwrite.io/mcp')).toBe( + 'https://MCP.appwrite.io/mcp' + ); + }); +}); + +describe('isMcpGrant', () => { + const urls = mcpResourceUrls(''); + + it('detects the hosted MCP resource URI', () => { + expect(isMcpGrant(grantWith(['https://mcp.appwrite.io/mcp']), urls)).toBe(true); + }); + + it('tolerates a trailing slash on the requested resource', () => { + expect(isMcpGrant(grantWith(['https://mcp.appwrite.io/mcp/']), urls)).toBe(true); + }); + + it('ignores unrelated resources', () => { + expect(isMcpGrant(grantWith(['https://api.example.com']), urls)).toBe(false); + expect(isMcpGrant(grantWith([]), urls)).toBe(false); + expect(isMcpGrant(grantWith(undefined as unknown as string[]), urls)).toBe(false); + }); + + it('does not loosen to any URL ending in /mcp', () => { + expect(isMcpGrant(grantWith(['https://evil.example.com/mcp']), urls)).toBe(false); + }); + + it('honors the env-style override list', () => { + const local = mcpResourceUrls('http://localhost:8000/mcp'); + expect(isMcpGrant(grantWith(['http://localhost:8000/mcp']), local)).toBe(true); + expect(isMcpGrant(grantWith(['https://mcp.appwrite.io/mcp']), local)).toBe(false); + expect(isMcpResource(['http://localhost:8000/mcp/'], local)).toBe(true); + }); +}); + +describe('composeGrantedScopes', () => { + const REQUESTED = [ + 'openid', + 'profile', + 'email', + 'all', + 'project:all', + 'organization:all', + 'project:tables.read', + 'project:tables.write', + 'project:rows.read', + 'project:rows.write', + 'project:files.read', + 'project:executions.write', + 'organization:projects.read', + 'organization:projects.write' + ]; + const model = splitConsentScopes(REQUESTED); + + const fullInput = { + model, + project: {}, + organization: {}, + readOnly: false, + resourcesNarrowed: false + }; + + it('omits scope entirely when the selection is untouched', () => { + const composed = composeGrantedScopes(fullInput); + expect(composed.scope).toBeUndefined(); + expect(composed.untouched).toBe(true); + expect(composed.blocked).toBe(false); + }); + + it('treats an explicit all-selected record as untouched', () => { + const composed = composeGrantedScopes({ + ...fullInput, + project: { + tables: { selected: true, level: 'full' }, + rows: { selected: true, level: 'full' }, + files: { selected: true, level: 'full' }, + executions: { selected: true, level: 'full' } + } + }); + expect(composed.scope).toBeUndefined(); + expect(composed.untouched).toBe(true); + }); + + it('drops `all` and collapses to umbrellas when only resources are narrowed', () => { + const composed = composeGrantedScopes({ ...fullInput, resourcesNarrowed: true }); + expect(composed.untouched).toBe(false); + expect(composed.scope).toBe('openid profile email project:all organization:all'); + }); + + it('emits both .read and .write for a kept Read + Write resource', () => { + const composed = composeGrantedScopes({ + ...fullInput, + project: { + rows: { selected: false, level: 'full' }, + files: { selected: false, level: 'full' }, + executions: { selected: false, level: 'full' } + }, + organization: { projects: { selected: false, level: 'full' } } + }); + const scopes = composed.scope!.split(' '); + expect(scopes).toContain('project:tables.read'); + expect(scopes).toContain('project:tables.write'); + expect(scopes).not.toContain('all'); + expect(scopes).not.toContain('project:all'); + expect(scopes).not.toContain('project:rows.read'); + }); + + it('keeps only .read for a read-level resource — write never implies read', () => { + const composed = composeGrantedScopes({ + ...fullInput, + project: { + tables: { selected: true, level: 'read' }, + rows: { selected: false, level: 'full' }, + files: { selected: false, level: 'full' }, + executions: { selected: false, level: 'full' } + }, + organization: { projects: { selected: false, level: 'full' } } + }); + const scopes = composed.scope!.split(' '); + expect(scopes).toContain('project:tables.read'); + expect(scopes).not.toContain('project:tables.write'); + }); + + it('collapses a fully kept tier to its umbrella while the other tier narrows', () => { + const composed = composeGrantedScopes({ + ...fullInput, + organization: { projects: { selected: true, level: 'read' } } + }); + const scopes = composed.scope!.split(' '); + expect(scopes).toContain('project:all'); + expect(scopes).toContain('organization:projects.read'); + expect(scopes).not.toContain('organization:all'); + expect(scopes).not.toContain('all'); + }); + + it('always retains the identity scopes', () => { + const composed = composeGrantedScopes({ + ...fullInput, + project: { + tables: { selected: true, level: 'read' }, + rows: { selected: false, level: 'full' }, + files: { selected: false, level: 'full' }, + executions: { selected: false, level: 'full' } + }, + organization: { projects: { selected: false, level: 'full' } } + }); + expect(composed.scope!.startsWith('openid profile email ')).toBe(true); + }); + + it('the master read-only toggle keeps only .read tokens', () => { + const composed = composeGrantedScopes({ ...fullInput, readOnly: true }); + const scopes = composed.scope!.split(' '); + expect(scopes).toContain('project:tables.read'); + expect(scopes).toContain('project:rows.read'); + expect(scopes).toContain('project:files.read'); + expect(scopes).toContain('organization:projects.read'); + expect(scopes.some((scope) => scope.endsWith('.write'))).toBe(false); + expect(scopes).not.toContain('all'); + expect(scopes).not.toContain('project:all'); + }); + + it('blocks when no non-identity scope remains', () => { + const composed = composeGrantedScopes({ + ...fullInput, + project: { + tables: { selected: false, level: 'full' }, + rows: { selected: false, level: 'full' }, + files: { selected: false, level: 'full' }, + executions: { selected: false, level: 'full' } + }, + organization: { projects: { selected: false, level: 'full' } } + }); + expect(composed.blocked).toBe(true); + }); + + it('every emitted scope is a literal subset of the request', () => { + const requested = new Set(REQUESTED); + const composed = composeGrantedScopes({ + ...fullInput, + readOnly: true, + resourcesNarrowed: true + }); + for (const scope of composed.scope!.split(' ')) { + expect(requested.has(scope)).toBe(true); + } + }); + + it('collapses the larger tier to its umbrella when the length cap is exceeded', () => { + const manyScopes = ['openid', 'all', 'project:all', 'organization:all']; + for (let i = 0; i < 900; i++) { + manyScopes.push(`project:resource${i}.read`); + } + manyScopes.push('organization:projects.read'); + const bigModel = splitConsentScopes(manyScopes); + // Narrow one project resource so the tier can't collapse on its own — + // the remaining ~899 granular tokens blow past the cap. + const narrowedProject: Record = { + resource0: { selected: false, level: 'full' } + }; + const long = composeGrantedScopes({ + model: bigModel, + project: narrowedProject, + organization: { projects: { selected: true, level: 'read' } }, + readOnly: false, + resourcesNarrowed: false + }); + expect(long.lengthCollapsed).toBe(true); + expect(long.scope!.length).toBeLessThanOrEqual(MAX_SCOPE_PARAM_LENGTH); + expect(long.scope!.split(' ')).toContain('project:all'); + }); +}); diff --git a/src/lib/helpers/oauth2-mcp.ts b/src/lib/helpers/oauth2-mcp.ts new file mode 100644 index 000000000..a16c01f62 --- /dev/null +++ b/src/lib/helpers/oauth2-mcp.ts @@ -0,0 +1,205 @@ +import { env } from '$env/dynamic/public'; +import type { Models } from '@appwrite.io/console'; +import { + ALL_SCOPE, + PROJECT_ALL_SCOPE, + ORGANIZATION_ALL_SCOPE, + PROJECT_SCOPE_PREFIX, + ORGANIZATION_SCOPE_PREFIX, + scopeAction, + scopeResource, + type ConsentScopeModel, + type TierScopes +} from '$lib/helpers/oauth2-scopes'; + +/** + * MCP-grant detection and consent-time scope narrowing for the hosted Appwrite + * MCP server (granular MCP scopes design). + * + * The MCP server advertises the authorization server's full scope catalog, so + * MCP clients mechanically request *everything*. The consent screen detects + * those grants — the grant's RFC 8707 `resources` contains the MCP server's + * canonical resource URI — and only then offers a narrowing editor. Because + * every granular scope was literally requested, whatever the user narrows to is + * a plain subset that the approve endpoint's literal check already accepts. + * + * The detection signal is self-fulfilling: the resource value becomes the + * token's `aud`, and the MCP server hard-rejects foreign audiences, so a lying + * client gains nothing by claiming the MCP resource URI. + */ + +/** Canonical resource URI of the hosted Appwrite MCP server. */ +export const DEFAULT_MCP_RESOURCE_URLS = ['https://mcp.appwrite.io/mcp']; + +/** Mirror of the authorization server's `scope` parameter length cap. */ +export const MAX_SCOPE_PARAM_LENGTH = 8192; + +/** Normalize an RFC 8707 resource URI for comparison: trailing slashes only — + * resource indicators are canonical URIs, so anything else compares exactly. */ +export function normalizeResourceUrl(url: string): string { + return url.trim().replace(/\/+$/, ''); +} + +/** + * The MCP resource URIs this console recognizes. Defaults to the hosted MCP; + * extendable via the comma-separated `PUBLIC_MCP_RESOURCE_URLS` env var (e.g. + * `http://localhost:8000/mcp` for local development). + */ +export function mcpResourceUrls(raw?: string | null): string[] { + const configured = (raw ?? env.PUBLIC_MCP_RESOURCE_URLS ?? '') + .split(',') + .map(normalizeResourceUrl) + .filter((url) => url !== ''); + const urls = configured.length > 0 ? configured : DEFAULT_MCP_RESOURCE_URLS; + return urls.map(normalizeResourceUrl); +} + +/** Whether any of the grant's requested resources is a known MCP resource URI. */ +export function isMcpResource(resources: string[], urls: string[] = mcpResourceUrls()): boolean { + const known = new Set(urls.map(normalizeResourceUrl)); + return resources.some( + (resource) => typeof resource === 'string' && known.has(normalizeResourceUrl(resource)) + ); +} + +/** MCP grants (and only MCP grants) get the consent-time narrowing editor. */ +export function isMcpGrant(grant: Models.Oauth2Grant, urls?: string[]): boolean { + return isMcpResource(grant.resources ?? [], urls ?? mcpResourceUrls()); +} + +/* -------------------------------------------------------------------------- */ +/* Grant composition — turn the editor's selection into the approve payload */ +/* -------------------------------------------------------------------------- */ + +/** Per-resource editor selection within one tier. Rows absent from the record + * default to selected with full requested access. */ +export interface ResourceSelection { + selected: boolean; + /** `full` grants every requested action; `read` keeps only `.read`. */ + level: 'full' | 'read'; +} + +export type TierSelection = Record; + +export interface ComposeInput { + model: ConsentScopeModel; + project: TierSelection; + organization: TierSelection; + /** Master read-only toggle — treats every selected resource as `read`. */ + readOnly: boolean; + /** True when the user narrowed the org/project resource pickers. */ + resourcesNarrowed: boolean; +} + +export interface ComposedGrant { + /** + * The `scope` value for the approve endpoint, or `undefined` to omit it. + * Omission means "grant the full literal requested list" — required so the + * consent-skip diff stays empty on the next re-authorization. + */ + scope: string | undefined; + /** The user's selection is the full request — nothing was narrowed. */ + untouched: boolean; + /** No non-identity scope remains; Authorize must be disabled. */ + blocked: boolean; + /** A tier was collapsed to its umbrella to fit the scope length cap. */ + lengthCollapsed: boolean; +} + +/** The bare scope tokens (`tables.read`, …) one tier's selection emits. Every + * emitted token is one of the tier's requested tokens — never synthesized — + * so the result is a literal subset of the request by construction. */ +function tierEmission( + tier: TierScopes, + selection: TierSelection, + readOnly: boolean +): { tokens: string[]; full: boolean } { + const tokens: string[] = []; + for (const token of tier.scopes) { + const resource = scopeResource(token); + const action = scopeAction(token); + const row = selection[resource] ?? { selected: true, level: 'full' }; + if (!row.selected) continue; + const level = readOnly ? 'read' : row.level; + if (level === 'read' && action !== 'read') continue; + tokens.push(token); + } + return { tokens, full: tokens.length === tier.scopes.length }; +} + +/** + * Compose the scope narrowing to send to the approve endpoint. + * + * - Untouched selection → omit `scope` entirely: the server keeps the full + * literal requested list, so re-authorizations skip consent (the diff against + * the previously approved scopes stays empty). + * - Any narrowing → identity scopes plus the selected granular tokens; a tier + * whose requested tokens all survive collapses to its requested umbrella + * (`project:all` / `organization:all`). The console-wide `all` is never part + * of a narrowed grant — it bypasses RFC 9396 resource restrictions. + * - `.write` never implies `.read`: a "Read + Write" row emits both tokens. + */ +export function composeGrantedScopes(input: ComposeInput): ComposedGrant { + const { model, readOnly, resourcesNarrowed } = input; + + const project = tierEmission(model.project, input.project, readOnly); + const organization = tierEmission(model.organization, input.organization, readOnly); + + const capabilitiesFull = project.full && organization.full && !readOnly; + if (capabilitiesFull && !resourcesNarrowed) { + return { scope: undefined, untouched: true, blocked: false, lengthCollapsed: false }; + } + + // A fully-kept tier collapses to its umbrella (when the umbrella was + // requested) — keeps the granted string short and re-consent diffs sane. + // Covers the degenerate umbrella-only request (`project:all` with no + // granular tokens) too: a full selection keeps the umbrella. + const tierScopes = ( + tier: TierScopes, + emission: { tokens: string[]; full: boolean }, + prefix: string, + umbrella: string + ): string[] => { + const requested = tier.all || tier.scopes.length > 0; + if (requested && emission.full && tier.all) return [umbrella]; + return emission.tokens.map((token) => prefix + token); + }; + + let projectScopes = tierScopes(model.project, project, PROJECT_SCOPE_PREFIX, PROJECT_ALL_SCOPE); + let organizationScopes = tierScopes( + model.organization, + organization, + ORGANIZATION_SCOPE_PREFIX, + ORGANIZATION_ALL_SCOPE + ); + + const blocked = projectScopes.length === 0 && organizationScopes.length === 0; + + const identity = model.identity.map((scope) => scope.id); + const join = () => [...identity, ...projectScopes, ...organizationScopes].join(' '); + + // Client-side mirror of the server's scope length cap. Unreachable in + // practice (the full catalog is ~2.6 KB), but if a selection ever exceeds + // it, collapse the larger tier to its requested umbrella and surface that. + let lengthCollapsed = false; + if (join().length > MAX_SCOPE_PARAM_LENGTH) { + const projectLength = projectScopes.join(' ').length; + const organizationLength = organizationScopes.join(' ').length; + if (projectLength >= organizationLength && model.project.all) { + projectScopes = [PROJECT_ALL_SCOPE]; + lengthCollapsed = true; + } else if (model.organization.all) { + organizationScopes = [ORGANIZATION_ALL_SCOPE]; + lengthCollapsed = true; + } + if (join().length > MAX_SCOPE_PARAM_LENGTH && model.project.all) { + projectScopes = [PROJECT_ALL_SCOPE]; + lengthCollapsed = true; + } + } + + return { scope: join(), untouched: false, blocked, lengthCollapsed }; +} + +/** Never granted by a narrowed MCP consent — documented here for tests. */ +export const NARROWED_GRANT_NEVER_INCLUDES = [ALL_SCOPE]; diff --git a/src/lib/helpers/oauth2-scopes.ts b/src/lib/helpers/oauth2-scopes.ts index e4d5c6e10..4b09c75ee 100644 --- a/src/lib/helpers/oauth2-scopes.ts +++ b/src/lib/helpers/oauth2-scopes.ts @@ -446,16 +446,21 @@ function actionRank(action: string): number { return 2; } -function actionOf(scope: string): string { +/** The action of a bare scope token — `read` in `tables.read`. */ +export function scopeAction(scope: string): string { const dot = scope.lastIndexOf('.'); return dot === -1 ? scope : scope.slice(dot + 1); } -function resourceOf(scope: string): string { +/** The resource of a bare scope token — `tables` in `tables.read`. */ +export function scopeResource(scope: string): string { const dot = scope.lastIndexOf('.'); return dot === -1 ? scope : scope.slice(0, dot); } +const actionOf = scopeAction; +const resourceOf = scopeResource; + function tierLines( tier: TierScopes, prefix: string, @@ -526,6 +531,63 @@ function tierLines( return lines; } +/* -------------------------------------------------------------------------- */ +/* Editor rows — per-resource rows for the MCP consent narrowing editor */ +/* -------------------------------------------------------------------------- */ + +export interface EditorRow { + /** Resource key (everything before the last dot), stable editor identity. */ + resource: string; + /** Display title from the resource catalog, e.g. "Tables". */ + title: string; + /** One-line description of what the resource covers. */ + description?: string; + /** Requested actions for this resource, `read` before `write` before others. */ + actions: string[]; + hasRead: boolean; + hasWrite: boolean; + /** Access chip label for the full requested access, e.g. "Read + Write". */ + access: string; + /** Whether the chip should read as elevated (write access). */ + accessStrong: boolean; +} + +/** + * Group one tier's requested scopes into per-resource editor rows for the MCP + * consent narrowing editor. Same grouping and copy as the read-only summary, + * but keyed by resource so each row can be toggled and its access level set. + */ +export function buildTierEditorRows(tier: TierScopes, prefix: string): EditorRow[] { + const copyMap = + prefix === PROJECT_SCOPE_PREFIX ? PROJECT_RESOURCE_COPY : ORGANIZATION_RESOURCE_COPY; + const groups = new Map(); + for (const scope of tier.scopes) { + const resource = resourceOf(scope); + const bucket = groups.get(resource); + if (bucket) bucket.push(scope); + else groups.set(resource, [scope]); + } + return [...groups.entries()].map(([resource, scopes]) => { + scopes.sort((a, b) => actionRank(actionOf(a)) - actionRank(actionOf(b))); + const actions = scopes.map(actionOf); + const { title, description, access, accessStrong } = describeResource( + resource, + actions, + copyMap + ); + return { + resource, + title, + description, + actions, + hasRead: actions.includes('read'), + hasWrite: actions.includes('write'), + access, + accessStrong + }; + }); +} + /** * Build the read-only permission summary the consent screen displays. Scopes are * not individually selectable — the client decides what it requests — so this is diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index edc30531b..fcf50e7b5 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -11,13 +11,28 @@ IconOfficeBuilding, IconLockClosed, IconExclamationCircle, - IconDuplicate + IconDuplicate, + IconAdjustments, + IconShieldCheck } 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 { splitConsentScopes, buildConsentPermissions } from '$lib/helpers/oauth2-scopes'; + import { + splitConsentScopes, + buildConsentPermissions, + buildTierEditorRows, + PROJECT_SCOPE_PREFIX, + ORGANIZATION_SCOPE_PREFIX, + type EditorRow + } from '$lib/helpers/oauth2-scopes'; + import { + isMcpGrant, + composeGrantedScopes, + type TierSelection, + type ResourceSelection + } from '$lib/helpers/oauth2-mcp'; import { parseAuthorizationDetails, mergeIdentifiers, @@ -114,17 +129,92 @@ const permissionGroups = $derived(buildConsentPermissions(scopeModel)); let showPermissions = $state(true); + // MCP grants (detected via the grant's RFC 8707 resources) get a narrowing + // editor: the client requested the full scope catalog, so consent is the + // control point. Every other grant renders exactly as before — read-only + // permissions, no scope narrowing. + const canNarrow = $derived(isMcpGrant(grant)); + // The one thing the user controls: which projects / organizations the tiers // are bound to. Defaults to exactly what the client requested; reset on grant // change so a stale selection can't leak. let projectSelected = $state([]); let organizationSelected = $state([]); + + // Scope-narrowing editor state (MCP grants only). Rows absent from a tier's + // selection are selected with full requested access, so the empty record is + // the "full access" default. + let customize = $state(false); + let readOnlyAll = $state(false); + let projectSelection = $state({}); + let organizationSelection = $state({}); + $effect(() => { grant.$id; projectSelected = [...projectIdentifiers]; organizationSelected = [...organizationIdentifiers]; + customize = false; + readOnlyAll = false; + projectSelection = {}; + organizationSelection = {}; }); + const projectRows = $derived( + canNarrow ? buildTierEditorRows(scopeModel.project, PROJECT_SCOPE_PREFIX) : [] + ); + const organizationRows = $derived( + canNarrow ? buildTierEditorRows(scopeModel.organization, ORGANIZATION_SCOPE_PREFIX) : [] + ); + + function sameIdentifiers(a: string[], b: string[]): boolean { + return a.length === b.length && a.every((id) => b.includes(id)); + } + const resourcesNarrowed = $derived( + !sameIdentifiers(projectSelected, projectIdentifiers) || + !sameIdentifiers(organizationSelected, organizationIdentifiers) + ); + + // The narrowed grant to send on approve. `scope: undefined` means the user + // kept the full request — the approve call then omits `scope` so the server + // grants the full literal requested list and re-authorizations skip consent. + const composed = $derived( + canNarrow + ? composeGrantedScopes({ + model: scopeModel, + project: projectSelection, + organization: organizationSelection, + readOnly: readOnlyAll, + resourcesNarrowed + }) + : null + ); + + function rowState(selection: TierSelection, resource: string): ResourceSelection { + return selection[resource] ?? { selected: true, level: 'full' }; + } + + function updateRow( + tier: 'project' | 'organization', + resource: string, + patch: Partial + ) { + const selection = tier === 'project' ? projectSelection : organizationSelection; + const next = { ...selection, [resource]: { ...rowState(selection, resource), ...patch } }; + if (tier === 'project') projectSelection = next; + else organizationSelection = next; + } + + function setAllRows(tier: 'project' | 'organization', rows: EditorRow[], selected: boolean) { + const next: TierSelection = {}; + for (const row of rows) next[row.resource] = { selected, level: 'full' }; + if (tier === 'project') projectSelection = next; + else organizationSelection = next; + } + + function tierAllSelected(rows: EditorRow[], selection: TierSelection): boolean { + return rows.every((row) => rowState(selection, row.resource).selected); + } + const projectGranted = $derived(projectRequested && projectSelected.length > 0); const organizationGranted = $derived(organizationRequested && organizationSelected.length > 0); @@ -144,7 +234,13 @@ !projectGranted && !organizationGranted ); - const blocked = $derived(nothingToGrant || projectNeedsResource || organizationNeedsResource); + // With the narrowing editor, the selection must keep at least one + // non-identity scope — an identity-only grant would leave the app + // "authorized" but unable to act. + const nothingSelected = $derived(composed?.blocked ?? false); + const blocked = $derived( + nothingToGrant || projectNeedsResource || organizationNeedsResource || nothingSelected + ); // Resource search wiring. Projects search server-side (there can be many); // organizations are few, so they load once and filter client-side. @@ -189,8 +285,12 @@ try { const result = await sdk.forConsole.oauth2.approve({ grantId, - // Scopes are not downscoped — omit `scope` so the server keeps what - // the client requested. Only the resource binding is narrowed. + // For MCP grants the editor may downscope the requested catalog; + // `scope` stays omitted when the user kept the full request so + // the server grants the full literal requested list (keeping the + // consent-skip diff empty on re-authorization). Non-MCP grants + // never send `scope` — only the resource binding is narrowed. + scope: composed?.scope, authorizationDetails: projectRequested || organizationRequested ? serializeGrantedDetails({ @@ -243,6 +343,88 @@ } +{#snippet editorGroup( + tierKey: 'project' | 'organization', + heading: string, + note: string, + rows: EditorRow[], + selection: TierSelection +)} + {#if rows.length > 0} +
    +
    + + {note} +
    +
      + {#each rows as row (row.resource)} + {@const state = rowState(selection, row.resource)} +
    • + + + + {row.title} + {#if row.hasRead && row.hasWrite} + + + + + {:else} + + {row.access} + + {/if} + + {#if row.description} + {row.description} + {/if} + +
    • + {/each} +
    +
    + {/if} +{/snippet} + {#snippet copyBtn(token: string)} + + {#if customize} +
    + + + {#if scopeModel.identity.length > 0} + + Basic identity ({scopeModel.identity + .map((scope) => scope.id) + .join(', ')}) is always shared so {app.name} can recognize your + account. + + {/if} + + {@render editorGroup( + 'project', + 'Projects', + 'Applies only to the projects you select below.', + projectRows, + projectSelection + )} + {@render editorGroup( + 'organization', + 'Organizations', + 'Applies only to the organizations you select below.', + organizationRows, + organizationSelection + )} + + {#if nothingSelected} +
    + + Select at least one permission, or {app.name} gets no access + at all. +
    + {/if} + {#if composed?.lengthCollapsed} +
    + + Your selection was too long to grant scope-by-scope, so a + fully selected tier was granted as full tier access instead. +
    + {/if} +
    + {/if} + + {:else if permissionGroups.length > 0}
    From 3b26e6b408d7ba9edbab541fdf8b1dc4f1bd53c2 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Fri, 3 Jul 2026 18:51:40 +0530 Subject: [PATCH 35/42] fix: omit authorizationDetails on untouched MCP approve to keep consent-skip working The server's consent-skip check hashes the request's authorization_details against the identity's stored details. Sending the wildcard details on an untouched MCP approve made every re-authorization re-prompt consent (the MCP request carries no authorization_details). Omit the param when the resource pickers are untouched so the server keeps exactly what the client requested; a narrowed selection is still sent and deliberately re-prompts on the next full request. Found in end-to-end testing against the local stack (scenario 4 of the granular-scopes test matrix). --- src/routes/(public)/oauth2/consent-card.svelte | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index fcf50e7b5..cd426fe3d 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -291,12 +291,22 @@ // consent-skip diff empty on re-authorization). Non-MCP grants // never send `scope` — only the resource binding is narrowed. scope: composed?.scope, + // Same consent-skip reasoning for the resource binding: on an + // MCP grant with untouched pickers, omit `authorizationDetails` + // so the server keeps exactly what the client requested — the + // re-auth diff (a hash of requested vs stored details) then + // stays empty. A narrowed selection is sent and deliberately + // forces re-consent on the next full request. authorizationDetails: projectRequested || organizationRequested - ? serializeGrantedDetails({ - project: projectGranted ? projectSelected : undefined, - organization: organizationGranted ? organizationSelected : undefined - }) + ? canNarrow && !resourcesNarrowed + ? undefined + : serializeGrantedDetails({ + project: projectGranted ? projectSelected : undefined, + organization: organizationGranted + ? organizationSelected + : undefined + }) : undefined }); if (grant.$id !== grantId) return; From 8be55afe84744ecd80e86d6f5757c1c3cbde8df5 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Fri, 3 Jul 2026 19:37:30 +0530 Subject: [PATCH 36/42] (test): drop oauth2-mcp unit tests --- src/lib/helpers/oauth2-mcp.test.ts | 244 ----------------------------- 1 file changed, 244 deletions(-) delete mode 100644 src/lib/helpers/oauth2-mcp.test.ts diff --git a/src/lib/helpers/oauth2-mcp.test.ts b/src/lib/helpers/oauth2-mcp.test.ts deleted file mode 100644 index 09b6dc93e..000000000 --- a/src/lib/helpers/oauth2-mcp.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import type { Models } from '@appwrite.io/console'; -import { - DEFAULT_MCP_RESOURCE_URLS, - MAX_SCOPE_PARAM_LENGTH, - composeGrantedScopes, - isMcpGrant, - isMcpResource, - mcpResourceUrls, - normalizeResourceUrl -} from './oauth2-mcp'; -import { splitConsentScopes } from './oauth2-scopes'; - -function grantWith(resources: string[]): Models.Oauth2Grant { - return { resources } as unknown as Models.Oauth2Grant; -} - -describe('mcpResourceUrls', () => { - it('defaults to the hosted MCP resource URI', () => { - expect(mcpResourceUrls('')).toEqual(DEFAULT_MCP_RESOURCE_URLS); - }); - - it('parses a comma-separated override', () => { - expect(mcpResourceUrls('http://localhost:8000/mcp, https://mcp.appwrite.io/mcp')).toEqual([ - 'http://localhost:8000/mcp', - 'https://mcp.appwrite.io/mcp' - ]); - }); - - it('normalizes trailing slashes only', () => { - expect(normalizeResourceUrl('https://mcp.appwrite.io/mcp/')).toBe( - 'https://mcp.appwrite.io/mcp' - ); - expect(normalizeResourceUrl('https://MCP.appwrite.io/mcp')).toBe( - 'https://MCP.appwrite.io/mcp' - ); - }); -}); - -describe('isMcpGrant', () => { - const urls = mcpResourceUrls(''); - - it('detects the hosted MCP resource URI', () => { - expect(isMcpGrant(grantWith(['https://mcp.appwrite.io/mcp']), urls)).toBe(true); - }); - - it('tolerates a trailing slash on the requested resource', () => { - expect(isMcpGrant(grantWith(['https://mcp.appwrite.io/mcp/']), urls)).toBe(true); - }); - - it('ignores unrelated resources', () => { - expect(isMcpGrant(grantWith(['https://api.example.com']), urls)).toBe(false); - expect(isMcpGrant(grantWith([]), urls)).toBe(false); - expect(isMcpGrant(grantWith(undefined as unknown as string[]), urls)).toBe(false); - }); - - it('does not loosen to any URL ending in /mcp', () => { - expect(isMcpGrant(grantWith(['https://evil.example.com/mcp']), urls)).toBe(false); - }); - - it('honors the env-style override list', () => { - const local = mcpResourceUrls('http://localhost:8000/mcp'); - expect(isMcpGrant(grantWith(['http://localhost:8000/mcp']), local)).toBe(true); - expect(isMcpGrant(grantWith(['https://mcp.appwrite.io/mcp']), local)).toBe(false); - expect(isMcpResource(['http://localhost:8000/mcp/'], local)).toBe(true); - }); -}); - -describe('composeGrantedScopes', () => { - const REQUESTED = [ - 'openid', - 'profile', - 'email', - 'all', - 'project:all', - 'organization:all', - 'project:tables.read', - 'project:tables.write', - 'project:rows.read', - 'project:rows.write', - 'project:files.read', - 'project:executions.write', - 'organization:projects.read', - 'organization:projects.write' - ]; - const model = splitConsentScopes(REQUESTED); - - const fullInput = { - model, - project: {}, - organization: {}, - readOnly: false, - resourcesNarrowed: false - }; - - it('omits scope entirely when the selection is untouched', () => { - const composed = composeGrantedScopes(fullInput); - expect(composed.scope).toBeUndefined(); - expect(composed.untouched).toBe(true); - expect(composed.blocked).toBe(false); - }); - - it('treats an explicit all-selected record as untouched', () => { - const composed = composeGrantedScopes({ - ...fullInput, - project: { - tables: { selected: true, level: 'full' }, - rows: { selected: true, level: 'full' }, - files: { selected: true, level: 'full' }, - executions: { selected: true, level: 'full' } - } - }); - expect(composed.scope).toBeUndefined(); - expect(composed.untouched).toBe(true); - }); - - it('drops `all` and collapses to umbrellas when only resources are narrowed', () => { - const composed = composeGrantedScopes({ ...fullInput, resourcesNarrowed: true }); - expect(composed.untouched).toBe(false); - expect(composed.scope).toBe('openid profile email project:all organization:all'); - }); - - it('emits both .read and .write for a kept Read + Write resource', () => { - const composed = composeGrantedScopes({ - ...fullInput, - project: { - rows: { selected: false, level: 'full' }, - files: { selected: false, level: 'full' }, - executions: { selected: false, level: 'full' } - }, - organization: { projects: { selected: false, level: 'full' } } - }); - const scopes = composed.scope!.split(' '); - expect(scopes).toContain('project:tables.read'); - expect(scopes).toContain('project:tables.write'); - expect(scopes).not.toContain('all'); - expect(scopes).not.toContain('project:all'); - expect(scopes).not.toContain('project:rows.read'); - }); - - it('keeps only .read for a read-level resource — write never implies read', () => { - const composed = composeGrantedScopes({ - ...fullInput, - project: { - tables: { selected: true, level: 'read' }, - rows: { selected: false, level: 'full' }, - files: { selected: false, level: 'full' }, - executions: { selected: false, level: 'full' } - }, - organization: { projects: { selected: false, level: 'full' } } - }); - const scopes = composed.scope!.split(' '); - expect(scopes).toContain('project:tables.read'); - expect(scopes).not.toContain('project:tables.write'); - }); - - it('collapses a fully kept tier to its umbrella while the other tier narrows', () => { - const composed = composeGrantedScopes({ - ...fullInput, - organization: { projects: { selected: true, level: 'read' } } - }); - const scopes = composed.scope!.split(' '); - expect(scopes).toContain('project:all'); - expect(scopes).toContain('organization:projects.read'); - expect(scopes).not.toContain('organization:all'); - expect(scopes).not.toContain('all'); - }); - - it('always retains the identity scopes', () => { - const composed = composeGrantedScopes({ - ...fullInput, - project: { - tables: { selected: true, level: 'read' }, - rows: { selected: false, level: 'full' }, - files: { selected: false, level: 'full' }, - executions: { selected: false, level: 'full' } - }, - organization: { projects: { selected: false, level: 'full' } } - }); - expect(composed.scope!.startsWith('openid profile email ')).toBe(true); - }); - - it('the master read-only toggle keeps only .read tokens', () => { - const composed = composeGrantedScopes({ ...fullInput, readOnly: true }); - const scopes = composed.scope!.split(' '); - expect(scopes).toContain('project:tables.read'); - expect(scopes).toContain('project:rows.read'); - expect(scopes).toContain('project:files.read'); - expect(scopes).toContain('organization:projects.read'); - expect(scopes.some((scope) => scope.endsWith('.write'))).toBe(false); - expect(scopes).not.toContain('all'); - expect(scopes).not.toContain('project:all'); - }); - - it('blocks when no non-identity scope remains', () => { - const composed = composeGrantedScopes({ - ...fullInput, - project: { - tables: { selected: false, level: 'full' }, - rows: { selected: false, level: 'full' }, - files: { selected: false, level: 'full' }, - executions: { selected: false, level: 'full' } - }, - organization: { projects: { selected: false, level: 'full' } } - }); - expect(composed.blocked).toBe(true); - }); - - it('every emitted scope is a literal subset of the request', () => { - const requested = new Set(REQUESTED); - const composed = composeGrantedScopes({ - ...fullInput, - readOnly: true, - resourcesNarrowed: true - }); - for (const scope of composed.scope!.split(' ')) { - expect(requested.has(scope)).toBe(true); - } - }); - - it('collapses the larger tier to its umbrella when the length cap is exceeded', () => { - const manyScopes = ['openid', 'all', 'project:all', 'organization:all']; - for (let i = 0; i < 900; i++) { - manyScopes.push(`project:resource${i}.read`); - } - manyScopes.push('organization:projects.read'); - const bigModel = splitConsentScopes(manyScopes); - // Narrow one project resource so the tier can't collapse on its own — - // the remaining ~899 granular tokens blow past the cap. - const narrowedProject: Record = { - resource0: { selected: false, level: 'full' } - }; - const long = composeGrantedScopes({ - model: bigModel, - project: narrowedProject, - organization: { projects: { selected: true, level: 'read' } }, - readOnly: false, - resourcesNarrowed: false - }); - expect(long.lengthCollapsed).toBe(true); - expect(long.scope!.length).toBeLessThanOrEqual(MAX_SCOPE_PARAM_LENGTH); - expect(long.scope!.split(' ')).toContain('project:all'); - }); -}); From c7b29a4f1c29966e2355ea81c60652890a2284c5 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Fri, 3 Jul 2026 19:43:12 +0530 Subject: [PATCH 37/42] (fix): add consent copy for legacy and uncovered scope resources The full 118-scope catalog surfaced resources without an entry in the consent copy maps, which rendered as bare titleized names with no description: the deprecated policies / collections / attributes / documents / execution / organization keys / devKeys pairs, plus the current project.oauth2 configuration scopes. Every scope in the live catalog now renders with a title and description. --- src/lib/helpers/oauth2-scopes.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/lib/helpers/oauth2-scopes.ts b/src/lib/helpers/oauth2-scopes.ts index 4b09c75ee..79fc427c3 100644 --- a/src/lib/helpers/oauth2-scopes.ts +++ b/src/lib/helpers/oauth2-scopes.ts @@ -192,6 +192,14 @@ const PROJECT_RESOURCE_COPY: Record = { name: 'Project policies', desc: "This project's security and access policies." }, + policies: { + name: 'Policies', + desc: "Legacy access to this project's security and backup policies." + }, + 'project.oauth2': { + name: 'OAuth2 configuration', + desc: "This project's OAuth2 authorization server configuration." + }, templates: { name: 'Templates', desc: "The project's customizable email and SMS message templates." @@ -236,6 +244,18 @@ const PROJECT_RESOURCE_COPY: Record = { name: 'Rows', desc: 'The individual rows of data stored inside your database tables.' }, + collections: { + name: 'Collections', + desc: 'Legacy database collections and their structure, replaced by tables.' + }, + attributes: { + name: 'Attributes', + desc: 'Legacy collection attributes that define document structure, replaced by columns.' + }, + documents: { + name: 'Documents', + desc: 'Legacy documents stored inside your collections, replaced by rows.' + }, buckets: { name: 'Storage buckets', desc: 'Storage buckets and their file-level permission and security settings.' @@ -256,6 +276,10 @@ const PROJECT_RESOURCE_COPY: Record = { name: 'Executions', desc: 'The execution history and logs of your serverless functions.' }, + execution: { + name: 'Executions (legacy)', + desc: 'Legacy access to function executions, replaced by Executions.' + }, sites: { name: 'Sites', desc: 'Hosted sites and their deployments, builds, and configuration.' @@ -371,6 +395,14 @@ const ORGANIZATION_RESOURCE_COPY: Record = { name: 'Organization keys', desc: 'Organization-level API keys that authorize access across projects.' }, + keys: { + name: 'Organization keys (legacy)', + desc: 'Legacy access to organization API keys, replaced by Organization keys.' + }, + devKeys: { + name: 'Development keys', + desc: 'Development keys used to bypass rate limits while building locally.' + }, domains: { name: 'Organization domains', desc: 'Custom domains owned and managed at the organization level.' From 462d5e531dcfeded325d2a1df61acc3f2f6c8a65 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 6 Jul 2026 12:42:28 +0530 Subject: [PATCH 38/42] (feat): show success screen when OAuth redirect targets a native app When an OAuth2 client redirects to a custom protocol (e.g. cursor://), the browser hands off to the OS and the tab is left hanging with no feedback. Detect non-web redirect URIs after approve/reject and render an outcome screen instead. The shared outcome card completes the consent card's identity row (dashed pending connector resolves to a check when approved, X when cancelled) and offers an Open-app button to retry the deep link. The device flow's approved/denied screens now reuse the same card. --- .../(public)/oauth2/consent-card.svelte | 24 +- .../(public)/oauth2/consent/+page.svelte | 39 ++- .../(public)/oauth2/device/+page.svelte | 64 +---- .../(public)/oauth2/outcome-card.svelte | 244 ++++++++++++++++++ 4 files changed, 311 insertions(+), 60 deletions(-) create mode 100644 src/routes/(public)/oauth2/outcome-card.svelte diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index edc30531b..1c372d1bf 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -35,6 +35,7 @@ import ResourceSelector from './resource-selector.svelte'; export type OAuth2Flow = 'authorization' | 'device'; + export type OAuth2Outcome = 'approved' | 'denied'; function hostnameOf(uri: string): string | null { try { @@ -44,6 +45,15 @@ } } + function isWebRedirect(uri: string): boolean { + try { + const { protocol } = new URL(uri); + return protocol === 'http:' || protocol === 'https:'; + } catch { + return false; + } + } + // Scope tokens are never rendered inline — they add noise. Instead each row // exposes a hover copy button that yields the raw token, exactly as issued // (prefix included), for anyone who needs the precise string. @@ -65,10 +75,10 @@ app: Models.App; accountLabel?: string; flow: OAuth2Flow; - onDeviceDone?: (outcome: 'approved' | 'denied') => void; + onDone?: (outcome: OAuth2Outcome, redirectUrl?: string) => void; } - let { grant, app, accountLabel = undefined, flow, onDeviceDone }: Props = $props(); + let { grant, app, accountLabel = undefined, flow, onDone }: Props = $props(); let error = $state(null); let approving = $state(false); @@ -202,10 +212,13 @@ if (grant.$id !== grantId) return; trackEvent(Submit.AccountOAuth2ConsentApprove, { app_id: grant.appId, flow }); if (flow === 'device' || !result.redirectUrl) { - onDeviceDone?.('approved'); + onDone?.('approved', result.redirectUrl); return; } window.location.href = result.redirectUrl; + if (!isWebRedirect(result.redirectUrl)) { + onDone?.('approved', result.redirectUrl); + } } catch (e: unknown) { if (grant.$id !== grantId) return; const message = (e as Error)?.message ?? 'Failed to authorize the application'; @@ -227,10 +240,13 @@ if (grant.$id !== grantId) return; trackEvent(Submit.AccountOAuth2ConsentDeny, { app_id: grant.appId, flow }); if (flow === 'device' || !result.redirectUrl) { - onDeviceDone?.('denied'); + onDone?.('denied', result.redirectUrl); return; } window.location.href = result.redirectUrl; + if (!isWebRedirect(result.redirectUrl)) { + onDone?.('denied', result.redirectUrl); + } } catch (e: unknown) { if (grant.$id !== grantId) return; const message = (e as Error)?.message ?? 'Failed to cancel the request'; diff --git a/src/routes/(public)/oauth2/consent/+page.svelte b/src/routes/(public)/oauth2/consent/+page.svelte index bec5acd84..cf3fa1435 100644 --- a/src/routes/(public)/oauth2/consent/+page.svelte +++ b/src/routes/(public)/oauth2/consent/+page.svelte @@ -7,15 +7,17 @@ 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'; + import OAuth2ConsentCard, { type OAuth2Outcome } from '../consent-card.svelte'; + import OAuth2OutcomeCard from '../outcome-card.svelte'; - type Phase = 'loading' | 'ready' | 'error'; + type Phase = 'loading' | 'ready' | 'approved' | 'denied' | 'error'; let phase = $state('loading'); let grant = $state(null); let app = $state(null); let account = $state | null>(null); let error = $state(null); + let completedRedirectUrl = $state(undefined); // OIDC `max_age` is a non-negative integer count of seconds. Reject anything // else (e.g. `max_age=abc`) so we omit the param rather than forwarding NaN. @@ -25,6 +27,20 @@ return Number.isInteger(value) && value >= 0 ? value : undefined; } + function isWebRedirect(uri: string): boolean { + try { + const { protocol } = new URL(uri); + return protocol === 'http:' || protocol === 'https:'; + } catch { + return false; + } + } + + function onDone(outcome: OAuth2Outcome, redirectUrl?: string) { + completedRedirectUrl = redirectUrl; + phase = outcome === 'approved' ? 'approved' : 'denied'; + } + // 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. @@ -38,6 +54,7 @@ let cancelled = false; phase = 'loading'; error = null; + completedRedirectUrl = undefined; const currentRelativeUrl = () => window.location.pathname + window.location.search; @@ -124,6 +141,14 @@ if (result.redirectUrl) { // Already consented — go straight back to the client. window.location.href = result.redirectUrl; + if (!isWebRedirect(result.redirectUrl)) { + completedRedirectUrl = result.redirectUrl; + account = loggedInAccount; + app = await sdk.forConsole.apps + .get({ appId: clientId }) + .catch(() => null); + phase = 'approved'; + } return; } if (result.grantId) { @@ -184,7 +209,15 @@ {grant} {app} accountLabel={account?.email || account?.name || undefined} - flow="authorization" /> + flow="authorization" + {onDone} /> + {:else if phase === 'approved' || phase === 'denied'} + {/if} diff --git a/src/routes/(public)/oauth2/device/+page.svelte b/src/routes/(public)/oauth2/device/+page.svelte index cc06f4bad..15f37b0d4 100644 --- a/src/routes/(public)/oauth2/device/+page.svelte +++ b/src/routes/(public)/oauth2/device/+page.svelte @@ -5,16 +5,13 @@ 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 { IconDesktopComputer } 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'; + import OAuth2ConsentCard, { type OAuth2Flow, type OAuth2Outcome } from '../consent-card.svelte'; + import OAuth2OutcomeCard from '../outcome-card.svelte'; type Phase = 'loading' | 'enter-code' | 'consent' | 'approved' | 'denied'; @@ -127,7 +124,7 @@ } } - function onDeviceDone(outcome: 'approved' | 'denied') { + function onDone(outcome: OAuth2Outcome) { phase = outcome === 'approved' ? 'approved' : 'denied'; } @@ -209,32 +206,13 @@ {app} accountLabel={account?.email || account?.name || undefined} flow={DEVICE_FLOW} - {onDeviceDone} /> - {:else if phase === 'approved'} - - -
    - -
    - Device connected - - You've authorized {app?.name ?? 'the application'}. You can return to your - device — it will continue automatically. - -
    -
    - {:else if phase === 'denied'} - - -
    - -
    - Request cancelled - - No access was granted. You can close this page. - -
    -
    + {onDone} /> + {:else if phase === 'approved' || phase === 'denied'} + {/if} @@ -300,26 +278,6 @@ 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; } diff --git a/src/routes/(public)/oauth2/outcome-card.svelte b/src/routes/(public)/oauth2/outcome-card.svelte new file mode 100644 index 000000000..b70ee2471 --- /dev/null +++ b/src/routes/(public)/oauth2/outcome-card.svelte @@ -0,0 +1,244 @@ + + + +
    +
    +
    + {#if app?.logoUri} + {appName} + {:else} +
    {appInitial}
    + {/if} + + + + + + + + +
    + +
    + {title} + + {message} + +
    +
    + +
    + {#if approved && redirectUrl} + +

    It's safe to close this tab.

    + {/if} + +

    + + {#if approved} + You can revoke access anytime in your account settings + {:else} + {appName} was not given access to your account + {/if} +

    +
    +
    +
    + + From 5396441676b88fa156aa8fde4496c70773c6217b Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 6 Jul 2026 15:27:39 +0530 Subject: [PATCH 39/42] (fix): address review comments on OAuth outcome screen Guard the already-consented fast path against a cancelled effect, hide the account avatar and move the status onto the app avatar when no account label is known, and extract the duplicated isWebRedirect helper to $lib/helpers/oauth2-redirect. --- src/lib/helpers/oauth2-redirect.ts | 14 +++++++ .../(public)/oauth2/consent-card.svelte | 10 +---- .../(public)/oauth2/consent/+page.svelte | 11 +---- .../(public)/oauth2/outcome-card.svelte | 42 ++++++++++++++++--- 4 files changed, 53 insertions(+), 24 deletions(-) create mode 100644 src/lib/helpers/oauth2-redirect.ts diff --git a/src/lib/helpers/oauth2-redirect.ts b/src/lib/helpers/oauth2-redirect.ts new file mode 100644 index 000000000..061d9046d --- /dev/null +++ b/src/lib/helpers/oauth2-redirect.ts @@ -0,0 +1,14 @@ +/** + * Whether an OAuth2 redirect URI points back to the web (http/https) rather + * than a native application deep link (e.g. cursor://). Native redirects hand + * off to the OS and leave the tab open, so the console shows an outcome + * screen instead of relying on the navigation. + */ +export function isWebRedirect(uri: string): boolean { + try { + const { protocol } = new URL(uri); + return protocol === 'http:' || protocol === 'https:'; + } catch { + return false; + } +} diff --git a/src/routes/(public)/oauth2/consent-card.svelte b/src/routes/(public)/oauth2/consent-card.svelte index 1c372d1bf..20a52ea58 100644 --- a/src/routes/(public)/oauth2/consent-card.svelte +++ b/src/routes/(public)/oauth2/consent-card.svelte @@ -18,6 +18,7 @@ import { sdk } from '$lib/stores/sdk'; import { Submit, trackError, trackEvent } from '$lib/actions/analytics'; import { splitConsentScopes, buildConsentPermissions } from '$lib/helpers/oauth2-scopes'; + import { isWebRedirect } from '$lib/helpers/oauth2-redirect'; import { parseAuthorizationDetails, mergeIdentifiers, @@ -45,15 +46,6 @@ } } - function isWebRedirect(uri: string): boolean { - try { - const { protocol } = new URL(uri); - return protocol === 'http:' || protocol === 'https:'; - } catch { - return false; - } - } - // Scope tokens are never rendered inline — they add noise. Instead each row // exposes a hover copy button that yields the raw token, exactly as issued // (prefix included), for anyone who needs the precise string. diff --git a/src/routes/(public)/oauth2/consent/+page.svelte b/src/routes/(public)/oauth2/consent/+page.svelte index cf3fa1435..799ea54d2 100644 --- a/src/routes/(public)/oauth2/consent/+page.svelte +++ b/src/routes/(public)/oauth2/consent/+page.svelte @@ -7,6 +7,7 @@ import { IconExclamation } from '@appwrite.io/pink-icons-svelte'; import { Button } from '$lib/elements/forms'; import { sdk } from '$lib/stores/sdk'; + import { isWebRedirect } from '$lib/helpers/oauth2-redirect'; import OAuth2ConsentCard, { type OAuth2Outcome } from '../consent-card.svelte'; import OAuth2OutcomeCard from '../outcome-card.svelte'; @@ -27,15 +28,6 @@ return Number.isInteger(value) && value >= 0 ? value : undefined; } - function isWebRedirect(uri: string): boolean { - try { - const { protocol } = new URL(uri); - return protocol === 'http:' || protocol === 'https:'; - } catch { - return false; - } - } - function onDone(outcome: OAuth2Outcome, redirectUrl?: string) { completedRedirectUrl = redirectUrl; phase = outcome === 'approved' ? 'approved' : 'denied'; @@ -147,6 +139,7 @@ app = await sdk.forConsole.apps .get({ appId: clientId }) .catch(() => null); + if (cancelled) return; phase = 'approved'; } return; diff --git a/src/routes/(public)/oauth2/outcome-card.svelte b/src/routes/(public)/oauth2/outcome-card.svelte index b70ee2471..bd6347cf3 100644 --- a/src/routes/(public)/oauth2/outcome-card.svelte +++ b/src/routes/(public)/oauth2/outcome-card.svelte @@ -58,14 +58,20 @@ {:else}
    {appInitial}
    {/if} - - - + {#if accountLabel} + + + + + + + + + {:else} + - - - + {/if}
    @@ -119,11 +125,35 @@ connector becomes a solid line with a status node when approved; stays dashed with an X when the request was cancelled. */ .identity { + position: relative; display: flex; align-items: center; justify-content: center; } + /* Fallback when no account is known: the status sits on the app avatar's + corner instead of in the connector. */ + .status-badge { + position: absolute; + right: -0.5rem; + bottom: -0.35rem; + display: flex; + align-items: center; + justify-content: center; + width: 1.5rem; + height: 1.5rem; + border-radius: 50%; + border: 1px solid var(--border-neutral); + background: var(--bgcolor-neutral-primary); + color: var(--fgcolor-neutral-secondary); + } + + .status-badge.approved { + border-color: var(--border-success, rgba(16, 185, 129, 0.45)); + background: var(--bgcolor-success-weaker, rgba(16, 185, 129, 0.12)); + color: var(--fgcolor-success); + } + .avatar { width: 3.5rem; height: 3.5rem; From 9c0f9ecb973924520366865c25d65759f0c0fc6f Mon Sep 17 00:00:00 2001 From: Harsh Mahajan <127186841+HarshMN2345@users.noreply.github.com> Date: Mon, 6 Jul 2026 17:05:46 +0530 Subject: [PATCH 40/42] Revert "feat: sort users and projects by last activity by default" --- src/routes/(console)/organization-[organization]/+page.ts | 2 +- src/routes/(console)/project-[region]-[project]/auth/+page.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/routes/(console)/organization-[organization]/+page.ts b/src/routes/(console)/organization-[organization]/+page.ts index 382497b87..d82f803b6 100644 --- a/src/routes/(console)/organization-[organization]/+page.ts +++ b/src/routes/(console)/organization-[organization]/+page.ts @@ -64,7 +64,7 @@ export const load: PageLoad = async ({ params, url, route, depends, parent }) => ...projectScopeQueries, Query.offset(offset), Query.limit(limit), - Query.orderDesc('accessedAt'), + Query.orderDesc(''), Query.equal('teamId', params.organization) ] }); diff --git a/src/routes/(console)/project-[region]-[project]/auth/+page.ts b/src/routes/(console)/project-[region]-[project]/auth/+page.ts index 245993c94..1453b72dd 100644 --- a/src/routes/(console)/project-[region]-[project]/auth/+page.ts +++ b/src/routes/(console)/project-[region]-[project]/auth/+page.ts @@ -23,7 +23,7 @@ export const load: PageLoad = async ({ url, route, params, depends }) => { search, page, users: await sdk.forProject(params.region, params.project).users.list({ - queries: [Query.limit(limit), Query.offset(offset), Query.orderDesc('accessedAt')], + queries: [Query.limit(limit), Query.offset(offset), Query.orderDesc('')], search }) }; From 471e15763c09602dfca3492c0b921c6907047152 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 6 Jul 2026 18:04:33 +0530 Subject: [PATCH 41/42] =?UTF-8?q?(fix):=20address=20Greptile=20review=20?= =?UTF-8?q?=E2=80=94=20guard=20umbrella=20collapse=20under=20read-only,=20?= =?UTF-8?q?drop=20redundant=20normalize=20pass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib/helpers/oauth2-mcp.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/lib/helpers/oauth2-mcp.ts b/src/lib/helpers/oauth2-mcp.ts index a16c01f62..c85918888 100644 --- a/src/lib/helpers/oauth2-mcp.ts +++ b/src/lib/helpers/oauth2-mcp.ts @@ -50,8 +50,7 @@ export function mcpResourceUrls(raw?: string | null): string[] { .split(',') .map(normalizeResourceUrl) .filter((url) => url !== ''); - const urls = configured.length > 0 ? configured : DEFAULT_MCP_RESOURCE_URLS; - return urls.map(normalizeResourceUrl); + return configured.length > 0 ? configured : DEFAULT_MCP_RESOURCE_URLS; } /** Whether any of the grant's requested resources is a known MCP resource URI. */ @@ -161,7 +160,10 @@ export function composeGrantedScopes(input: ComposeInput): ComposedGrant { umbrella: string ): string[] => { const requested = tier.all || tier.scopes.length > 0; - if (requested && emission.full && tier.all) return [umbrella]; + // Never collapse under read-only: the umbrella grants write, so a tier + // whose requested tokens are all `.read` (emission.full despite the + // toggle) must still emit the explicit token list. + if (requested && emission.full && tier.all && !readOnly) return [umbrella]; return emission.tokens.map((token) => prefix + token); }; @@ -181,8 +183,10 @@ export function composeGrantedScopes(input: ComposeInput): ComposedGrant { // Client-side mirror of the server's scope length cap. Unreachable in // practice (the full catalog is ~2.6 KB), but if a selection ever exceeds // it, collapse the larger tier to its requested umbrella and surface that. + // Umbrella collapse grants write, so it is off the table under read-only — + // the toggle already halves the token list, keeping it well under the cap. let lengthCollapsed = false; - if (join().length > MAX_SCOPE_PARAM_LENGTH) { + if (!readOnly && join().length > MAX_SCOPE_PARAM_LENGTH) { const projectLength = projectScopes.join(' ').length; const organizationLength = organizationScopes.join(' ').length; if (projectLength >= organizationLength && model.project.all) { From f14ddc4b6df9b5012a2e0f2b9f7d190cf681d7ee Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 6 Jul 2026 19:20:29 +0530 Subject: [PATCH 42/42] Remove Activity screens from the console Audit logging has permanently stopped writing to the old project-DB audit collection cloud reads from -- account, users, teams, messaging topics, and database tables/collections Activity tabs (plus the per-row/document activity side sheets) can never show new data again, and are broken outright wherever the underlying endpoint was never restored. Removes the tabs, command-palette entries, and the now-dead route/component files rather than leaving broken or permanently-stale screens in the product. --- src/lib/commandCenter/searchers/teams.ts | 11 -- src/lib/commandCenter/searchers/users.ts | 10 -- src/lib/layout/activity.svelte | 128 ------------------ src/lib/layout/index.ts | 1 - .../(console)/account/activity/+page.svelte | 8 -- .../(console)/account/activity/+page.ts | 19 --- src/routes/(console)/account/header.svelte | 6 - .../teams/team-[team]/activity/+page.svelte | 8 -- .../auth/teams/team-[team]/activity/+page.ts | 20 --- .../auth/teams/team-[team]/header.svelte | 6 - .../auth/user-[user]/activity/+page.svelte | 8 -- .../auth/user-[user]/activity/+page.ts | 19 --- .../auth/user-[user]/header.svelte | 6 - .../(entity)/views/field/activity.svelte | 74 ---------- .../(entity)/views/field/index.ts | 1 - .../views/layouts/sheetOptions.svelte | 3 - .../collection-[collection]/+layout.svelte | 15 -- .../activity/+page.svelte | 14 -- .../collection-[collection]/activity/+page.ts | 21 --- .../collection-[collection]/header.svelte | 6 - .../spreadsheet.svelte | 6 - .../collection-[collection]/store.ts | 5 - .../table-[table]/+layout.svelte | 15 -- .../table-[table]/activity/+page.svelte | 14 -- .../table-[table]/activity/+page.ts | 21 --- .../table-[table]/header.svelte | 6 - .../table-[table]/rows/activity.svelte | 68 ---------- .../table-[table]/sheetOptions.svelte | 3 - .../table-[table]/spreadsheet.svelte | 6 - .../table-[table]/store.ts | 5 - .../topics/topic-[topic]/+layout.svelte | 12 -- .../topic-[topic]/activity/+page.svelte | 8 -- .../topics/topic-[topic]/activity/+page.ts | 20 --- .../topics/topic-[topic]/header.svelte | 5 - 34 files changed, 578 deletions(-) delete mode 100644 src/lib/layout/activity.svelte delete mode 100644 src/routes/(console)/account/activity/+page.svelte delete mode 100644 src/routes/(console)/account/activity/+page.ts delete mode 100644 src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.svelte delete mode 100644 src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.ts delete mode 100644 src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.svelte delete mode 100644 src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.ts delete mode 100644 src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/activity.svelte delete mode 100644 src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/activity/+page.svelte delete mode 100644 src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/activity/+page.ts delete mode 100644 src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.svelte delete mode 100644 src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.ts delete mode 100644 src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/activity.svelte delete mode 100644 src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.svelte delete mode 100644 src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.ts diff --git a/src/lib/commandCenter/searchers/teams.ts b/src/lib/commandCenter/searchers/teams.ts index 7e9f4dc60..15fff3433 100644 --- a/src/lib/commandCenter/searchers/teams.ts +++ b/src/lib/commandCenter/searchers/teams.ts @@ -33,17 +33,6 @@ export const teamSearcher = (async (query: string) => { }, group: 'teams', nested: true - }, - - { - label: 'Go to activity', - callback: () => { - goto( - `${base}/project-${page.params.region}-${page.params.project}/auth/teams/team-${teams[0].$id}/activity` - ); - }, - group: 'teams', - nested: true } ]; } diff --git a/src/lib/commandCenter/searchers/users.ts b/src/lib/commandCenter/searchers/users.ts index c4e08409a..9e340694f 100644 --- a/src/lib/commandCenter/searchers/users.ts +++ b/src/lib/commandCenter/searchers/users.ts @@ -34,16 +34,6 @@ export const userSearcher = (async (query: string) => { nested: true, icon: IconTrash }, - { - label: 'Go to activity', - callback: () => { - goto( - `${base}/project-${page.params.region}-${page.params.project}/auth/user-${users[0].$id}/activity` - ); - }, - group: 'users', - nested: true - }, { label: 'Go to sessions', callback: () => { diff --git a/src/lib/layout/activity.svelte b/src/lib/layout/activity.svelte deleted file mode 100644 index 63f108899..000000000 --- a/src/lib/layout/activity.svelte +++ /dev/null @@ -1,128 +0,0 @@ - - - - {#if logs.total} - - - User - Event - Location - IP - Date - - {#each logs.logs as log} - - - - {#if log.userEmail} - {#if log.userName} - - {log.userName} - {:else} - - {log.userEmail} - {/if} - {:else} -
    - -
    - {log.userName ?? 'Anonymous'} - {/if} -
    -
    - - - {log.event} - - - - {#if log.countryCode !== '--'} - {log.countryName} - {:else} - Unknown - {/if} - - - - - - - - - -
    - {/each} -
    - - - {:else} - - - - - - - - {/if} -
    diff --git a/src/lib/layout/index.ts b/src/lib/layout/index.ts index 248cc3c6c..d28020209 100644 --- a/src/lib/layout/index.ts +++ b/src/lib/layout/index.ts @@ -12,7 +12,6 @@ export { default as Breadcrumbs } from './breadcrumbs.svelte'; export { default as Unauthenticated } from './unauthenticated.svelte'; export { default as Usage, type UsagePeriods } from './usage.svelte'; export { default as UsageMultiple } from './usageMultiple.svelte'; -export { default as Activity } from './activity.svelte'; export { default as Progress } from './progress.svelte'; export { default as GridHeader } from './gridHeader.svelte'; export { default as ContainerHeader } from './containerHeader.svelte'; diff --git a/src/routes/(console)/account/activity/+page.svelte b/src/routes/(console)/account/activity/+page.svelte deleted file mode 100644 index d3939555d..000000000 --- a/src/routes/(console)/account/activity/+page.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/src/routes/(console)/account/activity/+page.ts b/src/routes/(console)/account/activity/+page.ts deleted file mode 100644 index 20e70bbf3..000000000 --- a/src/routes/(console)/account/activity/+page.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Query } from '@appwrite.io/console'; -import { sdk } from '$lib/stores/sdk'; -import { getLimit, getPage, pageToOffset } from '$lib/helpers/load'; -import { PAGE_LIMIT } from '$lib/constants'; -import type { PageLoad } from './$types'; - -export const load: PageLoad = async ({ url, route }) => { - const page = getPage(url); - const limit = getLimit(url, route, PAGE_LIMIT); - const offset = pageToOffset(page, limit); - - return { - offset, - limit, - logs: await sdk.forConsole.account.listLogs({ - queries: [Query.offset(offset), Query.limit(limit)] - }) - }; -}; diff --git a/src/routes/(console)/account/header.svelte b/src/routes/(console)/account/header.svelte index 850b5953a..f39da5c9a 100644 --- a/src/routes/(console)/account/header.svelte +++ b/src/routes/(console)/account/header.svelte @@ -27,12 +27,6 @@ title: 'Applications', event: 'applications' }, - { - href: `${path}/activity`, - title: 'Activity', - event: 'activity', - hasChildren: true - }, { href: `${path}/organizations`, title: 'Organizations', diff --git a/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.svelte b/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.svelte deleted file mode 100644 index f805a79f0..000000000 --- a/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.ts b/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.ts deleted file mode 100644 index 6e680410c..000000000 --- a/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/activity/+page.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Query } from '@appwrite.io/console'; -import { sdk } from '$lib/stores/sdk'; -import { getLimit, getPage, pageToOffset } from '$lib/helpers/load'; -import { PAGE_LIMIT } from '$lib/constants'; -import type { PageLoad } from './$types'; - -export const load: PageLoad = async ({ params, url, route }) => { - const page = getPage(url); - const limit = getLimit(url, route, PAGE_LIMIT); - const offset = pageToOffset(page, limit); - - return { - offset, - limit, - logs: await sdk.forProject(params.region, params.project).teams.listLogs({ - teamId: params.team, - queries: [Query.limit(limit), Query.offset(offset)] - }) - }; -}; diff --git a/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/header.svelte b/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/header.svelte index b6bab1f33..b97c2b0f7 100644 --- a/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/header.svelte +++ b/src/routes/(console)/project-[region]-[project]/auth/teams/team-[team]/header.svelte @@ -18,12 +18,6 @@ title: 'Members', event: 'members', hasChildren: true - }, - { - href: `${path}/activity`, - title: 'Activity', - event: 'activity', - hasChildren: true } ]; diff --git a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.svelte b/src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.svelte deleted file mode 100644 index 0aa88a0c1..000000000 --- a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.ts b/src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.ts deleted file mode 100644 index 9106c57d2..000000000 --- a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/activity/+page.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Query } from '@appwrite.io/console'; -import { sdk } from '$lib/stores/sdk'; -import { getLimit, getPage, pageToOffset } from '$lib/helpers/load'; -import { PAGE_LIMIT } from '$lib/constants'; -import type { PageLoad } from './$types'; - -export const load: PageLoad = async ({ params, url, route }) => { - const page = getPage(url); - const limit = getLimit(url, route, PAGE_LIMIT); - const offset = pageToOffset(page, limit); - return { - offset, - limit, - logs: await sdk.forProject(params.region, params.project).users.listLogs({ - userId: params.user, - queries: [Query.limit(limit), Query.offset(offset)] - }) - }; -}; diff --git a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/header.svelte b/src/routes/(console)/project-[region]-[project]/auth/user-[user]/header.svelte index f11425ba9..b944378aa 100644 --- a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/header.svelte +++ b/src/routes/(console)/project-[region]-[project]/auth/user-[user]/header.svelte @@ -32,12 +32,6 @@ href: `${path}/sessions`, title: 'Sessions', event: 'sessions' - }, - { - href: `${path}/activity`, - title: 'Activity', - event: 'activity', - hasChildren: true } ]; diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/activity.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/activity.svelte deleted file mode 100644 index 041709ba4..000000000 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/activity.svelte +++ /dev/null @@ -1,74 +0,0 @@ - - -{#if loading} -
    - - -
    -{:else if recordActivityLogs} -
    - -
    -{/if} - - diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/index.ts b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/index.ts index 640842e60..5ad0a2729 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/index.ts +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/field/index.ts @@ -1,3 +1,2 @@ -export { default as RecordActivity } from './activity.svelte'; export { default as CsvDisabled } from './csvDisabled.svelte'; export { default as EditRecordPermissions } from './editPermissions.svelte'; diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/layouts/sheetOptions.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/layouts/sheetOptions.svelte index 35a926888..f6326b420 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/layouts/sheetOptions.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/(entity)/views/layouts/sheetOptions.svelte @@ -13,7 +13,6 @@ | 'update' | 'duplicate-row' | 'permissions' - | 'activity' | 'copy-url' | 'copy-json' // | 'copy-snippet' @@ -26,7 +25,6 @@ import { IconArrowLeft, IconArrowRight, - IconChartBar, IconClipboardCopy, IconDuplicate, IconKey, @@ -68,7 +66,6 @@ { label: 'Duplicate', icon: IconDuplicate, action: 'duplicate-row' }, { divider: true }, { label: 'Manage permissions', icon: IconKey, action: 'permissions' }, - { label: 'View activity', icon: IconChartBar, action: 'activity' }, { divider: true }, { label: 'Copy URL', icon: IconLink, action: 'copy-url' }, { label: 'Copy as JSON', icon: IconClipboardCopy, action: 'copy-json' }, diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/+layout.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/+layout.svelte index abae1c256..c3f081109 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/+layout.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/+layout.svelte @@ -42,7 +42,6 @@ import { sleep } from '$lib/helpers/promises'; import { hash } from '$lib/helpers/string'; import { - documentActivitySheet, documentPermissionSheet, noSqlDocument, showCreateIndexSheet @@ -50,7 +49,6 @@ import { SideSheet, EditRecordPermissions, - RecordActivity, useDatabaseSdk, DEFAULT_VECTOR_DIMENSION, type Field, @@ -139,15 +137,6 @@ disabled: page.url.pathname.endsWith('indexes'), group: 'collections' }, - { - label: 'Go to activity', - keys: ['g', 'c'], - callback() { - goto(withPath(basePath, '/activity')); - }, - disabled: page.url.pathname.endsWith('activity'), - group: 'collections' - }, { label: 'Go to usage', keys: ['g', 'u'], @@ -352,10 +341,6 @@ bind:record={$documentPermissionSheet.document} /> - - - - - import { Activity } from '$lib/layout'; - import type { PageData } from './$types'; - - const { - data - }: { - data: PageData; - } = $props(); - - -
    - -
    diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/activity/+page.ts b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/activity/+page.ts deleted file mode 100644 index 5a3883762..000000000 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/activity/+page.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { sdk } from '$lib/stores/sdk'; -import type { PageLoad } from './$types'; -import { PAGE_LIMIT } from '$lib/constants'; -import { Query } from '@appwrite.io/console'; -import { getLimit, getPage, pageToOffset } from '$lib/helpers/load'; - -export const load: PageLoad = async ({ params, url, route }) => { - const page = getPage(url); - const limit = getLimit(url, route, PAGE_LIMIT); - const offset = pageToOffset(page, limit); - - return { - offset, - limit, - logs: await sdk.forProject(params.region, params.project).tablesDB.listTableLogs({ - databaseId: params.database, - tableId: params.collection, - queries: [Query.limit(limit), Query.offset(offset)] - }) - }; -}; diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/header.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/header.svelte index bfeef0433..302f1131e 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/header.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/header.svelte @@ -27,12 +27,6 @@ title: 'Indexes', event: 'indexes' }, - { - href: `${path}/activity`, - title: 'Activity', - event: 'activity', - hasChildren: true - }, { href: `${path}/usage`, title: 'Usage', diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/spreadsheet.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/spreadsheet.svelte index 82bf056fc..dd695f859 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/spreadsheet.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/spreadsheet.svelte @@ -42,7 +42,6 @@ import { mockSuggestions } from '$database/(suggestions)'; import { collectionColumns, - documentActivitySheet, documentPermissionSheet, noSqlDocument, paginatedDocuments, @@ -431,11 +430,6 @@ selectedDocumentForDelete = document.$id; showDelete = true; } - - if (action === 'activity') { - $documentActivitySheet.show = true; - $documentActivitySheet.document = document; - } } // possibly for auto-save! diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/store.ts b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/store.ts index be4fcf1fb..0f48e9490 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/store.ts +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/store.ts @@ -95,11 +95,6 @@ export const documentPermissionSheet = writable({ document: null as Models.Document }); -export const documentActivitySheet = writable({ - show: false, - document: null as Models.Document -}); - export const showCreateIndexSheet = writable<{ show: boolean; column?: string; diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/+layout.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/+layout.svelte index 8c8043607..6bd8212f6 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/+layout.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/+layout.svelte @@ -29,7 +29,6 @@ databaseRowSheetOptions, showCreateColumnSheet, showCreateIndexSheet, - rowActivitySheet, databaseRelatedRowSheetOptions, rowPermissionSheet, showRowCreateSheet @@ -50,7 +49,6 @@ import { CreateIndex, EditRecordPermissions, - RecordActivity, SideSheet, type Field, useTerminology @@ -206,15 +204,6 @@ disabled: page.url.pathname.endsWith('indexes'), group: 'tables' }, - { - label: 'Go to activity', - keys: ['g', 'c'], - callback() { - goto(withPath(basePath, '/activity')); - }, - disabled: page.url.pathname.endsWith('activity'), - group: 'tables' - }, { label: 'Go to usage', keys: ['g', 'u'], @@ -593,10 +582,6 @@ bind:arePermsDisabled={editRowPermissionsDisabled} />
    - - - - diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.svelte deleted file mode 100644 index 849d38953..000000000 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.svelte +++ /dev/null @@ -1,14 +0,0 @@ - - -
    - -
    diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.ts b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.ts deleted file mode 100644 index fd816c1c0..000000000 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/activity/+page.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Query } from '@appwrite.io/console'; -import { sdk } from '$lib/stores/sdk'; -import { getLimit, getPage, pageToOffset } from '$lib/helpers/load'; -import { PAGE_LIMIT } from '$lib/constants'; -import type { PageLoad } from './$types'; - -export const load: PageLoad = async ({ params, url, route }) => { - const page = getPage(url); - const limit = getLimit(url, route, PAGE_LIMIT); - const offset = pageToOffset(page, limit); - - return { - offset, - limit, - logs: await sdk.forProject(params.region, params.project).tablesDB.listTableLogs({ - databaseId: params.database, - tableId: params.table, - queries: [Query.limit(limit), Query.offset(offset)] - }) - }; -}; diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/header.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/header.svelte index fd5d1e1f0..b408f6d22 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/header.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/header.svelte @@ -32,12 +32,6 @@ title: 'Indexes', event: 'indexes' }, - { - href: `${path}/activity`, - title: 'Activity', - event: 'activity', - hasChildren: true - }, { href: `${path}/usage`, title: 'Usage', diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/activity.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/activity.svelte deleted file mode 100644 index d7d37451f..000000000 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/activity.svelte +++ /dev/null @@ -1,68 +0,0 @@ - - -{#if loading} -
    - - -
    -{:else if rowActivityLogs} -
    - -
    -{/if} - - diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/sheetOptions.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/sheetOptions.svelte index ee0b793f7..c55ceae9b 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/sheetOptions.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/sheetOptions.svelte @@ -13,7 +13,6 @@ | 'update' | 'duplicate-row' | 'permissions' - | 'activity' | 'copy-url' | 'copy-json' // | 'copy-snippet' @@ -26,7 +25,6 @@ import { IconArrowLeft, IconArrowRight, - IconChartBar, IconClipboardCopy, IconDuplicate, IconKey, @@ -69,7 +67,6 @@ { label: 'Duplicate', icon: IconDuplicate, action: 'duplicate-row' }, { divider: true }, { label: 'Manage permissions', icon: IconKey, action: 'permissions' }, - { label: 'View activity', icon: IconChartBar, action: 'activity' }, { divider: true }, { label: 'Copy URL', icon: IconLink, action: 'copy-url' }, { label: 'Copy as JSON', icon: IconClipboardCopy, action: 'copy-json' }, diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/spreadsheet.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/spreadsheet.svelte index 4bdc4cd7b..918772822 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/spreadsheet.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/spreadsheet.svelte @@ -31,7 +31,6 @@ columnsWidth, showCreateIndexSheet, Deletion, - rowActivitySheet, paginatedRows, paginatedRowsLoading, databaseRelatedRowSheetOptions, @@ -678,11 +677,6 @@ showDelete = true; selectedRowForDelete = row.$id; } - - if (action === 'activity') { - $rowActivitySheet.row = row; - $rowActivitySheet.show = true; - } } } diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/store.ts b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/store.ts index 3928be3f5..26c9efdc2 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/store.ts +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/store.ts @@ -143,11 +143,6 @@ export enum Deletion { restrict = 'Row can not be deleted' } -export const rowActivitySheet = writable({ - show: false, - row: null as Models.Row -}); - export const rowPermissionSheet = writable({ show: false, row: null as Models.Row diff --git a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/+layout.svelte b/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/+layout.svelte index 015c066ee..e97e397f8 100644 --- a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/+layout.svelte +++ b/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/+layout.svelte @@ -20,18 +20,6 @@ group: 'topics', rank: 1 }, - { - label: 'Go to Activity', - callback() { - goto( - `${base}/project-${$project.region}-${$project.$id}/messaging/topics/topic-${topicId}/activity` - ); - }, - keys: ['g', 'a'], - disabled: page.url.pathname.endsWith('activity'), - group: 'topics', - rank: 1 - }, { label: 'Go to Overview', callback() { diff --git a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.svelte b/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.svelte deleted file mode 100644 index f805a79f0..000000000 --- a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.ts b/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.ts deleted file mode 100644 index f816a7a1a..000000000 --- a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/activity/+page.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Query } from '@appwrite.io/console'; -import { sdk } from '$lib/stores/sdk'; -import { getLimit, getPage, pageToOffset } from '$lib/helpers/load'; -import { PAGE_LIMIT } from '$lib/constants'; -import type { PageLoad } from './$types'; - -export const load: PageLoad = async ({ params, url, route }) => { - const page = getPage(url); - const limit = getLimit(url, route, PAGE_LIMIT); - const offset = pageToOffset(page, limit); - - return { - offset, - limit, - logs: await sdk.forProject(params.region, params.project).messaging.listTopicLogs({ - topicId: params.topic, - queries: [Query.limit(limit), Query.offset(offset)] - }) - }; -}; diff --git a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/header.svelte b/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/header.svelte index c0f0814f4..d7c925059 100644 --- a/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/header.svelte +++ b/src/routes/(console)/project-[region]-[project]/messaging/topics/topic-[topic]/header.svelte @@ -16,11 +16,6 @@ title: 'Subscribers', event: 'subscribers' }, - { - href: `${path}/activity`, - title: 'Activity', - event: 'activity' - }, { href: `${path}/settings`, title: 'Settings',