Skip to content

Commit 8933b58

Browse files
authored
feat: add site rename endpoint (#261)
* feat(sites): add rename endpoint * fix(sites): document rename 404 and cover invalid json * fix(sites): register rename route in the policy manifest * fix(sites): reject control characters in site names
1 parent 64fd9ad commit 8933b58

7 files changed

Lines changed: 271 additions & 4 deletions

File tree

‎src/app/api/v2/sites/[siteId]/route.ts‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import { createPrincipalApiHandler } from 'server/lib/createApiHandler';
1919
import type { Principal } from 'server/lib/principal';
2020
import { sitesSuccessResponse as successResponse } from 'server/lib/sites/routeHelpers';
2121
import { readSiteRevision, sitesErrorResponse } from 'server/lib/sites/routeHelpers';
22-
import SitesService from 'server/services/sites';
22+
import SitesService, { SitesServiceError } from 'server/services/sites';
2323

2424
type RouteContext = {
2525
params: Promise<{
@@ -57,6 +57,63 @@ type RouteContext = {
5757
* application/json:
5858
* schema:
5959
* $ref: '#/components/schemas/ApiErrorResponse'
60+
* patch:
61+
* summary: Rename a hosted static site
62+
* security:
63+
* - BearerAuth: []
64+
* - LifecycleApiKey: []
65+
* description: Changes the display name only; the Site ID and content URL stay the same.
66+
* tags:
67+
* - Sites
68+
* operationId: renameSite
69+
* parameters:
70+
* - in: path
71+
* name: siteId
72+
* required: true
73+
* schema:
74+
* type: string
75+
* requestBody:
76+
* required: true
77+
* content:
78+
* application/json:
79+
* schema:
80+
* type: object
81+
* additionalProperties: false
82+
* properties:
83+
* name: { type: string, minLength: 1, maxLength: 255 }
84+
* expectedAccessRevision: { type: integer, minimum: 1, maximum: 2147483647 }
85+
* required: [name]
86+
* responses:
87+
* '200':
88+
* description: Hosted static site renamed.
89+
* content:
90+
* application/json:
91+
* schema:
92+
* $ref: '#/components/schemas/SiteSuccessResponse'
93+
* '400':
94+
* description: Invalid JSON, name, or revision.
95+
* content:
96+
* application/json:
97+
* schema:
98+
* $ref: '#/components/schemas/ApiErrorResponse'
99+
* '403':
100+
* description: Only the site owner can rename it.
101+
* content:
102+
* application/json:
103+
* schema:
104+
* $ref: '#/components/schemas/ApiErrorResponse'
105+
* '404':
106+
* description: Site not found or sites hosting is disabled.
107+
* content:
108+
* application/json:
109+
* schema:
110+
* $ref: '#/components/schemas/ApiErrorResponse'
111+
* '409':
112+
* description: Access revision changed; refetch before retrying.
113+
* content:
114+
* application/json:
115+
* schema:
116+
* $ref: '#/components/schemas/ApiErrorResponse'
60117
* delete:
61118
* summary: Delete a hosted static site
62119
* security:
@@ -100,6 +157,37 @@ const getHandler = async (req: NextRequest, principal: Principal, { params }: Ro
100157
}
101158
};
102159

160+
const patchHandler = async (req: NextRequest, principal: Principal, { params }: RouteContext) => {
161+
const routeParams = await params;
162+
try {
163+
let body: unknown;
164+
try {
165+
body = await req.json();
166+
} catch {
167+
throw new SitesServiceError('Invalid JSON.', 400);
168+
}
169+
if (
170+
!body ||
171+
typeof body !== 'object' ||
172+
Array.isArray(body) ||
173+
Object.keys(body).some((key) => !['name', 'expectedAccessRevision'].includes(key))
174+
) {
175+
throw new SitesServiceError('Invalid rename request.', 400);
176+
}
177+
const input = body as Record<string, unknown>;
178+
if (typeof input.name !== 'string') throw new SitesServiceError('name is required.', 400);
179+
const site = await new SitesService().renameSite(
180+
routeParams.siteId,
181+
input.name,
182+
principal,
183+
readSiteRevision(input.expectedAccessRevision)
184+
);
185+
return successResponse({ site }, { status: 200 }, req);
186+
} catch (error) {
187+
return sitesErrorResponse(error, req);
188+
}
189+
};
190+
103191
const deleteHandler = async (req: NextRequest, principal: Principal, { params }: RouteContext) => {
104192
const routeParams = await params;
105193
try {
@@ -116,4 +204,5 @@ const deleteHandler = async (req: NextRequest, principal: Principal, { params }:
116204
};
117205

118206
export const GET = createPrincipalApiHandler({ scope: 'sites:read' }, getHandler);
207+
export const PATCH = createPrincipalApiHandler({ scope: 'sites:write' }, patchHandler);
119208
export const DELETE = createPrincipalApiHandler({ scope: 'sites:write' }, deleteHandler);

‎src/app/api/v2/sites/route.test.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const mockExtendSite = jest.fn();
1414
const mockRestoreSite = jest.fn();
1515
const mockGetCapabilities = jest.fn();
1616
const mockSetVisibility = jest.fn();
17+
const mockRenameSite = jest.fn();
1718
const mockLogger = { error: jest.fn(), info: jest.fn() };
1819

1920
jest.mock('server/lib/principal', () => ({
@@ -48,6 +49,7 @@ jest.mock('server/services/sites', () => {
4849
default: jest.fn(() => ({
4950
getCapabilities: (...args: unknown[]) => mockGetCapabilities(...args),
5051
setVisibility: (...args: unknown[]) => mockSetVisibility(...args),
52+
renameSite: (...args: unknown[]) => mockRenameSite(...args),
5153
listSites: (...args: unknown[]) => mockListSites(...args),
5254
createSite: (...args: unknown[]) => mockCreateSite(...args),
5355
getSite: (...args: unknown[]) => mockGetSite(...args),
@@ -61,7 +63,7 @@ jest.mock('server/services/sites', () => {
6163

6264
import { SitesServiceError } from 'server/services/sites';
6365
import { GET as listSites, POST as createSite } from './route';
64-
import { DELETE as deleteSite, GET as getSite } from './[siteId]/route';
66+
import { DELETE as deleteSite, GET as getSite, PATCH as renameSite } from './[siteId]/route';
6567
import { PUT as replaceContent } from './[siteId]/content/route';
6668
import { POST as extendSite } from './[siteId]/extend/route';
6769
import { POST as restoreSite } from './[siteId]/restore/route';
@@ -168,6 +170,7 @@ describe('hosted sites API routes', () => {
168170
upload: { maxUploadBytes: 1024, maxExtractedBytes: 1024, maxFiles: 10, allowedExtensions: ['html', 'zip'] },
169171
});
170172
mockSetVisibility.mockResolvedValue(site);
173+
mockRenameSite.mockResolvedValue({ ...site, name: 'Renamed' });
171174
mockCreateSite.mockResolvedValue(site);
172175
mockGetSite.mockResolvedValue(site);
173176
mockDeleteSite.mockResolvedValue({ ...site, deletedAt: '2026-08-27T00:00:00.000Z' });
@@ -440,6 +443,44 @@ describe('hosted sites API routes', () => {
440443
expect(res.status).toBe(200);
441444
expect(mockSetVisibility).toHaveBeenCalledWith('docs-abc123', 'private', sessionPrincipal, 7);
442445
});
446+
it.each([{}, { name: 123 }, { name: 'x', ownerSubject: 'attacker' }, { name: 'x', expectedAccessRevision: 0 }])(
447+
'rejects invalid rename body %p before the service',
448+
async (body) => {
449+
const res = await renameSite(
450+
request('http://localhost/api/v2/sites/docs-abc123', { method: 'PATCH', body }),
451+
context()
452+
);
453+
expect(res.status).toBe(400);
454+
expect(mockRenameSite).not.toHaveBeenCalled();
455+
}
456+
);
457+
it('renames a site with the optional revision and the verified principal', async () => {
458+
const res = await renameSite(
459+
request('http://localhost/api/v2/sites/docs-abc123', {
460+
method: 'PATCH',
461+
body: { name: 'Renamed', expectedAccessRevision: 4 },
462+
}),
463+
context()
464+
);
465+
expect(res.status).toBe(200);
466+
expect((await res.json()).data.site.name).toBe('Renamed');
467+
expect(mockRenameSite).toHaveBeenCalledWith('docs-abc123', 'Renamed', sessionPrincipal, 4);
468+
});
469+
it('rejects a rename body that is not JSON before the service', async () => {
470+
const req = request('http://localhost/api/v2/sites/docs-abc123', { method: 'PATCH' });
471+
(req.json as jest.Mock).mockRejectedValue(new SyntaxError('Unexpected token'));
472+
const res = await renameSite(req, context());
473+
expect(res.status).toBe(400);
474+
expect(mockRenameSite).not.toHaveBeenCalled();
475+
});
476+
it('maps a rename service failure through the sites error contract', async () => {
477+
mockRenameSite.mockRejectedValueOnce(new SitesServiceError('name must be 1-255 characters.', 400));
478+
const res = await renameSite(
479+
request('http://localhost/api/v2/sites/docs-abc123', { method: 'PATCH', body: { name: ' ' } }),
480+
context()
481+
);
482+
expect(res.status).toBe(400);
483+
});
443484
it('passes deletion revision and rejects malformed revisions', async () => {
444485
expect(
445486
(await deleteSite(request('http://localhost/api/v2/sites/docs-abc123?expectedAccessRevision=3'), context()))

‎src/server/lib/sites/validation.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,13 @@
1515
*/
1616

1717
import zlib from 'zlib';
18-
import { normalizeGatewayPath, SiteUploadValidationError, validateSiteUpload } from './validation';
18+
import {
19+
getSiteNameError,
20+
normalizeGatewayPath,
21+
SITE_NAME_MAX_LENGTH,
22+
SiteUploadValidationError,
23+
validateSiteUpload,
24+
} from './validation';
1925

2026
const DEFAULT_OPTIONS = {
2127
maxUploadBytes: 10 * 1024 * 1024,
@@ -431,3 +437,19 @@ describe('reserved Sites authentication paths', () => {
431437
}
432438
);
433439
});
440+
441+
describe('getSiteNameError', () => {
442+
it('accepts ordinary names, unicode, and emoji joiners', () => {
443+
expect(getSiteNameError('Q3 report')).toBeNull();
444+
expect(getSiteNameError('r\u00E9sum\u00E9 \u{1F469}\u200D\u{1F4BB}')).toBeNull();
445+
expect(getSiteNameError('x'.repeat(SITE_NAME_MAX_LENGTH))).toBeNull();
446+
});
447+
448+
it('rejects empty, oversized, control, and text-direction characters', () => {
449+
expect(getSiteNameError('')).toMatch(/1-255/);
450+
expect(getSiteNameError('x'.repeat(SITE_NAME_MAX_LENGTH + 1))).toMatch(/1-255/);
451+
for (const name of ['a\nb', 'a\tb', 'a\u001bb', 'a\u007fb', 'a\u202Eb', 'a\u2066b']) {
452+
expect(getSiteNameError(name)).toMatch(/control or text-direction/);
453+
}
454+
});
455+
});

‎src/server/lib/sites/validation.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,3 +356,13 @@ export function normalizeGatewayPath(pathname: string): string {
356356
const normalized = normalizeArchivePath(withoutLeadingSlash);
357357
return normalized.endsWith('/') ? `${normalized}index.html` : normalized;
358358
}
359+
360+
export const SITE_NAME_MAX_LENGTH = 255;
361+
362+
const UNSAFE_SITE_NAME_CHARACTERS = /[\p{Cc}\u202A-\u202E\u2066-\u2069]/u;
363+
364+
export function getSiteNameError(name: string): string | null {
365+
if (!name || name.length > SITE_NAME_MAX_LENGTH) return `name must be 1-${SITE_NAME_MAX_LENGTH} characters.`;
366+
if (UNSAFE_SITE_NAME_CHARACTERS.test(name)) return 'name cannot contain control or text-direction characters.';
367+
return null;
368+
}

‎src/server/lib/v2RoutePolicyManifest.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@ export const V2_ROUTE_POLICY_MANIFEST: readonly V2RoutePolicyEntry[] = [
276276
{ method: 'PATCH', route: '/api/v2/sites/{siteId}/access', policy: 'principal', scope: 'sites:write' },
277277
{ method: 'GET', route: '/api/v2/sites', policy: 'principal', scope: 'sites:read' },
278278
{ method: 'POST', route: '/api/v2/sites', policy: 'principal', scope: 'sites:write' },
279+
{ method: 'PATCH', route: '/api/v2/sites/{siteId}', policy: 'principal', scope: 'sites:write' },
279280
{ method: 'DELETE', route: '/api/v2/sites/{siteId}', policy: 'principal', scope: 'sites:write' },
280281
{ method: 'GET', route: '/api/v2/sites/{siteId}', policy: 'principal', scope: 'sites:read' },
281282
{ method: 'PUT', route: '/api/v2/sites/{siteId}/content', policy: 'principal', scope: 'sites:write' },

‎src/server/services/__tests__/sites.behavior.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,21 @@ describe('SitesService behavior', () => {
658658
now.mockRestore();
659659
});
660660

661+
it('rejects an unsafe or oversized name before any storage call', async () => {
662+
for (const name of ['bad\u001b[31mname', 'two\nlines', 'spoof\u202Eexe', 'x'.repeat(256)]) {
663+
await expect(
664+
service.createSite({
665+
principal,
666+
visibility: 'public',
667+
fileName: 'index.html',
668+
content: Buffer.from('site'),
669+
name,
670+
})
671+
).rejects.toMatchObject({ statusCode: 400 });
672+
}
673+
expect(mockPutFiles).not.toHaveBeenCalled();
674+
});
675+
661676
it('uses the generated default name and no expiry or actor when TTL is disabled', async () => {
662677
enabledConfig({ ttl: { enabled: false } });
663678

@@ -943,6 +958,66 @@ describe('SitesService behavior', () => {
943958
});
944959
});
945960

961+
describe('renameSite', () => {
962+
it('trims and persists the name without changing the id, url, or revisions', async () => {
963+
addSite(state, { name: 'old' });
964+
965+
const result = await service.renameSite('site-1', ' New name ', principal);
966+
967+
expect(result.name).toBe('New name');
968+
expect(result.id).toBe('site-1');
969+
expect(state.sites[0].name).toBe('New name');
970+
expect(state.sites[0].accessRevision).toBe(1);
971+
expect(mockAudit).toHaveBeenLastCalledWith(
972+
expect.anything(),
973+
expect.objectContaining({
974+
event: 'sites.renamed',
975+
meta: expect.objectContaining({ siteId: 'site-1', from: 'old', to: 'New name' }),
976+
})
977+
);
978+
});
979+
980+
it('rejects control and text-direction characters but allows emoji joiners', async () => {
981+
addSite(state, { name: 'old' });
982+
983+
for (const name of ['two\nlines', 'tab\there', 'esc\u001b[0m', 'spoof\u202Eexe']) {
984+
await expect(service.renameSite('site-1', name, principal)).rejects.toMatchObject({ statusCode: 400 });
985+
}
986+
await expect(service.renameSite('site-1', '\u{1F469}\u200D\u{1F4BB} docs', principal)).resolves.toMatchObject({
987+
name: '\u{1F469}\u200D\u{1F4BB} docs',
988+
});
989+
});
990+
991+
it('is a no-op without an audit entry when the name is unchanged', async () => {
992+
addSite(state, { name: 'same' });
993+
mockAudit.mockClear();
994+
995+
await expect(service.renameSite('site-1', ' same ', principal)).resolves.toMatchObject({ name: 'same' });
996+
expect(mockAudit).not.toHaveBeenCalled();
997+
});
998+
999+
it('rejects empty, blank, and oversized names', async () => {
1000+
addSite(state);
1001+
1002+
for (const name of ['', ' ', 'x'.repeat(256)]) {
1003+
await expect(service.renameSite('site-1', name, principal)).rejects.toMatchObject({ statusCode: 400 });
1004+
}
1005+
});
1006+
1007+
it('rejects a stale access revision and a non-owner', async () => {
1008+
addSite(state, { name: 'old' });
1009+
const stranger = { ...principal, userId: 'stranger', actor: 'stranger' } as Principal;
1010+
1011+
await expect(service.renameSite('site-1', 'new', principal, 99)).rejects.toMatchObject({ httpStatus: 409 });
1012+
await expect(service.renameSite('site-1', 'new', stranger)).rejects.toMatchObject({ httpStatus: 403 });
1013+
expect(state.sites[0].name).toBe('old');
1014+
});
1015+
1016+
it('returns not found for a missing site', async () => {
1017+
await expect(service.renameSite('missing', 'new', principal)).rejects.toMatchObject({ statusCode: 404 });
1018+
});
1019+
});
1020+
9461021
describe('deleteSite', () => {
9471022
it('tombstones the site and keeps its content restorable', async () => {
9481023
addSite(state);

‎src/server/services/sites.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { getLogger } from 'server/lib/logger';
2525
import { buildSiteUrl, parseSiteIdFromHost, resolveSitesConfig, ResolvedSitesConfig } from 'server/lib/sites/config';
2626
import { SitesObjectNotFoundError, SitesStorage } from 'server/lib/sites/storage';
2727
import {
28+
getSiteNameError,
2829
normalizeGatewayPath,
2930
SiteUploadValidationError,
3031
validateSiteUpload,
@@ -392,6 +393,9 @@ export default class SitesService extends Service {
392393
throw new SitesServiceError('Service-key sites must be public; visibility must be private or public.', 400);
393394
}
394395
if (principal.kind !== 'service_key' || visibility === 'private') this.assertPrivateReady(config);
396+
const requestedName = input.name?.trim();
397+
const nameError = requestedName ? getSiteNameError(requestedName) : null;
398+
if (nameError) throw new SitesServiceError(nameError, 400);
395399
const upload = this.validateUpload(input, config);
396400
const siteId = createSiteId();
397401
const site = await this.withUploadRollback(config, async (prefixes) => {
@@ -401,7 +405,7 @@ export default class SitesService extends Service {
401405
await assertSitesPrincipal(principal, 'write', trx);
402406
const created = (await this.db.models.Site.query(trx).insert({
403407
siteId,
404-
name: input.name?.trim() || this.defaultSiteName(siteId, config),
408+
name: requestedName || this.defaultSiteName(siteId, config),
405409
status: 'active',
406410
activeVersionId: null,
407411
fileCount: upload.fileCount,
@@ -602,6 +606,31 @@ export default class SitesService extends Service {
602606
});
603607
}
604608

609+
async renameSite(
610+
siteId: string,
611+
name: string,
612+
principal: Principal,
613+
expectedAccessRevision?: number
614+
): Promise<SiteResponse> {
615+
await assertSitesPrincipal(principal, 'write');
616+
const trimmed = typeof name === 'string' ? name.trim() : '';
617+
const nameError = getSiteNameError(trimmed);
618+
if (nameError) throw new SitesServiceError(nameError, 400);
619+
return this.db.models.Site.transact(async (trx) => {
620+
const { site, config } = await this.getActiveSite(siteId, trx);
621+
await assertSitesPrincipal(principal, 'write', trx);
622+
assertSiteOwner(site, principal);
623+
this.checkRevision(site, expectedAccessRevision);
624+
if (site.name === trimmed) return this.serialize(site, config, principal);
625+
await this.audit(trx, 'renamed', siteId, principal, { from: site.name, to: trimmed });
626+
const updated = await site.$query(trx).patchAndFetch({
627+
name: trimmed,
628+
updatedBy: principal.identity?.email || null,
629+
});
630+
return this.serialize(updated as Site, config, principal);
631+
});
632+
}
633+
605634
async deleteSite(siteId: string, principal: Principal, expectedAccessRevision?: number): Promise<SiteResponse> {
606635
await assertSitesPrincipal(principal, 'write');
607636
const config = await this.getConfig();

0 commit comments

Comments
 (0)