The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): authorize native profile creation with a dedicated grant
unsupportedpastels4ef87f4c4cd4
diff --git a/apps/desktop/electron/local-gateway-python.test.ts b/apps/desktop/electron/local-gateway-python.test.tsindex 1d50120f501..667665a0e74 100644--- a/apps/desktop/electron/local-gateway-python.test.ts+++ b/apps/desktop/electron/local-gateway-python.test.ts@@ -36,7 +36,7 @@ test.skipIf(process.platform === 'win32')('Python ticket bridge pins profile, owawait fs.writeFile(path.join(cwd, 'hermes_cli', 'gateway_client.py'), 'def _session_ticket(*args, **kwargs):\n return "untrusted-project-ticket"\n')try {- for (const purpose of ['interactive', 'native-http'] as const) {+ for (const purpose of ['interactive', 'native-http', 'native-profile-create'] as const) {await expect(mintGatewayTicketWithPython(backend, cwd, endpoint, purpose)).resolves.toBe('private-grant')// Only the interactive (shared-primary) socket asks for host scope; native-http stays profile-bound.expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose, ...(purpose === 'interactive' ? { scope: 'host' } : {}) })diff --git a/apps/desktop/electron/local-gateway-python.ts b/apps/desktop/electron/local-gateway-python.tsindex e4ac3d3f748..b2f53797cea 100644--- a/apps/desktop/electron/local-gateway-python.ts+++ b/apps/desktop/electron/local-gateway-python.ts@@ -77,7 +77,7 @@ class TicketBridge {this.child.on('close', () => this.dispose())}- request(endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http'): Promise<string> {+ request(endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create'): Promise<string> {clearTimeout(this.idleTimer)return new Promise((resolve, reject) => {@@ -238,7 +238,7 @@ export function createGatewayTicketResolver(resolveBackend: () => Promise<Resolvlet cached: Promise<{ command: string; env?: NodeJS.ProcessEnv }> | undefinedlet cachedGeneration = -1- return async (endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http'): Promise<string> => {+ return async (endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create'): Promise<string> => {const generation = bridgeGenerationif (!cached || cachedGeneration !== generation) {@@ -264,7 +264,7 @@ export function mintGatewayTicketWithPython(backend: { command: string; env?: NodeJS.ProcessEnv },cwd: string,endpoint: TicketEndpoint,- purpose: 'interactive' | 'native-http'+ purpose: 'interactive' | 'native-http' | 'native-profile-create'): Promise<string> {const env = { ...process.env, ...backend.env, HERMES_HOME: endpoint.profile_id,PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' }diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.tsindex c6f679de1ef..e8998cb8092 100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@ -91,6 +91,17 @@ test.skipIf(process.platform === 'win32').each([0o700, 0o750, 0o701])('native HTconst { mintLocalGatewayTicket } = await import('./local-gateway')await mintLocalGatewayTicket(endpoint)expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose: 'interactive', scope: 'host' })++ for (const [route, method, purpose] of [+ ['/api/profiles', 'POST', 'native-profile-create'],+ ['/api/profiles?unused=1', 'post', 'native-profile-create'],+ ['/api/profiles', 'GET', 'native-http'],+ ['/api/profiles/import', 'POST', 'native-http'],+ ['/api/config', 'POST', 'native-http']+ ]) {+ await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + route, home, method)+ expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose })+ }} finally {await new Promise<void>(resolve => server.close(() => resolve()))await fs.rm(home, { recursive: true, force: true })diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.tsindex 1f5b19fc59a..0236677874a 100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@ -333,23 +333,26 @@ export function routedGatewayEndpoint(endpoint: GatewayEndpoint, urlOrProfile: sreturn { ...endpoint, profile_id: home, control_home: endpoint.control_home || endpoint.profile_id }}-export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string, launchHome = descriptor.gatewayEndpoint.profile_id) {+export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string, launchHome = descriptor.gatewayEndpoint.profile_id, method = 'GET') {if (new URL(url).origin !== descriptor.gatewayEndpoint.api_origin || descriptor.baseUrl !== descriptor.gatewayEndpoint.api_origin) {throw new Error('Native gateway HTTP origin mismatch')}- return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(routedGatewayEndpoint(descriptor.gatewayEndpoint, url, launchHome), 'native-http') }+ const purpose = method.toUpperCase() === 'POST' && new URL(url).pathname.replace(/\/$/, '') === '/api/profiles'+ ? 'native-profile-create' : 'native-http'++ return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(routedGatewayEndpoint(descriptor.gatewayEndpoint, url, launchHome), purpose) }}// The installed runtime's own ticket client: every Windows mint (SID-validated pipe), and a POSIX// home whose group-write only Python can prove private.-let pythonTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http') => Promise<string>) | undefined+let pythonTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create') => Promise<string>) | undefinedexport function configurePythonGatewayTicketClient(client: NonNullable<typeof pythonTicketClient>) {pythonTicketClient = client}-async function mintGroupWritableHome(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http', homes: string[]) {+async function mintGroupWritableHome(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create', homes: string[]) {if (!pythonTicketClient) {throw new Error(`Unsafe gateway control path: profile home is group-writable and this Desktop cannot verify the group is private: run chmod g-w ${homes.map(shellQuote).join(' ')}`)}try {@@ -391,11 +394,11 @@ async function resolveControlSocket(home: string): Promise<string> {/** The Desktop's interactive socket is the one shared-primary route: its renderer selects every* served sibling with a `profile` param, so it asks for a host-scoped grant explicitly. Every* other ticket (and every other client's) stays bound to the one profile it names. */-export function ticketScope(purpose: 'interactive' | 'native-http'): { scope?: 'host' } {+export function ticketScope(purpose: 'interactive' | 'native-http' | 'native-profile-create'): { scope?: 'host' } {return purpose === 'interactive' ? { scope: 'host' } : {}}-export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' = 'interactive'): Promise<string> {+export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create' = 'interactive'): Promise<string> {if (process.platform === 'win32') {if (!pythonTicketClient) {throw new Error('Gateway ticket client is not configured')}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex e035825834b..8f12c6a2aac 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -5378,7 +5378,7 @@ function fetchJson(url, token, options: any = {}) {async (requestState: any) => {// Mint inside each retry: a grant authorizes exactly one HTTP request.const nativeHeaders = options.gatewayDescriptor- ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url, HERMES_HOME)+ ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url, HERMES_HOME, options.method || 'GET'): nullreturn new Promise((resolve, reject) => {diff --git a/apps/desktop/src/api/profiles.ts b/apps/desktop/src/api/profiles.tsindex 84788f31d3b..c1600e5c009 100644--- a/apps/desktop/src/api/profiles.ts+++ b/apps/desktop/src/api/profiles.ts@@ -16,8 +16,8 @@ export function getProfiles(scope?: ProfileScope): Promise<ProfilesResponse> {})}-export function createProfile(body: ProfileCreatePayload): Promise<{ name: string; ok: boolean; path: string }> {- return hermesApi<{ name: string; ok: boolean; path: string }>({+export function createProfile(body: ProfileCreatePayload): Promise<{ name: string; ok: boolean; path: string; soul_set?: boolean }> {+ return hermesApi<{ name: string; ok: boolean; path: string; soul_set?: boolean }>({path: '/api/profiles',method: 'POST',bodydiff --git a/apps/desktop/src/app/profiles/create-profile-dialog.test.tsx b/apps/desktop/src/app/profiles/create-profile-dialog.test.tsxnew file mode 100644index 00000000000..1587e91e573--- /dev/null+++ b/apps/desktop/src/app/profiles/create-profile-dialog.test.tsx@@ -0,0 +1,36 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'++import { CreateProfileDialog } from './create-profile-dialog'++const api = vi.hoisted(() => ({ createProfile: vi.fn(async () => ({})), updateProfileSoul: vi.fn(async () => ({})) }))+vi.mock('@/hermes', () => api)+afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++it.each([true, false])(+ 'creates the initial persona, retaining the older-backend fallback (soul_set=%s)',+ async applied => {+ api.createProfile.mockResolvedValueOnce({ soul_set: applied })+ const created = vi.fn()+ render(<CreateProfileDialog onClose={vi.fn()} onCreated={created} open />)+ fireEvent.change(screen.getByPlaceholderText('my-profile'), { target: { value: 'new-persona' } })+ fireEvent.change(screen.getByRole('textbox', { name: /SOUL.md/ }), { target: { value: 'A new persona' } })+ fireEvent.click(screen.getByRole('button', { name: 'Create profile' }))+ await waitFor(() => expect(created).toHaveBeenCalledWith('new-persona'))+ expect(api.createProfile).toHaveBeenCalledWith({+ name: 'new-persona',+ clone_from: 'default',+ soul: 'A new persona'+ })++ if (applied) {+ expect(api.updateProfileSoul).not.toHaveBeenCalled()+ } else {+ expect(api.updateProfileSoul).toHaveBeenCalledWith('new-persona', 'A new persona', 'new-persona')+ }+ }+)diff --git a/apps/desktop/src/app/profiles/create-profile-dialog.tsx b/apps/desktop/src/app/profiles/create-profile-dialog.tsxindex 67fbc96f38b..b2197aa2199 100644--- a/apps/desktop/src/app/profiles/create-profile-dialog.tsx+++ b/apps/desktop/src/app/profiles/create-profile-dialog.tsx@@ -77,10 +77,11 @@ export function CreateProfileDialog({setError(null)try {- await createProfile({ name: trimmed, clone_from: cloneFrom })+ const result = await createProfile({ name: trimmed, clone_from: cloneFrom, ...(soul.trim() ? { soul } : {}) })- if (soul.trim()) {- await updateProfileSoul(trimmed, soul)+ // Older remote backends do not accept an initial persona in the create request.+ if (soul.trim() && !result.soul_set) {+ await updateProfileSoul(trimmed, soul, trimmed)}await onCreated?.(trimmed)diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex c8d49127f5b..dd05b4e4721 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -1115,6 +1115,7 @@ export interface AutomationBlueprint {}export interface ProfileCreatePayload {+ soul?: stringclone_all?: booleanclone_from?: null | stringclone_from_default?: booleandiff --git a/gateway/runtime_bootstrap.py b/gateway/runtime_bootstrap.pyindex b9499f0dadc..61a882df37b 100644--- a/gateway/runtime_bootstrap.py+++ b/gateway/runtime_bootstrap.py@@ -10,6 +10,8 @@ _PURPOSE_CAPABILITIES = {'interactive': frozenset({'session:create', 'session:read', 'session:submit','session:control', 'session:approve', 'session:respond'}),'native-http': frozenset({'http:owner'}),+ # Same-user host operation, not permission to read or mutate another profile.+ 'native-profile-create': frozenset({'profiles:create'}),'exposure': frozenset({'transport:delegate'}),'worker-adoption': frozenset({'worker:adopt'}),}diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.pyindex 2c481c4aef9..eec9fc130c3 100644--- a/hermes_cli/dashboard_auth/native_http.py+++ b/hermes_cli/dashboard_auth/native_http.py@@ -103,6 +103,23 @@ async def _check_profile_scope(request, profile_id):raise PermissionError('profile_scope_mismatch')+def _redeem_http_ticket(store, ticket, request):+ try:+ grant = store.redeem(ticket, profile_id=None, purpose='native-http')+ expected = frozenset({'http:owner'})+ except PermissionError:+ # Only this host-management operation accepts the dedicated same-user grant.+ # Wrong-purpose redemption does not consume a ticket; ordinary profile grants+ # still reach _check_profile_scope and remain unable to create other profiles.+ if request.method != 'POST' or request.url.path.rstrip('/') != '/api/profiles':+ raise+ grant = store.redeem(ticket, profile_id=None, purpose='native-profile-create')+ expected = frozenset({'profiles:create'})+ if grant['capabilities'] != expected:+ raise PermissionError('invalid native grant')+ return grant++async def authenticate_native_http(request):"""Return a rejection or stamp a one-request principal; absent header is inert."""tickets = request.headers.getlist(HEADER)@@ -126,15 +143,14 @@ async def authenticate_native_http(request):return JSONResponse({'detail': 'Unauthorized'}, status_code=401)try:# The ticket names the served profile it was minted for; that home's authority owns it.- grant = store.redeem(tickets[0], profile_id=None, purpose='native-http')- if grant['capabilities'] != frozenset({'http:owner'}):- raise PermissionError('invalid native grant')+ grant = _redeem_http_ticket(store, tickets[0], request)if authority_for_profile_id(runner, grant['profile_id']) is None:raise PermissionError('unserved native grant')except PermissionError:return JSONResponse({'detail': 'Unauthorized'}, status_code=401)try:- await _check_profile_scope(request, grant['profile_id'])+ if grant['purpose'] != 'native-profile-create':+ await _check_profile_scope(request, grant['profile_id'])except PermissionError:return JSONResponse({'detail': 'profile_scope_mismatch'}, status_code=403)request.state.native_http_principal = grantdiff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.pyindex 5ff824867ad..65d0c37e004 100644--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@ -1400,7 +1400,7 @@ def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path],def create_profile(name: str, clone_from: Optional[str] = None, clone_all: bool = False, clone_config: bool = False,no_alias: bool = False, no_skills: bool = False, description: Optional[str] = None,- clone_channels: bool = False, sync_imports: bool = False,+ clone_channels: bool = False, sync_imports: bool = False, soul: Optional[str] = None,) -> Path:"""Create a new profile directory and return its path.@@ -1470,7 +1470,8 @@ def create_profile(stripped = strip_channel_settings(staging, include_state=clone_all, source_dir=source_dir)if stripped:logger.info("profile %s: cloned without messaging channels %s", canon, stripped)- _finish_profile_layout(staging, no_skills=no_skills, clone_all=clone_all, description=description)+ from hermes_cli.profiles_initialization import finish_profile_layout+ finish_profile_layout(staging, no_skills=no_skills, clone_all=clone_all, description=description, soul=soul)os.rename(staging, profile_dir)except BaseException:shutil.rmtree(staging, ignore_errors=True)@@ -1498,41 +1499,6 @@ def _clone_staging_dir(profile_dir: Path) -> Path:return staging-def _finish_profile_layout(profile_dir: Path, *, no_skills: bool, clone_all: bool,- description: Optional[str]) -> None:- """Seed files a fresh profile owns from day one; runs on the staging tree before publish."""- # Seed an empty .env so the profile owns a credentials file from day one. Without it,- # profile-scoped env writes (dashboard Channels/Keys pages, `hermes -p <name> auth add`)- # had no file until first write and the profile silently inherited shell API keys —- # read by users as "the new profile reads the root .env". Skipped when a clone copied one.- _seed_file_if_missing(profile_dir / ".env", _PLACEHOLDER_ENV, 0o600)-- # Default SOUL.md to customize immediately (skipped when a clone already provided one).- with contextlib.suppress(Exception): # best-effort — don't fail profile creation over this- from hermes_cli.default_soul import DEFAULT_SOUL_MD- _seed_file_if_missing(profile_dir / "SOUL.md", DEFAULT_SOUL_MD)-- # Opt-out marker read by seed_profile_skills() and `hermes update`'s all-profile sync- # (the feature still works via the empty skills/ dir if this fails).- if no_skills:- _seed_file_if_missing(- profile_dir / NO_BUNDLED_SKILLS_MARKER,- "This profile opted out of bundled-skill seeding (`hermes profile create --no-skills`).\n"- "Delete this file to re-enable sync on the next `hermes update`.\n",- )-- # Migrate config-only clones now so desktop/status don't warn that a just-created- # profile is v0/outdated; --clone-all snapshots stay byte-for-byte apart from the- # explicit runtime/history stripping above.- if not clone_all:- _migrate_profile_config_if_outdated(profile_dir)-- # Description last, so a partial-create failure doesn't strand a description file.- if description and description.strip():- with contextlib.suppress(Exception): # non-fatal — `hermes profile describe` works later- write_profile_meta(profile_dir, description=description.strip(), description_auto=False)--def _notify_multiplexer(canon: str) -> None:from hermes_cli.gateway_multiplex_served import notify_multiplexer_profiles_changednotify_multiplexer_profiles_changed(canon)diff --git a/hermes_cli/profiles_initialization.py b/hermes_cli/profiles_initialization.pynew file mode 100644index 00000000000..8dbe1052649--- /dev/null+++ b/hermes_cli/profiles_initialization.py@@ -0,0 +1,46 @@+"""Initial profile files, written on the staging tree before publication."""+import contextlib+from pathlib import Path+from typing import Optional+++def finish_profile_layout(profile_dir: Path, *, no_skills: bool, clone_all: bool,+ description: Optional[str], soul: Optional[str] = None) -> None:+ """Seed files a fresh profile owns from day one; runs on the staging tree before publish."""+ from hermes_cli.profiles import (+ _seed_file_if_missing, _PLACEHOLDER_ENV, NO_BUNDLED_SKILLS_MARKER,+ _migrate_profile_config_if_outdated, write_profile_meta,+ )+ if soul is not None:+ (profile_dir / "SOUL.md").write_text(soul, encoding="utf-8")++ # Seed an empty .env so the profile owns a credentials file from day one. Without it,+ # profile-scoped env writes (dashboard Channels/Keys pages, `hermes -p <name> auth add`)+ # had no file until first write and the profile silently inherited shell API keys —+ # read by users as "the new profile reads the root .env". Skipped when a clone copied one.+ _seed_file_if_missing(profile_dir / ".env", _PLACEHOLDER_ENV, 0o600)++ # Default SOUL.md to customize immediately (skipped when a clone already provided one).+ with contextlib.suppress(Exception): # best-effort — don't fail profile creation over this+ from hermes_cli.default_soul import DEFAULT_SOUL_MD+ _seed_file_if_missing(profile_dir / "SOUL.md", DEFAULT_SOUL_MD)++ # Opt-out marker read by seed_profile_skills() and `hermes update`'s all-profile sync+ # (the feature still works via the empty skills/ dir if this fails).+ if no_skills:+ _seed_file_if_missing(+ profile_dir / NO_BUNDLED_SKILLS_MARKER,+ "This profile opted out of bundled-skill seeding (`hermes profile create --no-skills`).\n"+ "Delete this file to re-enable sync on the next `hermes update`.\n",+ )++ # Migrate config-only clones now so desktop/status don't warn that a just-created+ # profile is v0/outdated; --clone-all snapshots stay byte-for-byte apart from the+ # explicit runtime/history stripping above.+ if not clone_all:+ _migrate_profile_config_if_outdated(profile_dir)++ # Description last, so a partial-create failure doesn't strand a description file.+ if description and description.strip():+ with contextlib.suppress(Exception): # non-fatal — `hermes profile describe` works later+ write_profile_meta(profile_dir, description=description.strip(), description_auto=False)diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.pyindex 3ea61f15216..b96151b370f 100644--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@ -438,6 +438,7 @@ class SkillsUpdateRequest(BaseModel):class ProfileCreate(BaseModel):name: str+ soul: Optional[str] = Noneclone_from: Optional[str] = Noneclone_from_default: bool = False # legacy clients; new ones send clone_from explicitlyclone_all: bool = Falsediff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.pyindex f5390d07421..783ec2376fc 100644--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@ -804,7 +804,7 @@ async def create_profile_endpoint(body: ProfileCreate):path = profiles_mod.create_profile(name=body.name, clone_from=clone_from, clone_all=body.clone_all,clone_config=clone_config, no_skills=body.no_skills, description=body.description,- clone_channels=body.clone_channels)+ clone_channels=body.clone_channels, **({"soul": body.soul} if body.soul is not None else {}))# Match the CLI flow: fresh named profiles get the bundled skills (cloning already# copied the source's; no_skills wrote the opt-out marker so seeding no-ops) and a# ~/.local/bin wrapper when the alias is safe.@@ -855,7 +855,7 @@ async def create_profile_endpoint(body: ProfileCreate):return {"ok": True, "name": body.name, "path": str(path), "model_set": model_set, "model_error": model_error,"mcp_written": mcp_written, "skills_disabled": skills_disabled,- "hub_installs": hub_installs}+ "hub_installs": hub_installs, "soul_set": body.soul is not None}@router.get("/api/profiles/active")diff --git a/tests/gateway/test_native_profile_create.py b/tests/gateway/test_native_profile_create.pynew file mode 100644index 00000000000..3b182799d2e--- /dev/null+++ b/tests/gateway/test_native_profile_create.py@@ -0,0 +1,40 @@+"""A dedicated same-user grant creates profiles without widening profile HTTP grants."""+import asyncio++import httpx+import pytest++from tests.gateway.test_native_http_auth import daemon, headers, reject_ws, ticket++[email protected]('linux')+def test_native_profile_create_grant_is_route_bound_and_single_use(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(+ base_url=descriptor['api_origin'], trust_env=False, timeout=20) as client:+ body = {'name': 'gui-created', 'clone_from': 'default', 'soul': 'A GUI-created persona'}+ assert client.post('/api/profiles', json=body,+ headers=headers(ticket(home, descriptor))).status_code == 403+ assert not (home / 'profiles' / 'gui-created').exists()+ assert client.get('/api/config?profile=other',+ headers=headers(ticket(home, descriptor))).status_code == 403+ grant = ticket(home, descriptor, 'native-profile-create')+ for method, path in [('GET', '/api/config'), ('GET', '/api/profiles'),+ ('POST', '/api/profiles/import'), ('PATCH', '/api/profiles/other'),+ ('DELETE', '/api/profiles/other')]:+ response = client.request(method, path, json=body, headers=headers(grant))+ assert response.status_code == 401, (method, path, response.text)+ asyncio.run(reject_ws(descriptor['api_origin'], grant))+ for origin in ('', 'https://evil.example'):+ response = client.post('/api/profiles', json=body, headers={**headers(grant), 'Origin': origin})+ assert response.status_code == 401+ created = client.post('/api/profiles', json=body, headers=headers(grant))+ assert created.status_code == 200, created.text+ assert created.json()['name'] == 'gui-created'+ assert (home / 'profiles' / 'gui-created' / 'config.yaml').is_file()+ assert (home / 'profiles' / 'gui-created' / 'SOUL.md').read_text() == body['soul']+ assert created.json()['soul_set'] is True+ listed = client.get('/api/profiles', headers=headers(ticket(home, descriptor)))+ assert 'gui-created' in {p['name'] for p in listed.json()['profiles']}+ assert client.post('/api/profiles', json={**body, 'name': 'replay'},+ headers=headers(grant)).status_code == 401+ assert not (home / 'profiles' / 'replay').exists()diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex 44a2b3a3df6..013f338954d 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -271,6 +271,19 @@ profile creation/import/activation, and profile rename/delete are not granted bythis primary-profile credential. Native clients must not rewrite `all` to `current`or borrow the primary grant to hide a cross-profile failure.+Creating a profile from native Desktop uses a separate, same-user+`purpose: "native-profile-create"` grant carrying only `profiles:create`. It is+accepted exclusively by `POST /api/profiles`; it does not authorize profile reads,+import, activation, rename, deletion, or WebSocket access. The existing create+handler validates the name and clone options. Optional `soul` content is written+inside the staged profile before publication, so creation does not need a follow-up+write or a running new-profile gateway; `soul_set` confirms it was applied. Older+remote backends retain the separate, explicitly profile-scoped SOUL update.+Desktop mints this grant per create+request, never sends it to the renderer, and still uses ordinary profile-bound+grants for subsequent requests. The same expiry, one-use, daemon, socket-peer and+Origin checks apply. Ordinary `native-http` grants still receive 403 on creation.+The native HTTP integration is covered by real ordinary-daemon/control-socket/TCPprobes in `tests/gateway/test_native_http_auth.py`, alongside gated OAuth/cookie andactual non-loopback-peer controls. This does not establish native Desktop UI parity