Merge remote-tracking branch 'origin/main' into feat/project-premium-geo-db-addon

# Conflicts:
#	bun.lock
#	package.json
This commit is contained in:
Damodar Lohani committed 2026-07-07 15:37:11 +05:45
commit e185cbd502
65 files changed
+3163 -1128

No files matched your search

-11
View File
@@ -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
}
];
}
-10
View File
@@ -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: () => {
@@ -32,7 +32,7 @@
const apexDomain = getApexDomain(selectedProxyRule.domain);
const domain = domainsList?.domains.find((d) => d.domain === apexDomain);
if (isCloud && domain) {
await sdk.forConsole.domains.updateNameservers({
await sdk.forConsole.domains.verifyNameservers({
domainId: domain.$id
});
}
@@ -2,27 +2,17 @@
import { Empty, Paginator } from '$lib/components';
import { Button } from '$lib/elements/forms';
import {
ActionMenu,
Accordion,
Badge,
InteractiveText,
Icon,
Layout,
Popover,
Skeleton,
Table,
Tooltip,
Button as PinkButton
Tooltip
} from '@appwrite.io/pink-svelte';
import {
IconDotsHorizontal,
IconCode,
IconUpload,
IconPlus,
IconTrash,
IconEyeOff,
IconPencil
} 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';
import SecretVariableModal from './secretVariableModal.svelte';
@@ -66,14 +56,14 @@
const tableColumns = $derived(
$isSmallViewport
? [
{ id: 'key', width: { min: 420 } },
{ id: 'value', width: { min: 240 } },
{ id: 'key', width: { min: 120, max: 300 } },
{ id: 'value', width: { min: 100, max: 200 } },
{ id: 'actions', width: 40 }
]
: [
{ 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 }
]
);
</script>
@@ -111,13 +101,15 @@
<Button
secondary
size="s"
icon={$isSmallViewport}
on:click={() => {
showCreate = true;
trackEvent(Click.VariablesCreateClick, {
source: createSource
});
}}>
<Icon slot="start" icon={IconPlus} /> Create variable
<Icon slot="start" icon={IconPlus} />
{#if !$isSmallViewport}Create variable{/if}
</Button>
{/if}
</Layout.Stack>
@@ -179,59 +171,20 @@
</Table.Cell>
<Table.Cell column="actions" {root}>
<div style="margin-inline-start: auto">
<Popover
padding="none"
placement="bottom-end"
let:toggle>
<PinkButton.Button
icon
variant="text"
size="s"
aria-label="More options"
onclick={(e) => {
e.preventDefault();
toggle(e);
}}>
<Icon icon={IconDotsHorizontal} size="s" />
</PinkButton.Button>
<svelte:fragment slot="tooltip" let:toggle>
<ActionMenu.Root>
{#if !variable?.secret}
<ActionMenu.Item.Button
leadingIcon={IconPencil}
onclick={(e) => {
toggle(e);
currentVariable = variable;
showUpdate = true;
}}>
Update
</ActionMenu.Item.Button>
{/if}
{#if !variable?.secret}
<ActionMenu.Item.Button
leadingIcon={IconEyeOff}
onclick={(e) => {
toggle(e);
currentVariable = variable;
showSecretModal = true;
}}>
Secret
</ActionMenu.Item.Button>
{/if}
<ActionMenu.Item.Button
status="danger"
leadingIcon={IconTrash}
onclick={(e) => {
toggle(e);
currentVariable = variable;
showDelete = true;
}}>
Delete
</ActionMenu.Item.Button>
</ActionMenu.Root>
</svelte:fragment>
</Popover>
<VariableActionMenu
{variable}
onUpdate={() => {
currentVariable = variable;
showUpdate = true;
}}
onSecret={() => {
currentVariable = variable;
showSecretModal = true;
}}
onDelete={() => {
currentVariable = variable;
showDelete = true;
}} />
</div>
</Table.Cell>
</Table.Row.Base>
@@ -23,10 +23,10 @@
function handleVariable() {
if (selectedVar) {
variables = variables.map((variable) => {
if (variable.$id === selectedVar.$id) {
return pair;
}
return variable;
const match = selectedVar.$id
? variable.$id === selectedVar.$id
: variable.key === selectedVar.key;
return match ? pair : variable;
});
} else {
variables = [...variables, pair];
@@ -0,0 +1,131 @@
<script lang="ts">
import { computePosition, flip, offset, shift, autoUpdate } from '@floating-ui/dom';
import { Icon, ActionMenu } from '@appwrite.io/pink-svelte';
import {
IconDotsHorizontal,
IconPencil,
IconEyeOff,
IconTrash
} from '@appwrite.io/pink-icons-svelte';
import { Button as PinkButton } from '@appwrite.io/pink-svelte';
import type { Models } from '@appwrite.io/console';
let {
variable,
onUpdate,
onSecret,
onDelete
}: {
variable: Partial<Models.Variable>;
onUpdate: () => void;
onSecret: () => void;
onDelete: () => void;
} = $props();
let open = $state(false);
let triggerEl = $state<HTMLElement | null>(null);
let menuEl = $state<HTMLElement | null>(null);
let cleanup: (() => void) | null = null;
function hide() {
open = false;
}
function toggle() {
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, () => {
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` });
}
});
});
} else {
cleanup?.();
cleanup = null;
}
});
function handleWindowClick(e: MouseEvent) {
if (!open) return;
const target = e.target as Node;
if (triggerEl?.contains(target) || menuEl?.contains(target)) return;
hide();
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') hide();
}
</script>
<svelte:window onclick={handleWindowClick} onkeydown={handleKeydown} />
<span bind:this={triggerEl}>
<PinkButton.Button
icon
variant="text"
size="s"
aria-label="More options"
onclick={(e) => {
e.preventDefault();
toggle();
}}>
<Icon icon={IconDotsHorizontal} size="s" />
</PinkButton.Button>
</span>
{#if open}
<div
use:portalToBody
bind:this={menuEl}
style="position: fixed; z-index: 9001; background: var(--bgcolor-neutral-primary); border: var(--border-width-s) solid var(--border-neutral); border-radius: var(--border-radius-m); box-shadow: 0 1px 3px 0 rgba(0,0,0,0.03), 0 4px 4px 0 rgba(0,0,0,0.04); overflow: hidden;"
role="menu">
<ActionMenu.Root>
{#if !variable?.secret}
<ActionMenu.Item.Button
leadingIcon={IconPencil}
on:click={() => {
hide();
onUpdate();
}}>
Update
</ActionMenu.Item.Button>
{/if}
{#if !variable?.secret}
<ActionMenu.Item.Button
leadingIcon={IconEyeOff}
on:click={() => {
hide();
onSecret();
}}>
Secret
</ActionMenu.Item.Button>
{/if}
<ActionMenu.Item.Button
status="danger"
leadingIcon={IconTrash}
on:click={() => {
hide();
onDelete();
}}>
Delete
</ActionMenu.Item.Button>
</ActionMenu.Root>
</div>
{/if}
+6 -2
View File
@@ -10,7 +10,7 @@
export let required = false;
export let disabled = false;
export let autofocus = false;
export let autocomplete = false;
export let autocomplete: boolean | string = false;
export let minlength = 8;
export let maxlength: number = null;
export let leadingIcon: ComponentType | undefined = undefined;
@@ -47,7 +47,11 @@
{leadingIcon}
state={error ? 'error' : 'default'}
autofocus={autofocus || undefined}
autocomplete={autocomplete ? 'on' : 'off'}
autocomplete={typeof autocomplete === 'string'
? (autocomplete as unknown as 'on')
: autocomplete
? 'on'
: 'off'}
helper={helper || error}
on:invalid={handleInvalid}
bind:value>
@@ -0,0 +1,272 @@
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 console OAuth2
* consent screen (contract v2).
*
* 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": ["<projectId>", …] | ["*"] }
* { "type": "organization", "identifiers": ["<teamId>", …] | ["*"] }
*
* `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.
*/
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';
export interface AuthorizationDetail {
type: string;
identifiers?: string[];
[key: string]: unknown;
}
/** 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 [];
}
}
/** Distinct, non-empty identifiers for a single entry. */
export function identifiersOf(detail: AuthorizationDetail): string[] {
if (!Array.isArray(detail.identifiers)) return [];
const seen = new Set<string>();
const out: string[] = [];
for (const identifier of detail.identifiers) {
if (typeof identifier === 'string' && identifier !== '' && !seen.has(identifier)) {
seen.add(identifier);
out.push(identifier);
}
}
return out;
}
/**
* 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 function mergeIdentifiers(details: AuthorizationDetail[], type: string): string[] {
const seen = new Set<string>();
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 out;
}
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 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(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);
}
/* -------------------------------------------------------------------------- */
/* Resource name resolution — turn identifiers into display names */
/* -------------------------------------------------------------------------- */
export interface ResolvedResource {
id: string;
/** Display name, or the raw id when it couldn't be resolved. */
name: string;
region?: string;
/** True when a real name was found; false means we fell back to the id. */
resolved: boolean;
}
export type ResourceNameMap = Map<string, ResolvedResource>;
function idOnlyMap(ids: string[]): ResourceNameMap {
const map: ResourceNameMap = new Map();
for (const id of ids) {
map.set(id, { id, name: id, resolved: false });
}
return map;
}
/**
* 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<ResourceNameMap> {
const map = idOnlyMap(ids);
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;
}
/**
* Best-effort resolution of organization ids to their names. The user's
* organization list already carries names, so a single list call covers it.
* Never throws: on any failure the caller still gets an id-only map.
*/
export async function resolveOrganizationNames(ids: string[]): Promise<ResourceNameMap> {
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<ResolvedResource[]> {
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<string>();
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<ResolvedResource[]> {
try {
const orgs = await getTeamOrOrganizationList([Query.limit(100)]);
return orgs.teams.map((org) => ({ id: org.$id, name: org.name, resolved: true }));
} catch {
return [];
}
}
+209
View File
@@ -0,0 +1,209 @@
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 !== '');
return configured.length > 0 ? configured : DEFAULT_MCP_RESOURCE_URLS;
}
/** 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<string, ResourceSelection>;
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;
// 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);
};
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.
// 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 (!readOnly && 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];
+14
View File
@@ -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;
}
}
+608 -120
View File
@@ -1,12 +1,41 @@
import type { ComponentType } from 'svelte';
import {
IconShieldCheck,
IconIdentification,
IconUser,
IconMail,
IconIdentification,
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:<scope>` — project-tier permissions
* - `organization:all` / `organization:<scope>` — 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;
@@ -14,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<string, Omit<ScopeDescriptor, 'id'>> = {
openid: {
title: 'Verify your identity',
@@ -36,13 +61,18 @@ const BUILTIN_SCOPES: Record<string, Omit<ScopeDescriptor, 'id'>> = {
},
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
},
[ALL_SCOPE]: {
title: 'Full access to your account',
description: 'Manage all your organizations, projects, and their resources on your behalf.',
icon: IconShieldCheck
}
};
@@ -65,128 +95,586 @@ 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 {
/** `<tier>: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 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. */
export interface ConsentScopeModel {
/** OIDC identity scopes, read-only, always granted. */
identity: ScopeDescriptor[];
/** Every other granular scope, bucketed by resource for collapsing. */
groups: ScopeResourceGroup[];
/** Total count of granular scopes across all groups. */
granularCount: number;
/** Console-wide `all` full access, read-only, subsumes everything else. */
all: ScopeDescriptor | null;
project: TierScopes;
organization: TierScopes;
}
/**
* 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.
*/
function splitScope(scope: string): { resource: string; action: string } {
const lastDot = scope.lastIndexOf('.');
if (lastDot <= 0) {
return { resource: scope, action: '' };
function collectTier(scopes: string[], prefix: string, allScope: string): TierScopes {
const seen = new Set<string>();
const out: string[] = [];
let all = false;
for (const scope of scopes) {
if (scope === allScope) {
all = true;
continue;
}
if (!scope.startsWith(prefix)) continue;
const bare = scope.slice(prefix.length);
if (bare === '' || seen.has(bare)) continue;
seen.add(bare);
out.push(bare);
}
return { resource: scope.slice(0, lastDot), action: scope.slice(lastDot + 1) };
return { all, scopes: out };
}
/**
* 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.
* 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.
*/
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<string, ResourceCopy> = {
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."
},
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."
},
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.'
},
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.'
},
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.'
},
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.'
},
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<string, ResourceCopy> = {
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.'
},
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.'
}
};
/**
* 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<string, ResourceCopy>
): { 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;
}
/** 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);
}
/** 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,
allScope: string,
copyMap: Record<string, ResourceCopy>
): 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<string, string[]>();
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<string, ScopeResourceGroup>();
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;
}
/* -------------------------------------------------------------------------- */
/* 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<string, string[]>();
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
* 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 groups = [...byResource.values()];
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 });
}
// 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 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
});
}
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;
}
-128
View File
@@ -1,128 +0,0 @@
<script lang="ts">
import { AvatarInitials, PaginationWithLimit, Trim } from '$lib/components';
import { Container } from '$lib/layout';
import DualTimeView from '$lib/components/dualTimeView.svelte';
import type { Models } from '@appwrite.io/console';
import { Layout, Table, Card, Empty, InteractiveText } from '@appwrite.io/pink-svelte';
import Button from '$lib/elements/forms/button.svelte';
import type { PinkColumn } from '$lib/helpers/types';
export let limit = 0;
export let offset = 0;
export let logs: Models.LogList;
export let insideSideSheet = false;
export let databasesScreen = false;
export let useCreateLinkForPagination = true;
function getColumnWidth(columnId: string): Pick<PinkColumn, 'width'> {
const widthConfig: Record<
string,
{ insideSheet: number | { min: number }; default: number | { min: number } }
> = {
user: { insideSheet: 140, default: { min: 100 } },
event: { insideSheet: 125, default: { min: 160 } },
location: { insideSheet: 100, default: { min: 120 } },
ip: { insideSheet: { min: 150 }, default: { min: 250 } },
date: { insideSheet: { min: 200 }, default: { min: 180 } }
};
const config = widthConfig[columnId];
if (!config) {
return {};
}
return { width: insideSideSheet ? config.insideSheet : config.default };
}
const columns: PinkColumn[] = [
{ id: 'user', ...getColumnWidth('user') },
{ id: 'event', ...getColumnWidth('event') },
{ id: 'location', ...getColumnWidth('location') },
{ id: 'ip', ...getColumnWidth('ip') },
{ id: 'date', ...getColumnWidth('date') }
];
</script>
<Container
{databasesScreen}
{insideSideSheet}
expanded={databasesScreen && !insideSideSheet}
slotSpacing={databasesScreen && !insideSideSheet}>
{#if logs.total}
<Table.Root class="responsive-table" {columns} let:root>
<svelte:fragment slot="header" let:root>
<Table.Header.Cell column="user" {root}>User</Table.Header.Cell>
<Table.Header.Cell column="event" {root}>Event</Table.Header.Cell>
<Table.Header.Cell column="location" {root}>Location</Table.Header.Cell>
<Table.Header.Cell column="ip" {root}>IP</Table.Header.Cell>
<Table.Header.Cell column="date" {root}>Date</Table.Header.Cell>
</svelte:fragment>
{#each logs.logs as log}
<Table.Row.Base {root}>
<Table.Cell column="user" {root}>
<Layout.Stack direction="row" alignItems="center">
{#if log.userEmail}
{#if log.userName}
<AvatarInitials size="xs" name={log.userName} />
<Trim>{log.userName}</Trim>
{:else}
<AvatarInitials size="xs" name={log.userEmail} />
<Trim>{log.userEmail}</Trim>
{/if}
{:else}
<div class="avatar is-size-small">
<span class="icon-anonymous" aria-hidden="true"></span>
</div>
<span class="text u-trim">{log.userName ?? 'Anonymous'}</span>
{/if}
</Layout.Stack>
</Table.Cell>
<Table.Cell column="event" {root}>
{log.event}
</Table.Cell>
<Table.Cell column="location" {root}>
{#if log.countryCode !== '--'}
{log.countryName}
{:else}
Unknown
{/if}
</Table.Cell>
<Table.Cell column="ip" {root}>
<InteractiveText variant="copy" text={log.ip} isVisible />
</Table.Cell>
<Table.Cell column="date" {root}>
<DualTimeView time={log.time} showDatetime />
</Table.Cell>
</Table.Row.Base>
{/each}
</Table.Root>
<PaginationWithLimit
{limit}
{offset}
on:page
name="Logs"
total={logs.total}
useCreateLink={useCreateLinkForPagination} />
{:else}
<Card.Base padding="none">
<Empty
title="No activities available"
description="Need a hand? Learn more in our documentation."
type="secondary">
<svelte:fragment slot="actions">
<Button
external
secondary
href="https://appwrite.io/docs/products/databases/databases">
Documentation
</Button>
</svelte:fragment>
</Empty>
</Card.Base>
{/if}
</Container>
+2 -2
View File
@@ -10,10 +10,10 @@
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
$organization?.billingPlanDetails?.name
} plan`;
export let disabled: boolean;
-1
View File
@@ -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';
@@ -1,8 +0,0 @@
<script lang="ts">
import { Activity } from '$lib/layout';
import type { PageData } from './$types';
export let data: PageData;
</script>
<Activity {...data} />
@@ -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)]
})
};
};
@@ -27,12 +27,6 @@
title: 'Applications',
event: 'applications'
},
{
href: `${path}/activity`,
title: 'Activity',
event: 'activity',
hasChildren: true
},
{
href: `${path}/organizations`,
title: 'Organizations',
@@ -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);
@@ -34,7 +34,7 @@
async function verifyStatus() {
try {
domain = await sdk.forConsole.domains.updateNameservers({ domainId: domain.$id });
domain = await sdk.forConsole.domains.verifyNameservers({ domainId: domain.$id });
verified = domain.nameservers.toLowerCase() === 'appwrite';
if (verified) {
addNotification({
@@ -29,7 +29,7 @@
async function retryDomain() {
try {
error = null;
const domain = await sdk.forConsole.domains.updateNameservers({
const domain = await sdk.forConsole.domains.verifyNameservers({
domainId: selectedDomain.$id
});
@@ -10,6 +10,7 @@
import PasswordStrengthPolicy from './passwordStrengthPolicy.svelte';
import SessionSecurity from './sessionSecurity.svelte';
import UpdateSignupEmailSecurity from './updateSignupEmailSecurity.svelte';
import { isCloud } from '$lib/system';
let { data }: PageProps = $props();
</script>
@@ -24,12 +25,14 @@
dictionaryPolicy={data.passwordDictionaryPolicy}
historyPolicy={data.passwordHistoryPolicy}
personalDataPolicy={data.passwordPersonalDataPolicy} />
<UpdateSignupEmailSecurity
project={data.project}
denyAliasedEmailPolicy={data.denyAliasedEmailPolicy}
denyDisposableEmailPolicy={data.denyDisposableEmailPolicy}
denyFreeEmailPolicy={data.denyFreeEmailPolicy}
denyCorporateEmailPolicy={data.denyCorporateEmailPolicy} />
{#if isCloud}
<UpdateSignupEmailSecurity
project={data.project}
denyAliasedEmailPolicy={data.denyAliasedEmailPolicy}
denyDisposableEmailPolicy={data.denyDisposableEmailPolicy}
denyFreeEmailPolicy={data.denyFreeEmailPolicy}
denyCorporateEmailPolicy={data.denyCorporateEmailPolicy} />
{/if}
<SessionSecurity
project={data.project}
sessionAlertPolicy={data.sessionAlertPolicy}
@@ -1,8 +0,0 @@
<script lang="ts">
import type { PageData } from './$types';
import { Activity } from '$lib/layout';
export let data: PageData;
</script>
<Activity {...data} />
@@ -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)]
})
};
};
@@ -18,12 +18,6 @@
title: 'Members',
event: 'members',
hasChildren: true
},
{
href: `${path}/activity`,
title: 'Activity',
event: 'activity',
hasChildren: true
}
];
</script>
@@ -1,8 +0,0 @@
<script lang="ts">
import type { PageData } from './$types';
import { Activity } from '$lib/layout';
export let data: PageData;
</script>
<Activity logs={data.logs} offset={data.offset} limit={data.limit} />
@@ -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)]
})
};
};
@@ -32,12 +32,6 @@
href: `${path}/sessions`,
title: 'Sessions',
event: 'sessions'
},
{
href: `${path}/activity`,
title: 'Activity',
event: 'activity',
hasChildren: true
}
];
</script>
@@ -81,6 +81,7 @@
label={`${i === 0 ? 'Value' : ''}`}
placeholder="Enter value"
bind:value={pair.value}
autocomplete="new-password"
minlength={0} />
<PinkButton.Button
icon
@@ -1,74 +0,0 @@
<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/state';
import { sdk } from '$lib/stores/sdk';
import { Activity } from '$lib/layout';
import { pageToOffset } from '$lib/helpers/load';
import { Skeleton } from '@appwrite.io/pink-svelte';
import { type Models, Query } from '@appwrite.io/console';
import { type Record, toSupportiveRecord } from '$database/(entity)';
const {
record
}: {
record: Record;
} = $props();
let limit = 25; /* default */
let offset = $state(0);
let loading = $state(true);
let recordActivityLogs = $state<Models.LogList | null>(null);
onMount(loadRecordLogs);
async function loadRecordLogs(event?: CustomEvent<number>) {
loading = true;
if (event) {
offset = pageToOffset(event.detail, limit);
}
const { $databaseId: databaseId, entityId, $id: recordId } = toSupportiveRecord(record);
recordActivityLogs = await sdk
.forProject(page.params.region, page.params.project)
.tablesDB.listRowLogs({
databaseId: databaseId,
tableId: entityId,
rowId: recordId,
queries: [Query.limit(limit), Query.offset(offset)]
});
loading = false;
}
</script>
{#if loading}
<div style:margin-block="" style:margin-inline-end="2.25rem">
<!--<Skeleton variant="line" height={25} width="25%" />-->
<Skeleton variant="line" height={40} width="auto" />
</div>
{:else if recordActivityLogs}
<div class="record-activity-wrapper">
<Activity
{limit}
{offset}
insideSideSheet
on:page={loadRecordLogs}
logs={recordActivityLogs}
useCreateLinkForPagination={false} />
</div>
{/if}
<style lang="scss">
.record-activity-wrapper {
& :global(.console-container) {
margin-inline: unset;
padding-inline-end: unset;
@media (max-width: 768px) {
margin-block: 0.5rem;
}
}
}
</style>
@@ -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';
@@ -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' },
@@ -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} />
</SideSheet>
<SideSheet title="Document activity" bind:show={$documentActivitySheet.show} closeOnBlur>
<RecordActivity record={$documentActivitySheet.document} />
</SideSheet>
<SideSheet
closeOnBlur
title="Create index"
@@ -1,14 +0,0 @@
<script lang="ts">
import { Activity } from '$lib/layout';
import type { PageData } from './$types';
const {
data
}: {
data: PageData;
} = $props();
</script>
<div class="wide-screen-wrapper databases-spreadsheet">
<Activity {...data} databasesScreen />
</div>
@@ -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)]
})
};
};
@@ -27,12 +27,6 @@
title: 'Indexes',
event: 'indexes'
},
{
href: `${path}/activity`,
title: 'Activity',
event: 'activity',
hasChildren: true
},
{
href: `${path}/usage`,
title: 'Usage',
@@ -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!
@@ -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;
@@ -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} />
</SideSheet>
<SideSheet title="Row activity" bind:show={$rowActivitySheet.show} closeOnBlur>
<RecordActivity record={$rowActivitySheet.row} />
</SideSheet>
<Dialog title="Generate sample data" bind:open={$randomDataModalState.show}>
<Layout.Stack style="gap: 28px;">
<Typography.Text>
@@ -1,14 +0,0 @@
<script lang="ts">
import { Activity } from '$lib/layout';
import type { PageData } from './$types';
const {
data
}: {
data: PageData;
} = $props();
</script>
<div class="wide-screen-wrapper databases-spreadsheet">
<Activity {...data} databasesScreen />
</div>
@@ -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)]
})
};
};
@@ -32,12 +32,6 @@
title: 'Indexes',
event: 'indexes'
},
{
href: `${path}/activity`,
title: 'Activity',
event: 'activity',
hasChildren: true
},
{
href: `${path}/usage`,
title: 'Usage',
@@ -1,68 +0,0 @@
<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/state';
import { sdk } from '$lib/stores/sdk';
import { Activity } from '$lib/layout';
import { rowActivitySheet } from '../store';
import { pageToOffset } from '$lib/helpers/load';
import { type Models, Query } from '@appwrite.io/console';
import { Skeleton } from '@appwrite.io/pink-svelte';
let limit = 25; /* default */
let offset = $state(0);
let loading = $state(true);
let rowActivityLogs = $state<Models.LogList | null>(null);
onMount(loadRowLogs);
async function loadRowLogs(event?: CustomEvent<number>) {
loading = true;
if (event) {
offset = pageToOffset(event.detail, limit);
}
const row = $rowActivitySheet.row;
rowActivityLogs = await sdk
.forProject(page.params.region, page.params.project)
.tablesDB.listRowLogs({
databaseId: row.$databaseId,
tableId: row.$tableId,
rowId: row.$id,
queries: [Query.limit(limit), Query.offset(offset)]
});
loading = false;
}
</script>
{#if loading}
<div style:margin-block="" style:margin-inline-end="2.25rem">
<!--<Skeleton variant="line" height={25} width="25%" />-->
<Skeleton variant="line" height={40} width="auto" />
</div>
{:else if rowActivityLogs}
<div class="row-activity-wrapper">
<Activity
{limit}
{offset}
insideSideSheet
on:page={loadRowLogs}
logs={rowActivityLogs}
useCreateLinkForPagination={false} />
</div>
{/if}
<style lang="scss">
.row-activity-wrapper {
& :global(.console-container) {
margin-inline: unset;
padding-inline-end: unset;
@media (max-width: 768px) {
margin-block: 0.5rem;
}
}
}
</style>
@@ -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' },
@@ -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;
}
}
}
@@ -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
@@ -62,7 +62,7 @@
const domain = data.domainsList.domains.find((d) => d.domain === apexDomain);
if (isCloud && domain) {
await sdk.forConsole.domains.updateNameservers({
await sdk.forConsole.domains.verifyNameservers({
domainId: domain.$id
});
}
@@ -57,7 +57,7 @@
const apexDomain = getApexDomain(selectedProxyRule.domain);
const domain = domainsList?.domains.find((d) => d.domain === apexDomain);
if (isCloud && domain) {
await sdk.forConsole.domains.updateNameservers({
await sdk.forConsole.domains.verifyNameservers({
domainId: domain.$id
});
}
@@ -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() {
@@ -1,8 +0,0 @@
<script lang="ts">
import type { PageData } from './$types';
import { Activity } from '$lib/layout';
export let data: PageData;
</script>
<Activity {...data} />
@@ -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)]
})
};
};
@@ -16,11 +16,6 @@
title: 'Subscribers',
event: 'subscribers'
},
{
href: `${path}/activity`,
title: 'Activity',
event: 'activity'
},
{
href: `${path}/settings`,
title: 'Settings',
@@ -61,7 +61,7 @@
const apexDomain = getApexDomain(proxyRule.domain);
const domain = data.domainsList.domains.find((d) => d.domain === apexDomain);
if (isCloud && domain) {
await sdk.forConsole.domains.updateNameservers({
await sdk.forConsole.domains.verifyNameservers({
domainId: domain.$id
});
}
@@ -57,7 +57,7 @@
const apexDomain = getApexDomain(selectedProxyRule.domain);
const domain = domainsList?.domains.find((d) => d.domain === apexDomain);
if (isCloud && domain) {
await sdk.forConsole.domains.updateNameservers({
await sdk.forConsole.domains.verifyNameservers({
domainId: domain.$id
});
}
@@ -61,7 +61,7 @@
const apexDomain = getApexDomain(proxyRule.domain);
const domain = data.domainsList.domains.find((d) => d.domain === apexDomain);
if (isCloud && domain) {
await sdk.forConsole.domains.updateNameservers({
await sdk.forConsole.domains.verifyNameservers({
domainId: domain.$id
});
}
@@ -57,7 +57,7 @@
const apexDomain = getApexDomain(selectedProxyRule.domain);
const domain = domainsList?.domains.find((d) => d.domain === apexDomain);
if (isCloud && domain) {
await sdk.forConsole.domains.updateNameservers({
await sdk.forConsole.domains.verifyNameservers({
domainId: domain.$id
});
}
@@ -525,7 +525,7 @@
{/if}
</Table.Cell>
<Table.Cell column="actions" {root}>
<Popover placement="bottom-end" let:toggle padding="none">
<Popover placement="bottom-end" let:toggle padding="none" portal>
<Button
text
icon
@@ -72,6 +72,7 @@
label="Value"
placeholder="Enter value"
bind:value={pair.value}
autocomplete="new-password"
minlength={0} />
<Selector.Checkbox
id="secret"
File diff suppressed because it is too large. Load diff
@@ -7,15 +7,18 @@
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 { isWebRedirect } from '$lib/helpers/oauth2-redirect';
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<Phase>('loading');
let grant = $state<Models.Oauth2Grant | null>(null);
let app = $state<Models.App | null>(null);
let account = $state<Models.User<Models.Preferences> | null>(null);
let error = $state<string | null>(null);
let completedRedirectUrl = $state<string | undefined>(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 +28,11 @@
return Number.isInteger(value) && value >= 0 ? value : undefined;
}
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 +46,7 @@
let cancelled = false;
phase = 'loading';
error = null;
completedRedirectUrl = undefined;
const currentRelativeUrl = () => window.location.pathname + window.location.search;
@@ -124,6 +133,15 @@
if (result.redirectUrl) {
// Already consented — go straight back to the client.
window.location.href = result.redirectUrl;
if (!isWebRedirect(result.redirectUrl)) {
completedRedirectUrl = result.redirectUrl;
account = loggedInAccount;
app = await sdk.forConsole.apps
.get({ appId: clientId })
.catch(() => null);
if (cancelled) return;
phase = 'approved';
}
return;
}
if (result.grantId) {
@@ -184,7 +202,15 @@
{grant}
{app}
accountLabel={account?.email || account?.name || undefined}
flow="authorization" />
flow="authorization"
{onDone} />
{:else if phase === 'approved' || phase === 'denied'}
<OAuth2OutcomeCard
outcome={phase}
flow="authorization"
{app}
accountLabel={account?.email || account?.name || undefined}
redirectUrl={completedRedirectUrl} />
{/if}
</div>
</div>
+11 -53
View File
@@ -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';
}
</script>
@@ -209,32 +206,13 @@
{app}
accountLabel={account?.email || account?.name || undefined}
flow={DEVICE_FLOW}
{onDeviceDone} />
{:else if phase === 'approved'}
<Card.Base padding="l" radius="l" style="width: 100%;">
<Layout.Stack gap="l" alignItems="center" alignContent="center">
<div class="success-icon-wrap">
<Icon icon={IconCheckCircle} size="l" color="--fgcolor-success" />
</div>
<Typography.Title size="m" align="center">Device connected</Typography.Title>
<Typography.Text variant="m-400" align="center">
You've authorized {app?.name ?? 'the application'}. You can return to your
device — it will continue automatically.
</Typography.Text>
</Layout.Stack>
</Card.Base>
{:else if phase === 'denied'}
<Card.Base padding="l" radius="l" style="width: 100%;">
<Layout.Stack gap="l" alignItems="center" alignContent="center">
<div class="denied-icon-wrap">
<Icon icon={IconXCircle} size="l" color="--fgcolor-neutral-secondary" />
</div>
<Typography.Title size="m" align="center">Request cancelled</Typography.Title>
<Typography.Text variant="m-400" align="center">
No access was granted. You can close this page.
</Typography.Text>
</Layout.Stack>
</Card.Base>
{onDone} />
{:else if phase === 'approved' || phase === 'denied'}
<OAuth2OutcomeCard
outcome={phase}
flow={DEVICE_FLOW}
{app}
accountLabel={account?.email || account?.name || undefined} />
{/if}
</div>
</div>
@@ -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;
}
@@ -0,0 +1,274 @@
<script lang="ts">
import type { Models } from '@appwrite.io/console';
import { Card, Typography, Icon } from '@appwrite.io/pink-svelte';
import { IconCheck, IconX, IconLockClosed } from '@appwrite.io/pink-icons-svelte';
import { Button } from '$lib/elements/forms';
import type { OAuth2Flow, OAuth2Outcome } from './consent-card.svelte';
interface Props {
outcome: OAuth2Outcome;
flow: OAuth2Flow;
app?: Models.App | null;
accountLabel?: string;
/**
* Present when the client redirect is a native deep link (cursor://…).
* The browser already attempted it once; the button retries it for users
* who dismissed the OS "open application" prompt.
*/
redirectUrl?: string;
}
let {
outcome,
flow,
app = null,
accountLabel = undefined,
redirectUrl = undefined
}: Props = $props();
const approved = $derived(outcome === 'approved');
const appName = $derived(app?.name ?? 'the application');
const appInitial = $derived((app?.name || '?').charAt(0).toUpperCase());
const accountInitial = $derived((accountLabel || '?').charAt(0).toUpperCase());
const title = $derived(
approved ? (flow === 'device' ? 'Device connected' : 'Access granted') : 'Request cancelled'
);
const message = $derived.by(() => {
if (!approved) {
return `No access was granted to ${appName}. You can close this tab.`;
}
if (flow === 'device') {
return `You've authorized ${appName}. Return to your device — it will continue automatically.`;
}
if (redirectUrl) {
return `Return to ${appName} to continue. If it didn't open automatically, use the button below.`;
}
return `Return to ${appName} to continue. You can close this tab.`;
});
</script>
<Card.Base padding="none" radius="l" style="width: 100%; overflow: hidden;">
<div class="outcome" class:approved>
<header class="header">
<div class="identity">
{#if app?.logoUri}
<img src={app.logoUri} alt={appName} class="avatar" />
{:else}
<div class="avatar placeholder">{appInitial}</div>
{/if}
{#if accountLabel}
<span class="connector">
<span class="connector-line"></span>
<span class="connector-node">
<Icon icon={approved ? IconCheck : IconX} size="s" />
</span>
<span class="connector-line"></span>
</span>
<div class="avatar account">{accountInitial}</div>
{:else}
<span class="status-badge" class:approved>
<Icon icon={approved ? IconCheck : IconX} size="s" />
</span>
{/if}
</div>
<div class="headline">
<Typography.Title size="m" align="center">{title}</Typography.Title>
<Typography.Text variant="m-400" align="center" color="--fgcolor-neutral-secondary">
{message}
</Typography.Text>
</div>
</header>
<div class="body">
{#if approved && redirectUrl}
<Button fullWidth on:click={() => (window.location.href = redirectUrl)}>
Open {app?.name ?? 'application'}
</Button>
<p class="close-hint">It's safe to close this tab.</p>
{/if}
<p class="footnote">
<Icon icon={IconLockClosed} size="s" />
{#if approved}
<span>You can revoke access anytime in your account settings</span>
{:else}
<span>{appName} was not given access to your account</span>
{/if}
</p>
</div>
</div>
</Card.Base>
<style lang="scss">
.outcome {
display: flex;
flex-direction: column;
}
.header {
display: flex;
flex-direction: column;
align-items: center;
gap: 1.25rem;
padding: 2.5rem 1.75rem 0.5rem;
background: radial-gradient(
120% 100% at 50% 0%,
var(--bgcolor-neutral-secondary) 0%,
transparent 70%
);
}
/* Same identity row as the consent card, now resolved: the dashed "pending"
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;
border-radius: var(--border-radius-l, 0.85rem);
object-fit: cover;
flex-shrink: 0;
border: 1px solid var(--border-neutral-strong);
background: var(--bgcolor-neutral-primary);
}
.avatar.placeholder {
display: flex;
align-items: center;
justify-content: center;
background: var(--bgcolor-neutral-secondary);
color: var(--fgcolor-neutral-secondary);
font-size: 1.25rem;
font-weight: 600;
}
.avatar.account {
width: 3rem;
height: 3rem;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
background: var(--bgcolor-neutral-invert);
color: var(--fgcolor-neutral-on-invert, var(--bgcolor-neutral-primary));
font-size: 1.1rem;
font-weight: 600;
}
.connector {
display: flex;
align-items: center;
margin-inline: 0.35rem;
}
.connector-line {
width: 1.1rem;
height: 0;
border-top: 2px dashed var(--border-neutral-strong);
}
.connector-node {
display: flex;
align-items: center;
justify-content: center;
width: 1.75rem;
height: 1.75rem;
border-radius: 50%;
border: 1px solid var(--border-neutral);
background: var(--bgcolor-neutral-primary);
color: var(--fgcolor-neutral-secondary);
}
.approved .connector-line {
border-top-style: solid;
border-top-color: var(--border-success, rgba(16, 185, 129, 0.45));
}
.approved .connector-node {
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);
animation: node-pop 0.35s cubic-bezier(0.2, 0.9, 0.3, 1.4) both;
}
@keyframes node-pop {
from {
transform: scale(0.5);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.approved .connector-node {
animation: none;
}
}
.headline {
display: flex;
flex-direction: column;
gap: 0.35rem;
max-width: 22rem;
}
.body {
display: flex;
flex-direction: column;
gap: 0.85rem;
padding: 1.25rem 1.75rem 1.75rem;
}
.close-hint {
margin: 0;
text-align: center;
font-size: 0.78rem;
color: var(--fgcolor-neutral-tertiary);
}
.footnote {
margin: 0.25rem 0 0;
display: flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
font-size: 0.78rem;
color: var(--fgcolor-neutral-tertiary);
text-align: center;
}
</style>
@@ -0,0 +1,452 @@
<script lang="ts">
import { Badge, Icon, Spinner } from '@appwrite.io/pink-svelte';
import {
IconPlus,
IconPencil,
IconCheck,
IconExclamationCircle
} from '@appwrite.io/pink-icons-svelte';
import { InputSearch } from '$lib/elements/forms';
import {
WILDCARD_IDENTIFIER,
type ResolvedResource,
type ResourceNameMap
} from '$lib/helpers/oauth2-authorization-details';
interface Props {
/** Plural label, e.g. `projects`. */
pluralLabel: string;
/** Identifiers the client requested (may be `['*']`). Defines the universe. */
requested: string[];
/** Current selection (`['*']` = all). Two-way bound to the parent. */
selected: string[];
/** Live search over the selectable universe. */
find: (term: string) => Promise<ResolvedResource[]>;
/** Resolve specific requested ids to display names. */
resolveNames: (ids: string[]) => Promise<ResourceNameMap>;
disabled?: boolean;
}
let {
pluralLabel,
requested,
selected = $bindable(),
find,
resolveNames,
disabled = false
}: Props = $props();
const wildcard = $derived(requested.includes(WILDCARD_IDENTIFIER));
const isAll = $derived(selected.includes(WILDCARD_IDENTIFIER));
const specificIds = $derived(selected.filter((id) => id !== WILDCARD_IDENTIFIER));
// Nothing selected — the tier grants nothing until the user picks a resource.
const isEmpty = $derived(!isAll && specificIds.length === 0);
// Whether the current selection still matches exactly what was requested.
const isDefault = $derived(
selected.length === requested.length && selected.every((id) => requested.includes(id))
);
// Search (which can *add* resources) is only offered when narrowing a
// wildcard grant — every match is still within the requested `*`, so it stays
// downscope-only. A specific requested list is fixed: the user can remove
// from it but never add resources the client didn't ask for.
const searchable = $derived(wildcard && !isAll);
let expanded = $state(false);
let names = $state<Record<string, ResolvedResource>>({});
let term = $state('');
let results = $state<ResolvedResource[]>([]);
let searching = $state(false);
function labelFor(id: string): ResolvedResource {
return names[id] ?? { id, name: id, resolved: false };
}
// Resolve the requested specific ids so chips show real names.
$effect(() => {
const ids = requested.filter((id) => id !== WILDCARD_IDENTIFIER);
if (ids.length === 0) return;
let cancelled = false;
void resolveNames(ids).then((map) => {
if (!cancelled) names = { ...names, ...Object.fromEntries(map) };
});
return () => {
cancelled = true;
};
});
// Debounced live search while the picker is open and searchable.
$effect(() => {
if (!expanded || !searchable) return;
const t = term;
let cancelled = false;
searching = true;
const timer = setTimeout(() => {
void find(t).then((res) => {
if (cancelled) return;
results = res;
const merged = { ...names };
for (const r of res) merged[r.id] = r;
names = merged;
searching = false;
});
}, 250);
return () => {
cancelled = true;
clearTimeout(timer);
};
});
const suggestions = $derived(results.filter((r) => !selected.includes(r.id)));
function setAll(all: boolean) {
selected = all ? [WILDCARD_IDENTIFIER] : [];
}
function add(id: string) {
if (selected.includes(id)) return;
selected = [...selected.filter((x) => x !== WILDCARD_IDENTIFIER), id];
}
function remove(id: string) {
selected = selected.filter((x) => x !== id);
}
const summary = $derived.by(() => {
if (isAll) return `All ${pluralLabel}`;
if (specificIds.length === 0) return `No ${pluralLabel} selected`;
if (specificIds.length <= 2) return specificIds.map((id) => labelFor(id).name).join(', ');
return `${specificIds.length} ${pluralLabel}`;
});
</script>
<div class="selector">
<div class="summary-row">
<span class="summary" class:empty={isEmpty}>
{#if isEmpty}
<Icon icon={IconExclamationCircle} size="s" />
{/if}
<span class="summary-text">{summary}</span>
{#if isDefault}
<span class="default-tag">Default</span>
{/if}
</span>
<button
type="button"
class="toggle"
class:active={expanded}
{disabled}
onclick={() => (expanded = !expanded)}>
<Icon icon={expanded ? IconCheck : IconPencil} size="s" />
{expanded ? 'Done' : 'Change'}
</button>
</div>
{#if expanded}
<div class="body">
{#if wildcard}
<div class="mode" role="group">
<button
type="button"
class="seg"
class:active={isAll}
{disabled}
onclick={() => setAll(true)}>All {pluralLabel}</button>
<button
type="button"
class="seg"
class:active={!isAll}
{disabled}
onclick={() => setAll(false)}>Specific {pluralLabel}</button>
</div>
{/if}
{#if specificIds.length > 0}
<div class="chips">
{#each specificIds as id (id)}
{@const r = labelFor(id)}
<span class="chip">
<span class="chip-name" class:mono={!r.resolved}>{r.name}</span>
{#if r.region}
<Badge size="xs" variant="secondary" content={r.region} />
{/if}
<button
type="button"
class="chip-remove"
aria-label={`Remove ${r.name}`}
{disabled}
onclick={() => remove(id)}>×</button>
</span>
{/each}
</div>
{/if}
{#if searchable}
<InputSearch
bind:value={term}
placeholder={`Search ${pluralLabel} by name`}
{disabled} />
<ul class="results">
{#if searching}
<li class="results-state"><Spinner size="s" /></li>
{:else if suggestions.length === 0}
<li class="results-state">
{term.trim()
? `No matching ${pluralLabel}`
: `Type to search ${pluralLabel}`}
</li>
{:else}
{#each suggestions as r (r.id)}
<li>
<button
type="button"
class="result"
{disabled}
onclick={() => add(r.id)}>
<span class="result-text">
<span class="result-name">{r.name}</span>
{#if r.region}
<Badge
size="xs"
variant="secondary"
content={r.region} />
{/if}
</span>
<Icon icon={IconPlus} size="s" />
</button>
</li>
{/each}
{/if}
</ul>
{/if}
</div>
{/if}
</div>
<style lang="scss">
.selector {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.summary-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
}
.summary {
display: inline-flex;
align-items: center;
gap: 0.4rem;
min-width: 0;
font-size: 0.875rem;
font-weight: 500;
color: var(--fgcolor-neutral-primary);
}
.summary.empty {
color: var(--fgcolor-warning);
}
.summary-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.default-tag {
flex-shrink: 0;
padding: 0.05rem 0.4rem;
border: 1px solid var(--border-neutral);
border-radius: var(--border-radius-xs, 0.3rem);
font-size: 0.68rem;
font-weight: 500;
color: var(--fgcolor-neutral-tertiary);
}
.toggle {
display: inline-flex;
align-items: center;
gap: 0.35rem;
flex-shrink: 0;
padding: 0.3rem 0.7rem;
border: 1px solid var(--border-neutral);
border-radius: var(--border-radius-s, 0.5rem);
background: var(--bgcolor-neutral-primary);
color: var(--fgcolor-neutral-primary);
font-size: 0.8rem;
font-weight: 500;
cursor: pointer;
transition:
background 0.15s ease,
border-color 0.15s ease;
}
.toggle:hover:not(:disabled) {
background: var(--overlay-neutral-hover, var(--bgcolor-neutral-secondary));
border-color: var(--border-neutral-strong);
}
.toggle.active {
border-color: var(--border-neutral-strong);
color: var(--fgcolor-success, var(--fgcolor-neutral-primary));
}
.toggle:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.body {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding-top: 0.85rem;
margin-top: 0.1rem;
border-top: 1px solid var(--border-neutral);
}
.mode {
display: inline-flex;
gap: 0.25rem;
padding: 0.2rem;
border: 1px solid var(--border-neutral);
border-radius: 0.6rem;
background: var(--bgcolor-neutral-default);
align-self: flex-start;
}
.seg {
border: none;
background: transparent;
border-radius: 0.45rem;
padding: 0.35rem 0.75rem;
font-size: 0.82rem;
color: var(--fgcolor-neutral-secondary);
cursor: pointer;
}
.seg:hover:not(:disabled):not(.active) {
color: var(--fgcolor-neutral-primary);
}
.seg.active {
background: var(--bgcolor-neutral-invert);
color: var(--fgcolor-neutral-on-invert, var(--bgcolor-neutral-primary));
}
.seg:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.chip {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.2rem 0.3rem 0.2rem 0.55rem;
border: 1px solid var(--border-neutral-strong);
border-radius: 2rem;
font-size: 0.8rem;
max-width: 100%;
}
.chip-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fgcolor-neutral-primary);
}
.chip-name.mono {
font-family: var(--font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: 0.74rem;
color: var(--fgcolor-neutral-secondary);
}
.chip-remove {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.1rem;
height: 1.1rem;
border: none;
border-radius: 50%;
background: transparent;
color: var(--fgcolor-neutral-tertiary);
font-size: 1rem;
line-height: 1;
cursor: pointer;
}
.chip-remove:hover:not(:disabled) {
background: var(--bgcolor-neutral-secondary);
color: var(--fgcolor-neutral-primary);
}
.results {
list-style: none;
margin: 0;
padding: 0;
border: 1px solid var(--border-neutral);
border-radius: var(--border-radius-s, 0.5rem);
max-height: 12rem;
overflow-y: auto;
background: var(--bgcolor-neutral-primary);
}
.results-state {
display: flex;
align-items: center;
justify-content: center;
padding: 0.75rem;
font-size: 0.8rem;
color: var(--fgcolor-neutral-tertiary);
}
.result {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
width: 100%;
padding: 0.55rem 0.7rem;
border: none;
background: transparent;
color: var(--fgcolor-neutral-primary);
cursor: pointer;
text-align: left;
}
.result:hover:not(:disabled) {
background: var(--overlay-neutral-hover, var(--bgcolor-neutral-secondary));
}
.result-text {
display: inline-flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
}
.result-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 0.85rem;
}
li:not(.results-state) + li .result {
border-top: 1px solid var(--border-neutral);
}
</style>