From 237ff84cc5842ea4970edadf5a5c53cb4a2252ea Mon Sep 17 00:00:00 2001 From: Neal Shah <30693865+ProgrammerIn-wonderland@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:02:07 -0500 Subject: [PATCH] feat(hosting): sites list their custom domains, and hosting.detach() removes them (#4651) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(hosting): sites list their custom domains, attach names a moved domain's old site, and hosting.detach() removes domains - puter-subdomains read/select return `custom_domains` ({ uuid, hostname, status }) per site, filled by a `site.customDomains` event listener. Only rows attached under the site's current owner count; the field is left out when the listener fails, so a failed lookup never reads as "no domains". - The attach dialog's answer carries `previousSite` when the user moved the domain from another site, kept through a status check or switch to www. - puter.hosting.detach(subdomain) opens the custom domain dialog in a remove-only mode (desktop message, frame, or popup) and resolves the domains the user removed, or []. Desktops advertise it as `custom-domains-detach`; older ones reject with not_supported. Co-Authored-By: Claude Opus 5.5 * test(workers): expect the sandbox-owner message create() throws now create() rejects another user's sandbox app with "The sandbox app '…' belongs to another user…" since the workers name-cap fix; the deploy test still expected the old wording and failed on main. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- src/backend/clients/event/types.ts | 17 +++ .../homepage/HomepageController.ts | 1 + .../drivers/subdomain/SubdomainDriver.test.ts | 25 ++++ .../drivers/subdomain/SubdomainDriver.ts | 62 ++++++++- src/docs/src/Hosting.md | 1 + src/docs/src/Hosting/attach.md | 2 + src/docs/src/Hosting/detach.md | 75 +++++++++++ src/docs/src/Objects/customdomain.md | 6 +- src/docs/src/Objects/subdomain.md | 10 ++ src/docs/src/examples.js | 6 + .../playground/examples/hosting-detach.html | 27 ++++ src/docs/src/sidebar.js | 8 ++ src/gui/src/IPC.js | 26 ++-- src/gui/src/UI/UIWindowAttachCustomDomain.js | 60 ++++++--- .../src/UI/UIWindowAttachCustomDomain.test.js | 124 +++++++++++++++++- src/gui/src/helpers/appLaunchUrl.js | 2 +- src/gui/src/helpers/popupFrame.js | 4 +- src/gui/src/i18n/translations/en.js | 3 + src/gui/src/initgui.js | 27 ++-- src/gui/src/util/popupAuth.js | 2 +- src/puter-js/index.d.ts | 1 + src/puter-js/src/lib/guiEmbed.js | 3 +- .../src/modules/UI.attachCustomDomain.test.js | 67 ++++++++++ .../UI.attachCustomDomainFrame.test.js | 25 ++++ src/puter-js/src/modules/UI.js | 97 ++++++++++---- .../src/modules/Workers.deploy.test.js | 2 +- src/puter-js/src/modules/hosting/detach.js | 33 +++++ .../src/modules/hosting/detach.test.js | 30 +++++ src/puter-js/src/modules/hosting/index.js | 4 +- src/puter-js/src/modules/hosting/types.js | 14 ++ .../e2e/fixtures/attach-custom-domain.html | 13 +- .../e2e/specs/attachCustomDomain.spec.js | 60 +++++++++ 32 files changed, 753 insertions(+), 84 deletions(-) create mode 100644 src/docs/src/Hosting/detach.md create mode 100644 src/docs/src/playground/examples/hosting-detach.html create mode 100644 src/puter-js/src/modules/hosting/detach.js create mode 100644 src/puter-js/src/modules/hosting/detach.test.js diff --git a/src/backend/clients/event/types.ts b/src/backend/clients/event/types.ts index 07d870277..a75d2bee4 100644 --- a/src/backend/clients/event/types.ts +++ b/src/backend/clients/event/types.ts @@ -62,6 +62,16 @@ export type TeamBillingEvent = TeamBillingContext & { // eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface IExtensionEventMap {} +/** A custom domain as a site object from the hosting API lists it. */ +export type SiteCustomDomain = { + uuid: string; + hostname: string; + status: string; +}; + +/** Site name → the custom domains attached to it. */ +export type SiteCustomDomainsBySite = Record; + /** * What a KV mutation did to a key. `expire` is a lifetime change rather than a * value change, which is why it is not folded into `set`. @@ -858,6 +868,13 @@ export type EventMap = { // listener that recognises the host sets `result.subdomain` to the site // it serves; an unclaimed host is answered with a 404. 'site.resolveHost': { host: string; result: { subdomain: string | null } }; + // Asked when site objects are returned by the hosting API. A listener + // that manages custom domains sets `result[subdomain]` to the hostnames + // attached to that site; a site it leaves out has none. + 'site.customDomains': { + sites: Array<{ subdomain: string; userId: number }>; + result: SiteCustomDomainsBySite; + }; // Asked before a hosted file is streamed. A listener that owns the site // sets `result.allowed = false` to withhold the entry; the visitor then // sees the same 404 as for a missing file. diff --git a/src/backend/controllers/homepage/HomepageController.ts b/src/backend/controllers/homepage/HomepageController.ts index 1b5b4d696..8aadc65eb 100644 --- a/src/backend/controllers/homepage/HomepageController.ts +++ b/src/backend/controllers/homepage/HomepageController.ts @@ -51,6 +51,7 @@ export const FRAMED_POPUP_ACTIONS = [ 'top-up', 'request-email-confirmation', 'attach-custom-domain', + 'detach-custom-domain', ] as const; /** Longest description/og:description/twitter:description on `/app/`. */ diff --git a/src/backend/drivers/subdomain/SubdomainDriver.test.ts b/src/backend/drivers/subdomain/SubdomainDriver.test.ts index 777bd2517..502331fcd 100644 --- a/src/backend/drivers/subdomain/SubdomainDriver.test.ts +++ b/src/backend/drivers/subdomain/SubdomainDriver.test.ts @@ -351,6 +351,31 @@ describe('SubdomainDriver.read / select', () => { expect(fetched?.subdomain).toBe(sub); }); + it('lists no custom domains, without asking listeners, while they are off', async () => { + const { actor } = await makeUser(); + const sub = uniqueSubdomain('no-domains'); + await withActor(actor, () => + driver.create({ + object: { + subdomain: sub, + root_dir: `/${actor.user!.username}/Public`, + }, + }), + ); + const listener = vi.fn(); + server.clients.event.on('site.customDomains', listener); + + try { + const fetched = (await withActor(actor, () => + driver.read({ id: { subdomain: sub } }), + )) as Record | null; + expect(fetched?.custom_domains).toEqual([]); + } finally { + server.clients.event.off('site.customDomains', listener); + } + expect(listener).not.toHaveBeenCalled(); + }); + it("rejects reading another user's subdomain with 403", async () => { const a = await makeUser(); const b = await makeUser(); diff --git a/src/backend/drivers/subdomain/SubdomainDriver.ts b/src/backend/drivers/subdomain/SubdomainDriver.ts index 18b1ec292..93d48ac32 100644 --- a/src/backend/drivers/subdomain/SubdomainDriver.ts +++ b/src/backend/drivers/subdomain/SubdomainDriver.ts @@ -18,6 +18,10 @@ */ import { posix as pathPosix } from 'node:path'; +import type { + EventMetadata, + SiteCustomDomainsBySite, +} from '../../clients/event/types.js'; import { HttpError } from '../../core/http/HttpError.js'; import { DEFAULT_FREE_SUBSCRIPTION, @@ -713,6 +717,9 @@ export class SubdomainDriver extends PuterDriver { const pendingEntries = awaitLater( this.stores.fsEntry.getEntriesByIds(rootDirIds), ); + const pendingCustomDomains = awaitLater( + this.#customDomainsBySite(rows), + ); // `associated_app` is derived: match apps owned by `subdomain.user_id` // whose `index_url` resolves to one of the subdomain's host @@ -728,13 +735,19 @@ export class SubdomainDriver extends PuterDriver { // Single round-trip per store, all in parallel — the filetype // lookup keys off the requested ids (not on getByIds' result), // so it doesn't need to wait for the app rows. - const [usersById, entriesById, appsById, filetypesByAppId] = - await Promise.all([ - pendingUsers, - pendingEntries, - this.stores.app.getByIds(allAppIds), - this.stores.app.getFiletypeAssociationsByIds(allAppIds), - ]); + const [ + usersById, + entriesById, + appsById, + filetypesByAppId, + customDomainsBySite, + ] = await Promise.all([ + pendingUsers, + pendingEntries, + this.stores.app.getByIds(allAppIds), + this.stores.app.getFiletypeAssociationsByIds(allAppIds), + pendingCustomDomains, + ]); const embeddedApps = [...appsById.values()]; const embedViews = await this.services.app.views(embeddedApps, actor, { @@ -751,10 +764,37 @@ export class SubdomainDriver extends PuterDriver { entriesById, appViewsById, associatedAppIdByRowUuid, + customDomainsBySite, }), ); } + /** + * The custom domains attached to each row's site, as the custom-domain + * listener reports them. Null when a listener failed, so an outage leaves + * the field out instead of reporting no domains. + */ + async #customDomainsBySite( + rows: Array>, + ): Promise { + const result: SiteCustomDomainsBySite = {}; + if (!this.config.custom_domains_enabled) return result; + const sites = rows.flatMap((row) => { + const userId = Number(row.user_id); + return typeof row.subdomain === 'string' && Number.isFinite(userId) + ? [{ subdomain: row.subdomain, userId }] + : []; + }); + if (sites.length === 0) return result; + const meta: EventMetadata = {}; + await this.clients.event.emitAndWait( + 'site.customDomains', + { sites, result }, + meta, + ); + return meta.listener_failed ? null : result; + } + /** * For each subdomain row, find the app owned by the same user whose * `index_url` matches one of the subdomain's host candidates (subdomain × @@ -848,6 +888,7 @@ export class SubdomainDriver extends PuterDriver { entriesById: Map; appViewsById: Map; associatedAppIdByRowUuid: Map; + customDomainsBySite: SiteCustomDomainsBySite | null; }, ): Record { const ts = row.ts; @@ -906,6 +947,13 @@ export class SubdomainDriver extends PuterDriver { : null, app_owner: appOwnerApp, protected: Boolean(row.protected), + ...(lookups.customDomainsBySite + ? { + custom_domains: + lookups.customDomainsBySite[String(row.subdomain)] ?? + [], + } + : {}), }; } } diff --git a/src/docs/src/Hosting.md b/src/docs/src/Hosting.md index ec38d7842..ae124fb17 100644 --- a/src/docs/src/Hosting.md +++ b/src/docs/src/Hosting.md @@ -192,6 +192,7 @@ These hosting features are supported out of the box when using Puter.js: - **[`puter.hosting.update()`](/Hosting/update/)** - Update hosting settings - **[`puter.hosting.delete()`](/Hosting/delete/)** - Delete a hosting deployment - **[`puter.hosting.attach()`](/Hosting/attach/)** - Let the user connect their own domain to a website +- **[`puter.hosting.detach()`](/Hosting/detach/)** - Let the user remove the custom domains of a website ## Examples diff --git a/src/docs/src/Hosting/attach.md b/src/docs/src/Hosting/attach.md index 35eb76d1b..fbb8f4c38 100644 --- a/src/docs/src/Hosting/attach.md +++ b/src/docs/src/Hosting/attach.md @@ -32,6 +32,8 @@ A `Promise` that resolves to a [`CustomDomain`](/Objects/customdomain/) object f A newly added domain resolves with `status` set to `pending`. Its `records` list the DNS records the user still has to set. +When the user moved the domain from another of their websites, its `previousSite` attribute names that website. The other website no longer has the domain. + On a website that is cross-origin isolated, the popup can't send its result back to your page, so the promise resolves `null` even if the user goes on to connect a domain in the popup. ## Errors diff --git a/src/docs/src/Hosting/detach.md b/src/docs/src/Hosting/detach.md new file mode 100644 index 000000000..ee408ae70 --- /dev/null +++ b/src/docs/src/Hosting/detach.md @@ -0,0 +1,75 @@ +--- +title: puter.hosting.detach() +description: Let the user remove the custom domains of a website hosted on Puter. +platforms: [websites, apps] +--- + +Opens a Puter dialog where the user removes custom domains from one of their websites. + +The dialog lists the domains connected to the website. Removing a domain takes it off the user's account. It stops serving the website right away, and its monthly charge stops. To use the domain again, the user adds it again with [`puter.hosting.attach()`](/Hosting/attach/) and sets its DNS records. + +Your app doesn't need any permission to call this method. The user makes the choice in the dialog, and your app only receives the domains they removed. + +Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs the user in first if needed. Puter's own apps on puter.com subdomains show it in a frame over the page instead, when the user is signed in to both. + +## Syntax + +```js +puter.hosting.detach(subdomain) +``` + +## Parameters + +#### `subdomain` (String) (required) + +The name of the website to remove domains from, such as `example` for `example.puter.site`. The website must belong to the signed-in user. + +## Return value + +A `Promise` that resolves to an array of [`CustomDomain`](/Objects/customdomain/) objects, one for each domain the user removed. The array is empty if the user closed the dialog without removing a domain. + +To see which domains a website still has, read the `custom_domains` attribute of its [`Subdomain`](/Objects/subdomain/) object from [`puter.hosting.get()`](/Hosting/get/). + +On a website that is cross-origin isolated, the popup can't send its result back to your page, so the promise resolves an empty array even if the user removes a domain in the popup. + +## Errors + +The promise rejects with an error whose `code` is one of the following: + +- `invalid_argument` when `subdomain` is missing or empty. +- `not_available` in an environment that can't show a dialog, such as Node.js or a worker. +- `not_supported` inside a version of the Puter desktop that doesn't have the dialog. + +## Examples + +### Remove a custom domain from a website + +```html;hosting-detach + + + + + + + +``` diff --git a/src/docs/src/Objects/customdomain.md b/src/docs/src/Objects/customdomain.md index 2675fea08..aad0ed851 100644 --- a/src/docs/src/Objects/customdomain.md +++ b/src/docs/src/Objects/customdomain.md @@ -3,7 +3,7 @@ title: CustomDomain description: The CustomDomain object containing the details of a domain connected to a website. --- -The `CustomDomain` object describes a domain the user owns that serves one of their websites hosted on Puter. The [`puter.hosting.attach()`](/Hosting/attach/) method resolves to it. +The `CustomDomain` object describes a domain the user owns that serves one of their websites hosted on Puter. The [`puter.hosting.attach()`](/Hosting/attach/) method resolves to it, and [`puter.hosting.detach()`](/Hosting/detach/) resolves to a list of them. ## Attributes @@ -57,6 +57,10 @@ When the domain became active, in milliseconds since the Unix epoch, or `null` i Who hosts the DNS of a root domain: `route53`, `godaddy` or `other`. Puter looks this up when a root domain is added, and only includes it in that response. Route 53 and GoDaddy can't point a root domain at another host name, so a root domain on either is added as its `www.` hostname (see `redirectFrom`). +#### `previousSite` (String, optional) + +The name of the website the domain served before, when the user moved it from that website in the [`puter.hosting.attach()`](/Hosting/attach/) dialog. Only the result of [`puter.hosting.attach()`](/Hosting/attach/) includes it. + #### `redirectFrom` (String, optional) The root domain that forwards to this `www.` hostname. A root domain hosted on Route 53 or GoDaddy is added as its `www.` hostname, and the user can switch any other root domain to `www.` in the dialog. The `records` then include an `A` record that forwards the root domain. diff --git a/src/docs/src/Objects/subdomain.md b/src/docs/src/Objects/subdomain.md index 7850db22f..ea36f3d14 100755 --- a/src/docs/src/Objects/subdomain.md +++ b/src/docs/src/Objects/subdomain.md @@ -19,3 +19,13 @@ e.g. in `example.puter.site`, `example` is the subdomain. #### `root_dir` (FSItem) An FSItem object representing the root directory of the subdomain. This is the directory where the files of the subdomain are stored. + +#### `custom_domains` (Array, optional) + +The custom domains connected to the website, whether pending or active. Each one is an object with these attributes: + +- `uuid` (String): the unique identifier of the custom domain. +- `hostname` (String): the domain, such as `www.example.com`. +- `status` (String): `pending`, `active` or `failed`, as on a [`CustomDomain`](/Objects/customdomain/). + +The array is empty when the website has no custom domains. The attribute is missing when Puter couldn't look the domains up, so read a missing attribute as unknown rather than as no domains. diff --git a/src/docs/src/examples.js b/src/docs/src/examples.js index 0fbec4fda..644090426 100644 --- a/src/docs/src/examples.js +++ b/src/docs/src/examples.js @@ -870,6 +870,12 @@ const examples = [ slug: 'hosting-attach', source: '/playground/examples/hosting-attach.html', }, + { + title: 'Remove a custom domain from a website', + description: 'Let the user remove a custom domain from a website with Puter.js hosting API. Run and experiment with this example directly in the playground.', + slug: 'hosting-detach', + source: '/playground/examples/hosting-detach.html', + }, { title: 'Publish a portfolio page', description: 'Publish a page built from form input as a public website with Puter.js hosting API. Run and modify this example directly in your browser.', diff --git a/src/docs/src/playground/examples/hosting-detach.html b/src/docs/src/playground/examples/hosting-detach.html new file mode 100644 index 000000000..063aeb56d --- /dev/null +++ b/src/docs/src/playground/examples/hosting-detach.html @@ -0,0 +1,27 @@ + + + + + + + diff --git a/src/docs/src/sidebar.js b/src/docs/src/sidebar.js index fd2da6856..bd4ed31fa 100755 --- a/src/docs/src/sidebar.js +++ b/src/docs/src/sidebar.js @@ -612,6 +612,14 @@ let sidebar = [ source: '/Hosting/attach.md', path: '/Hosting/attach', }, + { + title: 'detach()', + page_title: 'puter.hosting.detach()', + title_tag: 'puter.hosting.detach()', + icon: '/assets/img/function.svg', + source: '/Hosting/detach.md', + path: '/Hosting/detach', + }, ], }, { diff --git a/src/gui/src/IPC.js b/src/gui/src/IPC.js index 893d1d796..8e170ae8c 100644 --- a/src/gui/src/IPC.js +++ b/src/gui/src/IPC.js @@ -1519,17 +1519,16 @@ const ipc_listener = async (event, handled) => { } } //-------------------------------------------------------- - // attachCustomDomain + // attachCustomDomain / detachCustomDomain //-------------------------------------------------------- - else if ( event.data.msg === 'attachCustomDomain' ) { + else if ( event.data.msg === 'attachCustomDomain' || event.data.msg === 'detachCustomDomain' ) { + const detaching = event.data.msg === 'detachCustomDomain'; // Always answer, as for showFeedbackDialog: the SDK promise only // settles on a reply. - const respond = (domain) => { - target_iframe?.contentWindow?.postMessage({ - msg: 'customDomainAttached', - domain: domain ?? null, - original_msg_id: msg_id, - }, '*'); + const respond = (answer) => { + target_iframe?.contentWindow?.postMessage(detaching + ? { msg: 'customDomainDetached', domains: answer ?? [], original_msg_id: msg_id } + : { msg: 'customDomainAttached', domain: answer ?? null, original_msg_id: msg_id }, '*'); }; const subdomain = typeof event.data.subdomain === 'string' ? event.data.subdomain : ''; @@ -1546,23 +1545,24 @@ const ipc_listener = async (event, handled) => { return; } } catch ( e ) { - console.error('IPC attachCustomDomain: auth gate failed', e); + console.error(`IPC ${event.data.msg}: auth gate failed`, e); respond(null); return; } - let domain = null; + let answer = null; try { // The requester shown is the app's registered name from the // GUI's own records; its window title is app-controlled. - domain = await UIWindowAttachCustomDomain({ + answer = await UIWindowAttachCustomDomain({ subdomain, requester: app_name, + mode: detaching ? 'detach' : 'attach', }); } catch ( e ) { - console.error('IPC attachCustomDomain failed', e); + console.error(`IPC ${event.data.msg} failed`, e); } - respond(domain); + respond(answer); $(target_iframe).get(0)?.focus({ preventScroll: true }); } finally { custom_domain_dialog_guard.markClosed(); diff --git a/src/gui/src/UI/UIWindowAttachCustomDomain.js b/src/gui/src/UI/UIWindowAttachCustomDomain.js index b8355cebb..ce8733231 100644 --- a/src/gui/src/UI/UIWindowAttachCustomDomain.js +++ b/src/gui/src/UI/UIWindowAttachCustomDomain.js @@ -54,23 +54,28 @@ const ICON_X = svg('} The chosen domain as the API returns it, or - * null when the user closes the dialog first. Never rejects. + * @returns {Promise} Attaching: the chosen domain as the + * API returns it, with `previousSite` when it was moved here from another + * site, or null when the user closes the dialog first. Detaching: the + * domains the user removed, possibly none. Never rejects. */ async function UIWindowAttachCustomDomain (options) { options = options ?? {}; const subdomain = String(options.subdomain ?? ''); const site_host = `${subdomain}.${window.hosting_domain}`; + const detaching = options.mode === 'detach'; return new Promise((resolve) => { const modal_id = `custom-domain-${++attach_modal_seq}`; @@ -80,6 +85,17 @@ async function UIWindowAttachCustomDomain (options) { // A domain added in this dialog is the answer even if the user then // closes it: it exists, and is billed, either way. let chosen = null; + // The domain moved here in this dialog, and the site it served before. + let moved = null; + // Detaching: every domain removed in this dialog. + const removed = []; + const answer = () => { + if ( detaching ) return removed; + if ( chosen && moved?.uuid === chosen.uuid ) { + return { ...chosen, previousSite: moved.site }; + } + return chosen; + }; const titleId = `${modal_id}-title`; const closeLabel = html_encode(i18n('close')); @@ -89,8 +105,8 @@ async function UIWindowAttachCustomDomain (options) {
${ICON_GLOBE}
-

${i18n('custom_domain_title')}

-

${i18n('custom_domain_intro', [site_host])}

+

${i18n(detaching ? 'custom_domain_detach_title' : 'custom_domain_title')}

+

${i18n(detaching ? 'custom_domain_detach_intro' : 'custom_domain_intro', [site_host])}

${options.requester ? `

${i18n('custom_domain_requested_by', [options.requester])}

` : ''}
@@ -114,14 +130,16 @@ async function UIWindowAttachCustomDomain (options) {
    - - + ${detaching + ? `` + : ` + `}
    @@ -189,7 +207,7 @@ async function UIWindowAttachCustomDomain (options) { $(document).off(`keydown.${modal_id}`); $overlay.removeClass('app-feedback-open'); setTimeout(() => $overlay.remove(), 160); - resolve(chosen); + resolve(answer()); }; let currentPane = 'loading'; @@ -339,7 +357,7 @@ async function UIWindowAttachCustomDomain (options) { // in the empty state where the eye lands instead of the footer. const toggleEmpty = () => { $overlay.find('.custom-domain-empty').toggle(listed.length === 0); - $overlay.find('.custom-domain-list-add').toggle(listed.length > 0); + $overlay.find('.custom-domain-list-add').toggle(listed.length > 0 && ! detaching); }; // One row asks for confirmation at a time; asking on another puts the @@ -367,10 +385,10 @@ async function UIWindowAttachCustomDomain (options) { }; const renderList = (items) => { - listed = items; + listed = detaching ? items.filter((i) => i.site === subdomain) : items; const $list = $overlay.find('.custom-domain-list').empty(); toggleEmpty(); - for ( const item of items ) { + for ( const item of listed ) { const status = statusOf(item); const $row = $(`
  • @@ -400,7 +418,8 @@ async function UIWindowAttachCustomDomain (options) { 'aria-label': text('custom_domain_remove_named', [item.hostname]), title: text('custom_domain_remove'), }); - $row.find('.custom-domain-use').on('click', () => use(item, $row)); + if ( detaching ) $row.find('.custom-domain-use').remove(); + else $row.find('.custom-domain-use').on('click', () => use(item, $row)); $row.find('.custom-domain-remove').on('click', () => { if ( ! busy ) confirmOn($row, 'remove', text('custom_domain_remove_confirm')); }); @@ -438,6 +457,7 @@ async function UIWindowAttachCustomDomain (options) { showError('list', customDomainErrorText(res)); return; } + moved = { uuid: item.uuid, site: item.site }; settleOn(res.data); } catch ( e ) { console.error('custom-domain: move failed', e); @@ -474,6 +494,7 @@ async function UIWindowAttachCustomDomain (options) { const remove = async (item, $row, $btn) => { if ( busy ) return; if ( ! await deleteDomain(item, 'list', $btn) ) return; + if ( detaching ) removed.push(item); listed = listed.filter((i) => i.uuid !== item.uuid); // Focus moves to the next row, else the previous one, else to // adding a domain once the empty state shows. @@ -487,7 +508,10 @@ async function UIWindowAttachCustomDomain (options) { $row.remove(); toggleEmpty(); if ( hadFocus && focusLost() ) { - focusOn($overlay.find(listed.length ? '.custom-domain-list-add' : '.custom-domain-empty-add').get(0)); + const next = detaching + ? '[data-pane="list"] .custom-domain-close' + : (listed.length ? '.custom-domain-list-add' : '.custom-domain-empty-add'); + focusOn($overlay.find(next).get(0)); } }, 180); }; @@ -679,7 +703,7 @@ async function UIWindowAttachCustomDomain (options) { } renderList(res.data?.items ?? []); const price = formatCustomDomainPrice(res.data?.pricing); - if ( price ) { + if ( price && ! detaching ) { $overlay.find('.custom-domain-price').text(text('custom_domain_price_note', [price])).show(); } showPane('list'); diff --git a/src/gui/src/UI/UIWindowAttachCustomDomain.test.js b/src/gui/src/UI/UIWindowAttachCustomDomain.test.js index 641b3c615..320058e7c 100644 --- a/src/gui/src/UI/UIWindowAttachCustomDomain.test.js +++ b/src/gui/src/UI/UIWindowAttachCustomDomain.test.js @@ -51,10 +51,10 @@ const visiblePane = () => $('.custom-domain-pane').filter((_, el) => el.style.di const pressEscape = () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); /** Opens the dialog and waits for the list to load. */ -const open = async (items = [pendingDomain()]) => { +const open = async (items = [pendingDomain()], options = {}) => { globalThis.fetch = serve(items); let result = 'open'; - UIWindowAttachCustomDomain({ subdomain: 'mysite' }).then((r) => { + UIWindowAttachCustomDomain({ subdomain: 'mysite', ...options }).then((r) => { result = r; }); await flush(); @@ -254,4 +254,124 @@ describe('UIWindowAttachCustomDomain', () => { expect(row.isConnected).toBe(true); expect(row.hasAttribute('inert')).toBe(true); }); + + describe('the answer to the caller', () => { + /** Moves `item` here; the API answers with it serving this site. */ + const moveHere = async (item) => { + globalThis.fetch = vi.fn(async (url, opts = {}) => { + const path = String(url).split('/custom-domains')[1]; + const method = opts.method ?? 'GET'; + if ( method === 'GET' && ! path ) return json(200, { items: [item] }); + if ( method === 'PATCH' ) return json(200, { ...item, site: 'mysite' }); + if ( method === 'GET' ) return json(200, { ...item, site: 'mysite' }); + return json(200, {}); + }); + }; + + it('names the site a moved domain served before', async () => { + const item = pendingDomain({ site: 'oldsite' }); + const { result } = await open([item]); + await moveHere(item); + $('.custom-domain-row .custom-domain-use').trigger('click'); + $('.custom-domain-row .custom-domain-confirm-go').trigger('click'); + await flush(); + await flush(); + $('.custom-domain-done').trigger('click'); + await flush(); + + expect(result()).toMatchObject({ uuid: 'd1', site: 'mysite', previousSite: 'oldsite' }); + }); + + it('keeps the previous site through a status check', async () => { + const item = pendingDomain({ site: 'oldsite' }); + const { result } = await open([item]); + await moveHere(item); + $('.custom-domain-row .custom-domain-use').trigger('click'); + $('.custom-domain-row .custom-domain-confirm-go').trigger('click'); + await flush(); + await flush(); + $('.custom-domain-check').trigger('click'); + await flush(); + await flush(); + $('.custom-domain-done').trigger('click'); + await flush(); + + expect(result()).toMatchObject({ uuid: 'd1', previousSite: 'oldsite' }); + }); + + it('names no previous site for a domain already serving this site', async () => { + const { result } = await open(); + $('.custom-domain-row .custom-domain-use').trigger('click'); + $('.custom-domain-done').trigger('click'); + await flush(); + + expect(result()).toMatchObject({ uuid: 'd1' }); + expect(result()).not.toHaveProperty('previousSite'); + }); + }); + + describe('removing a domain from the site', () => { + const detach = (items) => open(items, { mode: 'detach' }); + + it("lists only this site's domains, with no way to move or add one", async () => { + await detach([ + pendingDomain(), + pendingDomain({ uuid: 'd2', hostname: 'b.example.com', site: 'other' }), + ]); + const hosts = $('.custom-domain-row-host').toArray().map((el) => el.textContent); + expect(hosts).toEqual(['www.example.com']); + expect($('.custom-domain-use').length).toBe(0); + expect($('.custom-domain-to-add').length).toBe(0); + }); + + it('answers with the domains removed', async () => { + const { result } = await detach([ + pendingDomain(), + pendingDomain({ uuid: 'd2', hostname: 'b.example.com' }), + ]); + const row = document.querySelector('.custom-domain-row'); + $(row).find('.custom-domain-remove').trigger('click'); + $(row).find('.custom-domain-confirm-go').trigger('click'); + await flush(); + await flush(); + + expect(globalThis.fetch).toHaveBeenCalledWith( + 'https://api.puter.test/custom-domains/d1', + expect.objectContaining({ method: 'DELETE' }), + ); + $('[data-pane="list"] .custom-domain-close').trigger('click'); + await flush(); + expect(result()).toEqual([pendingDomain()]); + }); + + it('answers with none when the user closes it without removing', async () => { + const { result } = await detach([pendingDomain()]); + pressEscape(); + await flush(); + expect(result()).toEqual([]); + expect(globalThis.fetch).not.toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ method: 'DELETE' }), + ); + }); + + it('says so when the site has no domains', async () => { + await detach([pendingDomain({ site: 'other' })]); + expect($('.custom-domain-empty').get(0).style.display).not.toBe('none'); + expect($('.custom-domain-empty .custom-domain-state-title').text()).toBe('custom_domain_detach_none'); + }); + + it('moves focus to Done once the last domain is removed', async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }); + const ready = detach([pendingDomain()]); + await vi.runAllTimersAsync(); + await ready; + const row = document.querySelector('.custom-domain-row'); + $(row).find('.custom-domain-remove').trigger('click'); + $(row).find('.custom-domain-confirm-go').trigger('click'); + await vi.runAllTimersAsync(); + + expect(document.activeElement).toBe($('[data-pane="list"] .custom-domain-close').get(0)); + }); + }); }); diff --git a/src/gui/src/helpers/appLaunchUrl.js b/src/gui/src/helpers/appLaunchUrl.js index 99177302c..2986e2879 100644 --- a/src/gui/src/helpers/appLaunchUrl.js +++ b/src/gui/src/helpers/appLaunchUrl.js @@ -30,7 +30,7 @@ export const BUILTIN_PREFIX = 'https://builtins.namespaces.puter.com/'; // message is never replied to, and a reply timeout can't stand in for the // check because legitimate replies only arrive when the user closes the dialog. // `push-permission`: `requestPermission` settles a held push grant itself. -const GUI_FEATURES = 'feedback-dialog,enable-push,custom-domains,push-status,disable-push,push-permission'; +const GUI_FEATURES = 'feedback-dialog,enable-push,custom-domains,custom-domains-detach,push-status,disable-push,push-permission'; /** * Where an app was launched from, sent to the app as `utm_campaign` so its diff --git a/src/gui/src/helpers/popupFrame.js b/src/gui/src/helpers/popupFrame.js index 42c8710b6..0ec420352 100644 --- a/src/gui/src/helpers/popupFrame.js +++ b/src/gui/src/helpers/popupFrame.js @@ -33,6 +33,7 @@ export const FRAMED_POPUP_ACTIONS = new Set([ 'top-up', 'request-email-confirmation', 'attach-custom-domain', + 'detach-custom-domain', ]); // Actions a frame shows only for the user the framing page is signed in as. @@ -44,11 +45,12 @@ const HOST_USER_ACTIONS = new Set([ 'top-up', 'request-email-confirmation', 'attach-custom-domain', + 'detach-custom-domain', ]); // Actions framed over the whole page with no box, which their own dialog's // scrim covers. -const TRANSPARENT_ACTIONS = new Set(['upgrade', 'top-up', 'request-email-confirmation', 'attach-custom-domain']); +const TRANSPARENT_ACTIONS = new Set(['upgrade', 'top-up', 'request-email-confirmation', 'attach-custom-domain', 'detach-custom-domain']); const UPGRADE_REASONS = new Set(['funds', 'subscription', 'storage']); const UPGRADE_METHOD_MAX = 200; diff --git a/src/gui/src/i18n/translations/en.js b/src/gui/src/i18n/translations/en.js index b5f0fe1a6..c24c185fe 100644 --- a/src/gui/src/i18n/translations/en.js +++ b/src/gui/src/i18n/translations/en.js @@ -147,6 +147,9 @@ const en = { custom_domain_claim_c2a: 'This domain is on another Puter account. If it\'s yours, add this record at your DNS provider, then verify. The domain moves to your account.', custom_domain_claim_not_found: 'The record isn\'t visible yet. DNS changes can take a few minutes; try again shortly.', custom_domain_check_status: 'Check Status', + custom_domain_detach_intro: 'Custom domains connected to %strong%.', + custom_domain_detach_none: 'This website has no custom domains.', + custom_domain_detach_title: 'Remove a Custom Domain', custom_domain_empty_hint: 'Add a domain you own and point it at this website.', custom_domain_error_generic: 'Something went wrong. Please try again.', custom_domain_error_invalid: 'Enter a domain name like www.example.com.', diff --git a/src/gui/src/initgui.js b/src/gui/src/initgui.js index 0c02f5cd0..5461891c3 100644 --- a/src/gui/src/initgui.js +++ b/src/gui/src/initgui.js @@ -1147,9 +1147,11 @@ const postAuthActions = async (action) => { // ------------------------------------------------------------------------------------- // Action: attach-custom-domain — puter.hosting.attach() on a website. Hosts the custom // domain dialog for `subdomain` and posts the chosen domain back to the opener, or to - // the first-party page framing it. + // the first-party page framing it. detach-custom-domain, behind puter.hosting.detach(), + // hosts it in its remove-only mode and posts back the domains removed. // ------------------------------------------------------------------------------------- - if ( action === 'attach-custom-domain' ) { + if ( action === 'attach-custom-domain' || action === 'detach-custom-domain' ) { + const detaching = action === 'detach-custom-domain'; const msg_id = window.url_query_params.get('msg_id'); const subdomain = window.url_query_params.get('subdomain'); // Browser-attested only: the domain goes to this origin and nowhere @@ -1159,10 +1161,10 @@ const postAuthActions = async (action) => { try { target_origin = origin ? new URL(origin).origin : null; } catch (e) { - console.error('attach-custom-domain: unusable origin', origin); + console.error(`${action}: unusable origin`, origin); } - let domain = null; + let answer = detaching ? [] : null; try { if ( ! target_origin ) { throw new Error('no opener origin; not prompting'); @@ -1175,13 +1177,14 @@ const postAuthActions = async (action) => { subdomain, requester: target_origin, fullpage: window.embedded_in_popup === true && !window.embedded_in_frame, + mode: detaching ? 'detach' : 'attach', }); if ( window.embedded_in_frame ) window.tell_popup_frame('ready'); - domain = await dialog; + answer = await dialog; // The answer removes the frame, so the dialog's exit plays first. if ( window.embedded_in_frame ) await overlayGone(document, '.custom-domain-overlay'); } catch (e) { - console.error('attach-custom-domain action failed', e); + console.error(`${action} action failed`, e); } // Without an attested origin there is no safe place to send a domain; @@ -1189,13 +1192,11 @@ const postAuthActions = async (action) => { if ( target_origin ) { const messageTarget = window.embedded_in_popup ? window.opener : window.parent; try { - messageTarget?.postMessage({ - msg: 'customDomainAttached', - domain, - original_msg_id: msg_id, - }, target_origin); + messageTarget?.postMessage(detaching + ? { msg: 'customDomainDetached', domains: answer, original_msg_id: msg_id } + : { msg: 'customDomainAttached', domain: answer, original_msg_id: msg_id }, target_origin); } catch (e) { - console.error('attach-custom-domain: could not answer the requester', e); + console.error(`${action}: could not answer the requester`, e); } } @@ -1932,7 +1933,7 @@ window.initgui = async function (options) { (action === 'upgrade' && !canShowUpgradeFrame(window, session)) || (action === 'top-up' && !canShowTopUpFrame(window, session)) || (action === 'request-email-confirmation' && !canShowEmailConfirmationFrame(session)) || - (action === 'attach-custom-domain' && !canShowCustomDomainFrame(session)) + ((action === 'attach-custom-domain' || action === 'detach-custom-domain') && !canShowCustomDomainFrame(session)) ) { window.tell_popup_frame('unavailable'); return; diff --git a/src/gui/src/util/popupAuth.js b/src/gui/src/util/popupAuth.js index 9227e6fff..5a166752d 100644 --- a/src/gui/src/util/popupAuth.js +++ b/src/gui/src/util/popupAuth.js @@ -34,7 +34,7 @@ */ /** Popup actions that exist to answer a question, not to authenticate. */ -const NON_AUTH_POPUP_ACTIONS = new Set(['request-permission', 'send-feedback', 'enable-push', 'attach-custom-domain']); +const NON_AUTH_POPUP_ACTIONS = new Set(['request-permission', 'send-feedback', 'enable-push', 'attach-custom-domain', 'detach-custom-domain']); /** * Popup actions that exist to sign the user in to the opener, besides a plain diff --git a/src/puter-js/index.d.ts b/src/puter-js/index.d.ts index 3537a0790..fd898dc74 100644 --- a/src/puter-js/index.d.ts +++ b/src/puter-js/index.d.ts @@ -209,6 +209,7 @@ export type { export type { CustomDomain, CustomDomainRecord, + SiteCustomDomain, Subdomain, } from './types/modules/hosting/types.js'; diff --git a/src/puter-js/src/lib/guiEmbed.js b/src/puter-js/src/lib/guiEmbed.js index 9a829fc05..398458b21 100644 --- a/src/puter-js/src/lib/guiEmbed.js +++ b/src/puter-js/src/lib/guiEmbed.js @@ -465,6 +465,7 @@ const UNBOXED_POPUP_FRAMES = { upgrade: { allow: 'payment; otp-credentials', escapeDismisses: false }, 'top-up': { allow: 'payment; otp-credentials', escapeDismisses: false }, 'attach-custom-domain': { allow: 'clipboard-write; otp-credentials', escapeDismisses: false }, + 'detach-custom-domain': { allow: 'otp-credentials', escapeDismisses: false }, }; /** @@ -481,7 +482,7 @@ const UNBOXED_POPUP_FRAMES = { * @template T * @param {Object} opts * @param {string} opts.guiOrigin - * @param {'sign-in' | 'show-open-file-picker' | 'show-save-file-picker' | 'show-directory-picker' | 'upgrade' | 'top-up' | 'request-email-confirmation' | 'attach-custom-domain'} opts.action + * @param {'sign-in' | 'show-open-file-picker' | 'show-save-file-picker' | 'show-directory-picker' | 'upgrade' | 'top-up' | 'request-email-confirmation' | 'attach-custom-domain' | 'detach-custom-domain'} opts.action * @param {Record} opts.fragment - the popup's parameters, and `user` for every action but the sign-in * @param {string} opts.title - the frame's accessible name * @param {string} [opts.closeLabel] - puts a close button on the frame diff --git a/src/puter-js/src/modules/UI.attachCustomDomain.test.js b/src/puter-js/src/modules/UI.attachCustomDomain.test.js index f84ffea79..b7d1370aa 100644 --- a/src/puter-js/src/modules/UI.attachCustomDomain.test.js +++ b/src/puter-js/src/modules/UI.attachCustomDomain.test.js @@ -172,3 +172,70 @@ describe('attachCustomDomain_ where no dialog can be shown', () => { }); }); }); + +const detachCalls = () => + parentWindow.postMessage.mock.calls.filter(([m]) => m?.msg === 'detachCustomDomain'); + +describe('detachCustomDomain_ inside the Puter desktop', () => { + beforeEach(() => { + globalThis.location = { search: '?puter.gui_features=custom-domains,custom-domains-detach' }; + }); + + it('asks the desktop and resolves the domains the user removed', async () => { + const ui = makeUI('app'); + const promise = ui.detachCustomDomain_('mysite'); + + const [[msg]] = detachCalls(); + expect(msg).toMatchObject({ msg: 'detachCustomDomain', subdomain: 'mysite' }); + + await deliver({ + source: parentWindow, + origin: GUI_ORIGIN, + data: { msg: 'customDomainDetached', original_msg_id: msg.uuid, domains: [DOMAIN] }, + }); + await expect(promise).resolves.toEqual([DOMAIN]); + }); + + it('rejects on a desktop that can attach but not remove, instead of hanging', async () => { + globalThis.location = { search: '?puter.gui_features=custom-domains' }; + const ui = makeUI('app'); + + await expect(ui.detachCustomDomain_('mysite')).rejects.toMatchObject({ + code: 'not_supported', + }); + expect(detachCalls()).toHaveLength(0); + }); +}); + +describe('detachCustomDomain_ on a third-party site', () => { + it('opens the remove popup for the subdomain and resolves its answer', async () => { + const ui = makeUI('web'); + const promise = ui.detachCustomDomain_('mysite'); + + const url = new URL(opened[0].url); + expect(url.pathname).toBe('/action/detach-custom-domain'); + expect(url.searchParams.get('subdomain')).toBe('mysite'); + const msg_id = url.searchParams.get('msg_id'); + + await deliver({ source: opened[0], origin: GUI_ORIGIN, data: { msg: 'customDomainDetached', original_msg_id: msg_id, domains: [DOMAIN] } }); + await expect(promise).resolves.toEqual([DOMAIN]); + }); + + it('resolves none once the popup is closed without an answer', async () => { + const ui = makeUI('web'); + const promise = ui.detachCustomDomain_('mysite'); + opened[0].closed = true; + + await vi.advanceTimersByTimeAsync(1200); + await expect(promise).resolves.toEqual([]); + }); +}); + +describe('detachCustomDomain_ where no dialog can be shown', () => { + it.each(['nodejs', 'web-worker', 'service-worker'])('rejects in %s', async (env) => { + await expect(makeUI(env).detachCustomDomain_('mysite')).rejects.toMatchObject({ + code: 'not_available', + message: 'puter.hosting.detach() needs a browser page or a Puter app', + }); + }); +}); diff --git a/src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js b/src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js index 18952a7e8..434cdac9a 100644 --- a/src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js +++ b/src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js @@ -185,3 +185,28 @@ describe('attachCustomDomain_ on a page that cannot frame the dialog', () => { expect(domainFrame()).toBeNull(); }); }); + +describe('detachCustomDomain_ on a signed-in first-party page', () => { + it('shows the remove dialog in a frame and resolves the domains removed', async () => { + const result = makeUI().detachCustomDomain_('mysite'); + await vi.waitFor(() => expect(domainFrame()).not.toBeNull()); + + expect(new URL(domainFrame().src).pathname).toBe('/embed/detach-custom-domain'); + const { msg_id, ...rest } = fragment(); + expect(rest).toEqual({ user: USER, subdomain: 'mysite' }); + fromFrame({ msg: 'puterPopupFrame', state: 'ready' }); + fromFrame({ msg: 'customDomainDetached', original_msg_id: msg_id, domains: [DOMAIN] }); + + await expect(result).resolves.toEqual([DOMAIN]); + expect(opened).toHaveLength(0); + }); + + it('resolves none when the frame closes without an answer', async () => { + const result = makeUI().detachCustomDomain_('mysite'); + await vi.waitFor(() => expect(domainFrame()).not.toBeNull()); + fromFrame({ msg: 'puterPopupFrame', state: 'ready' }); + fromFrame({ msg: 'puterPopupFrame', state: 'closed' }); + + await expect(result).resolves.toEqual([]); + }); +}); diff --git a/src/puter-js/src/modules/UI.js b/src/puter-js/src/modules/UI.js index 6ab3faf9a..0bfa2afac 100644 --- a/src/puter-js/src/modules/UI.js +++ b/src/puter-js/src/modules/UI.js @@ -10,6 +10,34 @@ import { checkPermissions } from './perms/lib/holds.js'; import { PUSH_NOTIFICATIONS_PERMISSION } from './perms/lib/permissionStrings.js'; +/** + * How each custom domain dialog is reached: the desktop feature that marks + * its handler, the desktop message, and the GUI popup action and its reply. + * + * @typedef {{ method: string, feature: string, unsupported: string, ipcMsg: string, action: 'attach-custom-domain' | 'detach-custom-domain', replyMsg: string, title: string }} CustomDomainDialog + */ +/** @type {{ attach: CustomDomainDialog, detach: CustomDomainDialog }} */ +const CUSTOM_DOMAIN_DIALOGS = { + attach: { + method: 'attach', + feature: 'custom-domains', + unsupported: 'Custom domains are not available on this Puter desktop', + ipcMsg: 'attachCustomDomain', + action: 'attach-custom-domain', + replyMsg: 'customDomainAttached', + title: 'Connect a custom domain', + }, + detach: { + method: 'detach', + feature: 'custom-domains-detach', + unsupported: 'Removing custom domains is not available on this Puter desktop', + ipcMsg: 'detachCustomDomain', + action: 'detach-custom-domain', + replyMsg: 'customDomainDetached', + title: 'Remove a custom domain', + }, +}; + /** * A button shown in an `alert()` dialog. * @@ -2793,49 +2821,72 @@ export class UIModule extends EventListener { * @returns {Promise} */ async attachCustomDomain_ (subdomain) { + const result = await this.#customDomainDialog(CUSTOM_DOMAIN_DIALOGS.attach, subdomain); + return /** @type {import('./hosting/types.js').CustomDomain | null} */ (result?.domain ?? null); + } + + /** + * Backs `puter.hosting.detach()`: lets the user remove the custom domains + * of `subdomain` in a Puter dialog. The app learns which ones were removed. + * + * @internal + * @param {string} subdomain + * @returns {Promise} + */ + async detachCustomDomain_ (subdomain) { + const result = await this.#customDomainDialog(CUSTOM_DOMAIN_DIALOGS.detach, subdomain); + const domains = result?.domains; + return /** @type {import('./hosting/types.js').CustomDomain[]} */ (Array.isArray(domains) ? domains : []); + } + + /** + * Shows a custom domain dialog wherever this page can: the desktop's, a + * frame over the page, or a popup. Resolves the GUI's reply, or null. + * + * @param {CustomDomainDialog} dialog + * @param {string} subdomain + * @returns {Promise | null>} + */ + async #customDomainDialog (dialog, subdomain) { if ( this.env === 'app' ) { // An older desktop has no handler and would never reply; see // showFeedbackDialog. - if ( ! this.#guiOffers('custom-domains') ) { - throw new PuterJSError( - 'Custom domains are not available on this Puter desktop', - 'not_supported', - ); + if ( ! this.#guiOffers(dialog.feature) ) { + throw new PuterJSError(dialog.unsupported, 'not_supported'); } - const result = await this.#postMessageAsync('attachCustomDomain', { subdomain }); - return result?.domain ?? null; + return await this.#postMessageAsync(dialog.ipcMsg, { subdomain }); } if ( this.env !== 'web' ) { throw new PuterJSError( - 'puter.hosting.attach() needs a browser page or a Puter app', + `puter.hosting.${dialog.method}() needs a browser page or a Puter app`, 'not_available', ); } // Not awaited where no frame can show, so the popup opens within the click. if ( this.#canFrameForUser() ) { - const framed = await this.#showCustomDomainFrame(subdomain); - if ( framed ) return framed.domain; + const framed = await this.#showCustomDomainFrame(dialog, subdomain); + if ( framed ) return framed; } - const result = await this.#runGuiActionPopup({ - action: 'attach-custom-domain', + return await this.#runGuiActionPopup({ + action: dialog.action, params: { subdomain }, - replyMsg: 'customDomainAttached', + replyMsg: dialog.replyMsg, popupName: 'puter-custom-domain', }); - return /** @type {import('./hosting/types.js').CustomDomain | null} */ (result?.domain ?? null); } /** * The custom domain dialog in a frame over the page, for the page's * signed-in user, or null when the popup has to host it. One at a time: a - * call while one is open resolves no domain, as the desktop does. + * call while one is open resolves as if it was closed, as the desktop does. * + * @param {CustomDomainDialog} dialog * @param {string} subdomain - * @returns {Promise<{ domain: import('./hosting/types.js').CustomDomain | null } | null>} + * @returns {Promise | null>} */ - async #showCustomDomainFrame (subdomain) { - if ( this.#customDomainFrameOpen ) return { domain: null }; + async #showCustomDomainFrame (dialog, subdomain) { + if ( this.#customDomainFrameOpen ) return {}; this.#customDomainFrameOpen = true; try { const user = await this.#frameUser(); @@ -2843,13 +2894,13 @@ export class UIModule extends EventListener { const msgId = `${this.#messageID++}-${Math.random().toString(36).slice(2, 10)}`; return await showPopupFrame({ guiOrigin: puter.defaultGUIOrigin, - action: 'attach-custom-domain', + action: dialog.action, fragment: { user: user.uuid, subdomain, msg_id: msgId }, - title: 'Connect a custom domain', - closed: () => ({ domain: null }), + title: dialog.title, + closed: () => ({}), onMessage: (data, finish) => { - if ( data.msg !== 'customDomainAttached' || data.original_msg_id !== msgId ) return; - finish({ domain: /** @type {import('./hosting/types.js').CustomDomain | null} */ (data.domain ?? null) }); + if ( data.msg !== dialog.replyMsg || data.original_msg_id !== msgId ) return; + finish(data); }, }); } finally { diff --git a/src/puter-js/src/modules/Workers.deploy.test.js b/src/puter-js/src/modules/Workers.deploy.test.js index 632086366..cd746817e 100644 --- a/src/puter-js/src/modules/Workers.deploy.test.js +++ b/src/puter-js/src/modules/Workers.deploy.test.js @@ -96,7 +96,7 @@ describe('workers.create', () => { const sdk = makeSdk({ sandboxApp: { uid: 'app-bob', owner: { uuid: 'u-bob', username: 'bob' } } }); vi.stubGlobal('puter', sdk); await expect(new WorkersHandler(sdk).create('myworker', '/alice/worker.js')).rejects.toThrow( - 'Sandbox context is not owned by you! This worker\'s sandbox is currently owned by: bob', + 'The sandbox app \'sandbox-myworker\' belongs to another user. Choose another worker name, or pass { sandbox: false }.', ); expect(driverCalls).toEqual([]); expect(sdk.apps.create).not.toHaveBeenCalled(); diff --git a/src/puter-js/src/modules/hosting/detach.js b/src/puter-js/src/modules/hosting/detach.js new file mode 100644 index 000000000..681ecea0e --- /dev/null +++ b/src/puter-js/src/modules/hosting/detach.js @@ -0,0 +1,33 @@ +import { PuterJSError } from '../../lib/PuterJSError.js'; +import { normalizeSubdomain } from './lib/args.js'; + +/** @typedef {import('./types.js').CustomDomain} CustomDomain */ + +/** + * @overload + * @param {string} subdomain The site to remove domains from, e.g. `example` for + * `example.puter.site`. + * @returns {Promise} + */ +/** + * Opens a Puter dialog that lists the custom domains of `subdomain`, in which + * the user can remove them from their account. Needs no permission: the user + * decides in the dialog, and only the domains they removed are returned. + * + * Resolves an empty array when the user closes the dialog without removing + * any. Rejects with `invalid_argument` for a missing subdomain, + * `not_available` where no dialog can be shown (node, workers, the Puter + * desktop itself), and `not_supported` inside an older Puter desktop that has + * no such dialog. + * + * @this {import('./index.js').HostingModule} + * @param {string} subdomain + * @returns {Promise} + */ +export async function detach (subdomain) { + if ( typeof subdomain !== 'string' || subdomain.trim() === '' ) { + throw new PuterJSError('A subdomain is required', 'invalid_argument'); + } + const name = /** @type {string} */ (normalizeSubdomain(subdomain.trim())); + return await this.puter.ui.detachCustomDomain_(name); +} diff --git a/src/puter-js/src/modules/hosting/detach.test.js b/src/puter-js/src/modules/hosting/detach.test.js new file mode 100644 index 000000000..66297e009 --- /dev/null +++ b/src/puter-js/src/modules/hosting/detach.test.js @@ -0,0 +1,30 @@ +import { describe, expect, it, vi } from 'vitest'; +import { detach } from './detach.js'; + +const hostingWith = (detachCustomDomain_) => ({ + puter: { ui: { detachCustomDomain_ } }, +}); + +describe('hosting.detach', () => { + it('hands the subdomain to the dialog and returns the domains removed', async () => { + const dialog = vi.fn(async () => [{ hostname: 'www.example.com' }]); + await expect(detach.call(hostingWith(dialog), 'mysite')).resolves.toEqual([ + { hostname: 'www.example.com' }, + ]); + expect(dialog).toHaveBeenCalledWith('mysite'); + }); + + it('accepts a full hosted host', async () => { + const dialog = vi.fn(async () => []); + await detach.call(hostingWith(dialog), ' mysite.puter.site '); + expect(dialog).toHaveBeenCalledWith('mysite'); + }); + + it.each([undefined, '', ' ', 42])('rejects %j', async (value) => { + const dialog = vi.fn(); + await expect(detach.call(hostingWith(dialog), value)).rejects.toMatchObject({ + code: 'invalid_argument', + }); + expect(dialog).not.toHaveBeenCalled(); + }); +}); diff --git a/src/puter-js/src/modules/hosting/index.js b/src/puter-js/src/modules/hosting/index.js index 8ba51562f..6486b427b 100644 --- a/src/puter-js/src/modules/hosting/index.js +++ b/src/puter-js/src/modules/hosting/index.js @@ -2,6 +2,7 @@ import { PuterModule } from '../../lib/PuterModule.js'; import { attach } from './attach.js'; import { create } from './create.js'; import { del } from './delete.js'; +import { detach } from './detach.js'; import { get } from './get.js'; import { list } from './list.js'; import { update } from './update.js'; @@ -26,6 +27,7 @@ export class HostingModule extends PuterModule { get = get; delete = del; attach = attach; + detach = detach; /** @param {Puter} puter */ constructor (puter) { @@ -34,7 +36,7 @@ export class HostingModule extends PuterModule { const methods = /** @type {Record unknown>} */ ( /** @type {unknown} */ (this) ); - for ( const name of ['list', 'create', 'update', 'get', 'delete', 'attach'] ) { + for ( const name of ['list', 'create', 'update', 'get', 'delete', 'attach', 'detach'] ) { methods[name] = methods[name].bind(this); } } diff --git a/src/puter-js/src/modules/hosting/types.js b/src/puter-js/src/modules/hosting/types.js index 7fdacb101..d45125cb8 100644 --- a/src/puter-js/src/modules/hosting/types.js +++ b/src/puter-js/src/modules/hosting/types.js @@ -9,6 +9,18 @@ * (e.g. `example` in `example.puter.site`). * @property {import('../FSItem.js').FSItem} root_dir The root directory of the subdomain, where its * files are stored. + * @property {SiteCustomDomain[]} [custom_domains] The custom domains attached to the site, pending or + * active. Missing when Puter couldn't look them up. + */ + +/** + * A custom domain as a {@link Subdomain} lists it. + * + * @typedef {Object} SiteCustomDomain + * @property {string} uuid Unique identifier of the custom domain. + * @property {string} hostname The domain, e.g. `www.example.com`. + * @property {'pending' | 'active' | 'failed'} status `active` once DNS is set up and the + * domain serves the site. */ /** @@ -43,6 +55,8 @@ * domain, when Puter looked it up while adding it. * @property {string} [redirectFrom] The root domain forwarded to this `www.` hostname, when * the root domain couldn't be served directly. + * @property {string} [previousSite] The subdomain the domain served before, when the user + * moved it from another site in the [`attach()`](/Hosting/attach/) dialog. */ export {}; diff --git a/src/puter-js/tests/e2e/fixtures/attach-custom-domain.html b/src/puter-js/tests/e2e/fixtures/attach-custom-domain.html index 93f569a48..c5b25984b 100644 --- a/src/puter-js/tests/e2e/fixtures/attach-custom-domain.html +++ b/src/puter-js/tests/e2e/fixtures/attach-custom-domain.html @@ -2,7 +2,7 @@ - puter-js test fixture: hosting.attach + puter-js test fixture: hosting.attach and hosting.detach