/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
import {
isAccessTokenActor,
isAccountContext,
isAppActor,
viaWorkerOf,
} from '../../core/actor.js';
import { HttpError } from '../../core/http/HttpError.js';
import {
APP_ICON_SIZES,
ICON_DATA_URL_MIME_ALLOWLIST,
isTrustedIconHost,
} from '../../util/appIcon.js';
import { toAppReadView } from '../../util/appView.js';
import { PuterController } from '../types.js';
import DEFAULT_APP_ICON from './default-app-icon.js';
/**
* Desktop boot reads the app list and individual app records repeatedly, so the
* ceiling is set well above normal boot traffic and exists to catch a runaway
* client rather than to pace one.
*
* "Repeatedly" is the operative word: an app record is read on launch, on
* permission checks, and again by anything resolving an app by name, so these
* accumulate against whatever else a session is doing rather than arriving on
* their own. Sized for a session working hard, not for a person clicking.
*/
const APP_READ_LIMIT = {
scope: 'app-read',
limit: 1_800,
window: 60_000,
key: 'user',
};
/**
* Unauthenticated icon serving; no actor to key on, so the bucket is the
* address — and an address is a NAT, a campus or a carrier gateway that can
* hold hundreds of desktops. Each dashboard load pulls its app icons at once,
* so a single burst from one network is already thousands of requests.
* Responses are publicly cacheable and usually a redirect, so the ceiling is
* not protecting bandwidth; it is there so a client looping on a broken icon
* can't spin unbounded.
*/
const APP_ICON_LIMIT = {
scope: 'app-icon',
limit: 12_000,
window: 60_000,
key: 'ip',
};
// Shared by `GET /apps/:name` (pipe-separated) and `POST /query/app`, which
// both fan out one lookup per name.
const APP_LOOKUP_MAX_ENTRIES = 200;
const APP_LOOKUP_MAX_SELECTOR_LEN = 200;
/** What `/apps/:name` reports for an app no launch gate applies to. */
const PUBLIC_APP_ACCESS = { hasAccess: true, checkedBy: 'core/public-app' };
/**
* REST endpoints for app management. CRUD goes through the apps driver; the
* read routes use AppService for visibility and views, as the driver does.
*/
export class AppController extends PuterController {
// In-flight background app-open writes. Tracked only so tests and
// shutdown can wait for them — the request path never does.
#pendingOpenWrites = new Set();
/**
* Record an app open. `app_opens` is analytics: it backs the recent-apps
* list and the open counters, and no response field is derived from it. The
* client posts this without awaiting and updates its own recent list
* optimistically, so holding a response open for a primary write only added
* latency to the launch that write is measuring.
*
* Failures are logged, never surfaced — a dropped stat must not turn into a
* failed app open.
*
* @param {string} appUid
* @param {number} userId
* @returns {Promise} Settles when the write and event emit finish
*/
#recordAppOpen(appUid, userId) {
const ts = Math.floor(Date.now() / 1000);
const work = (async () => {
try {
await this.stores.app.recordOpen(appUid, userId, ts);
} catch (e) {
console.warn('[rao] insert failed:', e);
}
try {
this.clients.event?.emitAndWait(
'app.opened',
{ app_uid: appUid, user_id: userId, ts },
{},
);
} catch {
// event emission best-effort
}
})();
this.#pendingOpenWrites.add(work);
work.finally(() => this.#pendingOpenWrites.delete(work));
return work;
}
/** Await every in-flight app-open write. */
async drainPendingAppOpens() {
await Promise.allSettled([...this.#pendingOpenWrites]);
}
registerRoutes(
/** @type {import('../../core/http/PuterRouter').PuterRouter} */ router,
) {
// GET /apps — list apps owned by the current user
router.get(
'/apps',
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const apps = await this.drivers.apps.select({
predicate: ['user-can-edit'],
});
res.json(apps);
},
);
// GET /apps/nameAvailable?name=foo
router.get(
'/apps/nameAvailable',
{
subdomain: 'api',
requireAuth: true,
// Answers "does this name exist?" for any name, so it is a
// name-enumeration oracle however cheap it is to serve.
// Mirrors the `isNameAvailable` budget on AppDriver.
rateLimit: {
scope: 'app-name-available',
limit: 60,
window: 60_000,
key: 'user',
},
},
async (req, res) => {
const name = req.query?.name;
if (!name || typeof name !== 'string') {
throw new HttpError(
400,
'Missing or invalid `name` query param',
{ legacyCode: 'bad_request' },
);
}
const available = await this.drivers.apps.isNameAvailable(name);
res.json({ name, available });
},
);
// POST /rao — record a recent app open. When an app-under-user
// actor calls this, the app id is already on the token — clients
// don't re-send it in the body. Fall back to the acting app's uid
// before 400-ing for a missing body field.
//
// Authorization: only two callers are trusted to report opens —
// 1. the account acting as itself (plain session or full-access
// token), e.g. the GUI launching apps on behalf of the user;
// 2. the app-under-user actor for the app being reported.
// Everything else — scoped and app-issued access tokens, asset
// tokens, app actors reporting for a *different* app — is denied,
// otherwise any authenticated party could inflate another app's
// open count.
router.post(
'/rao',
{
subdomain: 'api',
requireAuth: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const actor = req.actor;
// Server-side code running as the account (a worker, an events
// handler) is not someone opening the app. Answered as success
// so deployed workers, which still ask, don't log a failure.
if (viaWorkerOf(actor)) {
res.json({});
return;
}
const bodyAppUid = req.body?.app_uid;
const callerAppUid = actor?.effectiveApp?.uid;
const app_uid =
typeof bodyAppUid === 'string' && bodyAppUid.length > 0
? bodyAppUid
: callerAppUid;
if (!app_uid || typeof app_uid !== 'string') {
throw new HttpError(400, 'Missing or invalid `app_uid`', {
legacyCode: 'bad_request',
});
}
// Shared credentials shouldn't drive analytics counters.
if (isAccessTokenActor(actor) && !isAccountContext(actor)) {
throw new HttpError(
403,
'This token cannot report app opens',
{ legacyCode: 'forbidden' },
);
}
if (isAppActor(actor) && app_uid !== callerAppUid) {
throw new HttpError(
403,
'App actors can only report opens for their own app',
{ legacyCode: 'forbidden' },
);
}
const app = await this.stores.app.getByUid(app_uid);
if (!app)
throw new HttpError(404, 'App not found', {
legacyCode: 'not_found',
});
// Validation and authorization are settled by this point, so
// the caller learns the outcome now and the stats write lands
// on its own. See `#recordAppOpen`.
this.#recordAppOpen(app_uid, req.actor.user.id);
res.json({});
},
);
// GET /apps/:name — returns the app(s) by name.
// Supports pipe-separated names for batch lookup: /apps/foo|bar|baz
router.get(
'/apps/:name',
{
subdomain: 'api',
requireUserActor: true,
allowFullAccessToken: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const raw = req.params.name;
const names = raw.split('|').filter(Boolean);
if (names.length > APP_LOOKUP_MAX_ENTRIES) {
throw new HttpError(
400,
`at most ${APP_LOOKUP_MAX_ENTRIES} app names per request`,
{ legacyCode: 'bad_request' },
);
}
const actor = req.actor;
const appsByName = await this.stores.app.getByNames(
names.filter(
(name) => name.length <= APP_LOOKUP_MAX_SELECTOR_LEN,
),
);
const readable = await this.services.app.filterReadable(
[...new Set(appsByName.values())],
actor,
);
const views = await this.services.app.views(readable, actor, {
source: 'appsRoute',
});
const shapedByUid = new Map(
readable.map((app, i) => {
const shaped = toAppReadView(app, views[i], {
viewer: actor.user,
});
shaped.privateAccess ??= PUBLIC_APP_ACCESS;
return [app.uid, shaped];
}),
);
const results = names.map(
(name) =>
shapedByUid.get(appsByName.get(name)?.uid) ?? null,
);
// Single-name requests return the app directly; batch returns an array
if (names.length === 1) {
const single = results[0];
if (!single)
throw new HttpError(404, 'App not found', {
legacyCode: 'not_found',
});
return res.json(single);
}
res.json(results);
},
);
// -- POST /query/app ----------------------------------------
// Batch marketplace-style lookup by name or UID.
//
// Access rules: only apps the caller has a legitimate reason to
// see are returned — public (`approved_for_listing`), owned by
// the caller, or readable per `AppService.filterReadable` (for
// protected apps, a granted permission). Everything else is
// silently skipped so the endpoint can't be used to enumerate
// existence of private / unapproved apps by guessing names.
//
// Response shape is intentionally narrow and mirrors v1 — no
// internal identifiers (mysql `id`, `owner_user_id`), no
// `index_url`, no admin flags. Developer `metadata` is
// included for public/owned apps only, consistent with
// marketplace semantics.
router.post(
'/query/app',
{
subdomain: 'api',
requireAuth: true,
rateLimit: APP_READ_LIMIT,
},
async (req, res) => {
const appList = Array.isArray(req.body) ? req.body : [];
if (appList.length > APP_LOOKUP_MAX_ENTRIES) {
throw new HttpError(
400,
`request body must contain at most ${APP_LOOKUP_MAX_ENTRIES} selectors`,
{ legacyCode: 'bad_request' },
);
}
const actor = req.actor;
const selectors = appList.filter(
(selector) =>
typeof selector === 'string' &&
selector.length > 0 &&
selector.length <= APP_LOOKUP_MAX_SELECTOR_LEN,
);
const isUid = (selector) => selector.startsWith('app-');
const [byUid, byName] = await Promise.all([
this.stores.app.getByUids(selectors.filter(isUid)),
this.stores.app.getByNames(
selectors.filter((s) => !isUid(s)),
),
]);
const found = selectors
.map((s) => (isUid(s) ? byUid.get(s) : byName.get(s)))
.filter(Boolean);
// Unapproved apps the caller doesn't own surface only when
// the caller may read them (one batched grant check).
const isListed = (app) =>
app.owner_user_id === actor.user?.id ||
Boolean(app.approved_for_listing);
const readable = new Set(
await this.services.app.filterReadable(
[...new Set(found.filter((app) => !isListed(app)))],
actor,
),
);
const visible = found.filter(
(app) => isListed(app) || readable.has(app),
);
const filetypesByAppId =
await this.stores.app.getFiletypeAssociationsByIds(
visible.map((app) => app.id),
);
const results = visible.map((app) => ({
uuid: app.uid,
name: app.name,
title: app.title,
description: app.description,
metadata: app.metadata,
tags:
typeof app.tags === 'string' ? app.tags.split(',') : [],
created: app.timestamp,
associations: filetypesByAppId.get(app.id) ?? [],
}));
res.json(results);
},
);
// -- GET /app-icon/:app_uid(/:size) -------------------------
// Serve app icon — data URL decoded inline, HTTP URL redirected.
//
// ⚠ FLAG: Missing sharp-based resize pipeline; serves the original.
// Neutering headers for any response that echoes an icon byte
// stream on the main origin. `image/svg+xml` is in our MIME
// allow-list — it's a legitimate image format, and our own
// default icon is SVG — but SVGs can carry `