diff --git a/src/backend/clients/database/SqliteDatabaseClient.test.ts b/src/backend/clients/database/SqliteDatabaseClient.test.ts
index 2bdb7d98d..bd0f338c9 100644
--- a/src/backend/clients/database/SqliteDatabaseClient.test.ts
+++ b/src/backend/clients/database/SqliteDatabaseClient.test.ts
@@ -27,7 +27,7 @@ import { DatabaseClientFactory } from './index.js';
import { SqliteDatabaseClient } from './SqliteDatabaseClient.js';
/** Highest schema version the migration table can reach. */
-const CURRENT_SCHEMA_VERSION = 100;
+const CURRENT_SCHEMA_VERSION = 101;
/**
* These suites migrate real files on disk. Idle they finish in well under a
diff --git a/src/backend/clients/database/SqliteDatabaseClient.ts b/src/backend/clients/database/SqliteDatabaseClient.ts
index 299fc93d8..54d2af100 100644
--- a/src/backend/clients/database/SqliteDatabaseClient.ts
+++ b/src/backend/clients/database/SqliteDatabaseClient.ts
@@ -139,6 +139,7 @@ const AVAILABLE_MIGRATIONS: [number, string[]][] = [
[97, ['0102_notification-scope-id-index.sql']],
[98, ['0103_share-entry-owner-backfill.sql']],
[99, ['0104_signup-tls-fingerprint.sql']],
+ [100, ['0105_sessions_kind_debug_app.sql']],
];
export class SqliteDatabaseClient extends AbstractDatabaseClient {
diff --git a/src/backend/clients/database/migrations/mysql/mysql_mig_59.sql b/src/backend/clients/database/migrations/mysql/mysql_mig_59.sql
new file mode 100644
index 000000000..fb1f2bf15
--- /dev/null
+++ b/src/backend/clients/database/migrations/mysql/mysql_mig_59.sql
@@ -0,0 +1,46 @@
+-- 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 .
+
+-- Add 'debug_app' to the `sessions.kind` ENUM: a short-lived app session an
+-- operator creates on a user's behalf. Mirrors SQLite migration 0105.
+--
+-- Idempotent: guarded against COLUMN_TYPE so re-running the directory is a
+-- no-op once 'debug_app' is in the ENUM.
+
+DROP PROCEDURE IF EXISTS _puter_sessions_kind_debug_app;
+DELIMITER //
+CREATE PROCEDURE _puter_sessions_kind_debug_app()
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
+ WHERE TABLE_SCHEMA = DATABASE()
+ AND TABLE_NAME = 'sessions'
+ AND COLUMN_NAME = 'kind'
+ AND FIND_IN_SET('debug_app', REPLACE(REPLACE(REPLACE(COLUMN_TYPE, 'enum(', ''), ')', ''), '''', '')) > 0
+ ) THEN
+ ALTER TABLE `sessions`
+ MODIFY COLUMN `kind`
+ ENUM('web', 'app', 'access_token', 'asset', 'worker', 'debug_app')
+ NOT NULL DEFAULT 'web',
+ ALGORITHM=INSTANT;
+ END IF;
+END//
+DELIMITER ;
+
+CALL _puter_sessions_kind_debug_app();
+
+DROP PROCEDURE IF EXISTS _puter_sessions_kind_debug_app;
diff --git a/src/backend/clients/database/migrations/postgres/postgres_mig_48.sql b/src/backend/clients/database/migrations/postgres/postgres_mig_48.sql
new file mode 100644
index 000000000..897c0134c
--- /dev/null
+++ b/src/backend/clients/database/migrations/postgres/postgres_mig_48.sql
@@ -0,0 +1,24 @@
+-- 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 .
+
+-- Add 'debug_app' to the `sessions.kind` CHECK constraint: a short-lived app
+-- session an operator creates on a user's behalf. Mirrors SQLite migration
+-- 0105. Drop-then-add keeps it idempotent across directory replays.
+
+ALTER TABLE sessions DROP CONSTRAINT IF EXISTS sessions_kind_check;
+ALTER TABLE sessions ADD CONSTRAINT sessions_kind_check
+ CHECK (kind IN ('web', 'app', 'access_token', 'asset', 'worker', 'debug_app'));
diff --git a/src/backend/clients/database/migrations/sqlite/0105_sessions_kind_debug_app.sql b/src/backend/clients/database/migrations/sqlite/0105_sessions_kind_debug_app.sql
new file mode 100644
index 000000000..c8b078485
--- /dev/null
+++ b/src/backend/clients/database/migrations/sqlite/0105_sessions_kind_debug_app.sql
@@ -0,0 +1,89 @@
+-- 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 .
+
+-- Add 'debug_app' to the `kind` CHECK constraint on `sessions`. Mirrors the
+-- MySQL ENUM extension in mysql_mig_59.
+--
+-- SQLite cannot ALTER a CHECK constraint in place, so we follow the same
+-- table-rebuild as migration 0056: create `sessions_new` with the corrected
+-- constraint, copy rows, drop the old table, rename, then recreate every
+-- index that lived on the original.
+
+CREATE TABLE `sessions_new` (
+ "id" INTEGER PRIMARY KEY AUTOINCREMENT,
+ "user_id" INTEGER NOT NULL,
+ "uuid" TEXT NOT NULL,
+ "meta" JSON DEFAULT NULL,
+ "created_at" INTEGER DEFAULT 0,
+ "last_activity" INTEGER DEFAULT 0,
+ "kind" TEXT NOT NULL DEFAULT 'web'
+ CHECK (`kind` IN ('web', 'app', 'access_token', 'asset', 'worker', 'debug_app')),
+ "label" TEXT,
+ "parent_session_id" TEXT,
+ "last_ip" TEXT,
+ "last_user_agent" TEXT,
+ "revoked_at" INTEGER,
+ "expires_at" INTEGER,
+ "app_uid" TEXT,
+ "legacy_token_uid" TEXT,
+ "created_via" TEXT,
+ "auth_id" TEXT,
+ "access_token_uid" TEXT,
+ FOREIGN KEY("user_id") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+INSERT INTO `sessions_new` (
+ `id`, `user_id`, `uuid`, `meta`, `created_at`, `last_activity`,
+ `kind`, `label`, `parent_session_id`, `last_ip`, `last_user_agent`,
+ `revoked_at`, `expires_at`, `app_uid`, `legacy_token_uid`,
+ `created_via`, `auth_id`, `access_token_uid`
+)
+SELECT
+ `id`, `user_id`, `uuid`, `meta`, `created_at`, `last_activity`,
+ `kind`, `label`, `parent_session_id`, `last_ip`, `last_user_agent`,
+ `revoked_at`, `expires_at`, `app_uid`, `legacy_token_uid`,
+ `created_via`, `auth_id`, `access_token_uid`
+FROM `sessions`;
+
+DROP TABLE `sessions`;
+
+ALTER TABLE `sessions_new` RENAME TO `sessions`;
+
+CREATE INDEX IF NOT EXISTS `idx_sessions_user_revoked`
+ ON `sessions` (`user_id`, `revoked_at`);
+
+CREATE INDEX IF NOT EXISTS `idx_sessions_parent`
+ ON `sessions` (`parent_session_id`);
+
+CREATE UNIQUE INDEX IF NOT EXISTS `idx_sessions_user_app_active`
+ ON `sessions` (`user_id`, `app_uid`)
+ WHERE `kind` = 'app' AND `revoked_at` IS NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS `idx_sessions_legacy_token_active`
+ ON `sessions` (`legacy_token_uid`)
+ WHERE `legacy_token_uid` IS NOT NULL AND `revoked_at` IS NULL;
+
+CREATE INDEX IF NOT EXISTS `idx_sessions_kind_user`
+ ON `sessions` (`kind`, `user_id`);
+
+CREATE INDEX IF NOT EXISTS `idx_sessions_access_token_uid`
+ ON `sessions` (`access_token_uid`)
+ WHERE `access_token_uid` IS NOT NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS `idx_sessions_user_worker_active`
+ ON `sessions` (`user_id`, IFNULL(`app_uid`, ''), json_extract(`meta`, '$.worker_name'))
+ WHERE `kind` = 'worker' AND `revoked_at` IS NULL;
diff --git a/src/backend/services/auth/AuthService.test.ts b/src/backend/services/auth/AuthService.test.ts
index 4432d1d27..68981f8bf 100644
--- a/src/backend/services/auth/AuthService.test.ts
+++ b/src/backend/services/auth/AuthService.test.ts
@@ -124,6 +124,106 @@ describe('AuthService (integration)', () => {
return u;
};
+ const makeDebugApp = async (): Promise => {
+ const uid = `app-${uuidv4()}`;
+ await server.clients.db.write(
+ 'INSERT INTO `apps` (`uid`, `name`, `title`, `index_url`, `owner_user_id`) VALUES (?, ?, ?, ?, ?)',
+ [uid, `n-${uid}`, `t-${uid}`, `https://${uid}.example/`, 1],
+ );
+ return uid;
+ };
+
+ describe('createDebugAppToken', () => {
+ it('mints an app-under-user token on its own expiring, hidden session', async () => {
+ const user = await makeUser();
+ const appUid = await makeDebugApp();
+ const { token, sessionUuid, expiresAt } =
+ await authService.createDebugAppToken(
+ user as never,
+ { uid: appUid },
+ {
+ ttlSeconds: 3600,
+ label: 'debug',
+ meta: { debug_admin_username: 'op' },
+ },
+ );
+
+ // Its own dedicated row, not reusing a kind='app' session.
+ const row = (
+ (await server.clients.db.read(
+ 'SELECT `kind`, `app_uid`, `expires_at` FROM `sessions` WHERE `uuid` = ?',
+ [sessionUuid],
+ )) as Array>
+ )[0];
+ expect(row?.kind).toBe('debug_app');
+ expect(row?.app_uid).toBe(appUid);
+ expect(Number(row?.expires_at)).toBeGreaterThan(
+ Math.floor(Date.now() / 1000) + 3500,
+ );
+ expect(expiresAt).toBeGreaterThan(Date.now() + 3500 * 1000);
+
+ // Authenticates as the user acting in the app.
+ const { actor } = await authService.authenticate(token);
+ expect(actor?.user.uuid).toBe(user.uuid);
+ expect(actor?.app?.uid).toBe(appUid);
+
+ // Hidden from the user's own session list.
+ const listed = await authService.listSessions({
+ user: { id: user.id },
+ } as Actor);
+ expect(listed.some((s) => s.uuid === sessionUuid)).toBe(false);
+ });
+
+ it('carries an exp, so the token lapses on its own', async () => {
+ const user = await makeUser();
+ const appUid = await makeDebugApp();
+ const { token } = await authService.createDebugAppToken(
+ user as never,
+ { uid: appUid },
+ { ttlSeconds: 1234 },
+ );
+ const claims = server.services.token.verify('auth', token) as {
+ iat: number;
+ exp: number;
+ };
+ expect(claims.exp - claims.iat).toBe(1234);
+ });
+
+ it('records no activity for the user', async () => {
+ const user = await makeUser();
+ const appUid = await makeDebugApp();
+ const { token } = await authService.createDebugAppToken(
+ user as never,
+ { uid: appUid },
+ { ttlSeconds: 600 },
+ );
+ const touch = vi.spyOn(server.stores.session, 'touch');
+ try {
+ const ctx = { ip: '9.9.9.9', userAgent: 'debug' };
+ expect(
+ (await authService.authenticate(token, ctx)).actor,
+ ).toBeTruthy();
+ expect(touch).not.toHaveBeenCalled();
+ } finally {
+ touch.mockRestore();
+ }
+ });
+
+ it('is evicted by a password reset', async () => {
+ const user = await makeUser();
+ const appUid = await makeDebugApp();
+ const { token } = await authService.createDebugAppToken(
+ user as never,
+ { uid: appUid },
+ { ttlSeconds: 600 },
+ );
+ await authService.revokeInteractiveSessionsForUserId(user.id);
+ const result = await authService.authenticate(token);
+ expect(result.actor).toBeUndefined();
+ expect(result.reauth).toEqual({ reason: 'session_revoked' });
+ });
+ });
+
describe('authenticateFromToken', () => {
it('returns null for a malformed/unverifiable token', async () => {
const actor = await authService.authenticateFromToken('not-a-jwt');
diff --git a/src/backend/services/auth/AuthService.ts b/src/backend/services/auth/AuthService.ts
index 5293796eb..97706cbd4 100644
--- a/src/backend/services/auth/AuthService.ts
+++ b/src/backend/services/auth/AuthService.ts
@@ -31,6 +31,7 @@ import { awaitLater } from '../../util/concurrency.js';
import { appGenerationStart } from '../../util/appGeneration.js';
import {
ASSET_WINDOW_SECONDS,
+ DEBUG_APP_SESSION_KIND,
GODMODE_TOKEN_MAX_AGE_SECONDS,
GODMODE_TOKEN_WINDOW_SECONDS,
WEB_WINDOW_SECONDS,
@@ -787,6 +788,8 @@ export class AuthService extends PuterService {
const visible = [...live.values()].filter(
(row) =>
row.kind !== 'asset' &&
+ // Operator-created debug sessions are never the user's own.
+ row.kind !== DEBUG_APP_SESSION_KIND &&
(row.kind !== 'access_token' ||
!row.parent_session_id ||
live.has(row.parent_session_id)),
@@ -1075,7 +1078,12 @@ export class AuthService extends PuterService {
});
await this.#revokeCascades(
rows
- .filter((row) => row.kind === 'web' || row.kind === 'app')
+ .filter(
+ (row) =>
+ row.kind === 'web' ||
+ row.kind === 'app' ||
+ row.kind === DEBUG_APP_SESSION_KIND,
+ )
.map((row) => row.uuid as string),
);
}
@@ -1858,6 +1866,49 @@ export class AuthService extends PuterService {
});
}
+ /**
+ * An app token acting as `user` in `app` on its own `debug_app` session,
+ * which expires after `ttlSeconds` and never touches the user's real
+ * sessions. The caller authorizes who may ask; `meta` lands on the row.
+ */
+ async createDebugAppToken(
+ user: UserRow,
+ app: { uid: string },
+ opts: {
+ ttlSeconds: number;
+ label?: string | null;
+ meta?: Record;
+ },
+ ): Promise<{ token: string; sessionUuid: string; expiresAt: number }> {
+ const authId = this.#authIdFor(user);
+ const expiresAtSeconds = nowSeconds() + opts.ttlSeconds;
+ const session = await this.stores.session.create(user.id as number, {
+ kind: DEBUG_APP_SESSION_KIND,
+ app_uid: app.uid,
+ expires_at: expiresAtSeconds,
+ auth_id: authId,
+ label: opts.label ?? null,
+ meta: opts.meta ?? {},
+ });
+ const token = this.services.token.sign(
+ 'auth',
+ {
+ type: 'app-under-user',
+ version: '2',
+ user_uid: user.uuid,
+ app_uid: app.uid,
+ session_uid: session.uuid,
+ auth_id: authId,
+ },
+ { expiresIn: opts.ttlSeconds },
+ );
+ return {
+ token,
+ sessionUuid: session.uuid as string,
+ expiresAt: expiresAtSeconds * 1000,
+ };
+ }
+
/**
* Mint the full-access token a godmode app runs on. Only the desktop's own
* web session may ask, and only asking extends it: using the token never
@@ -2760,7 +2811,11 @@ export class AuthService extends PuterService {
// An events handler's calls are background work, not the user being
// active, and its session never expires, so they record no activity.
- if (decoded.worker_name !== EVENTS_WORKER_SESSION_NAME)
+ // Nor do calls on a debug session, which aren't the user's own.
+ if (
+ decoded.worker_name !== EVENTS_WORKER_SESSION_NAME &&
+ session.kind !== DEBUG_APP_SESSION_KIND
+ )
void this.#touchSession(session.uuid, user.id, ctx);
const actor = this.#buildAppUnderUserActor(user, app, session);
diff --git a/src/backend/stores/session/SessionStore.js b/src/backend/stores/session/SessionStore.js
index 908030825..4332d554b 100644
--- a/src/backend/stores/session/SessionStore.js
+++ b/src/backend/stores/session/SessionStore.js
@@ -60,6 +60,9 @@ export const APP_WINDOW_SECONDS = 365 * 24 * 60 * 60; // 1y
export const WORKER_WINDOW_SECONDS = 99 * 365 * 24 * 60 * 60; // 99y (virtually infinite);
export const ASSET_WINDOW_SECONDS = 7 * 24 * 60 * 60; // 7 days
+// An app session created on a user's behalf for debugging: hard expiry, never
+// slid, and hidden from the user's own session list.
+export const DEBUG_APP_SESSION_KIND = 'debug_app';
// A godmode app's token lapses at most this long after the desktop last asked
// for it, so a closed desktop's tokens die on their own. A token past the max
// age is never renewed again; the next ask replaces it and revokes the old one.
@@ -1004,6 +1007,18 @@ export class SessionStore extends PuterStore {
return result?.affectedRows ?? result?.changes ?? 0;
}
+ /**
+ * Hard-delete debug app sessions that expired before `cutoff` (unix
+ * seconds). Cached copies still read as expired, so need no invalidation.
+ */
+ async deleteExpiredDebugAppSessions(cutoff) {
+ const result = await this.clients.db.write(
+ 'DELETE FROM `sessions` WHERE `kind` = ? AND `expires_at` IS NOT NULL AND `expires_at` < ?',
+ [DEBUG_APP_SESSION_KIND, cutoff],
+ );
+ return result?.affectedRows ?? result?.changes ?? 0;
+ }
+
/**
* Bump `last_activity` and slide `expires_at` per the row's kind in a
* single UPDATE. Sliding kinds (web/app/asset) get their `expires_at`
diff --git a/src/backend/stores/session/SessionStore.test.ts b/src/backend/stores/session/SessionStore.test.ts
index 6a5a7fb6a..dffd83071 100644
--- a/src/backend/stores/session/SessionStore.test.ts
+++ b/src/backend/stores/session/SessionStore.test.ts
@@ -357,6 +357,28 @@ describe('SessionStore', () => {
});
});
+ describe('deleteExpiredDebugAppSessions', () => {
+ it('deletes only expired debug_app rows', async () => {
+ const user = await makeUser();
+ const now = Math.floor(Date.now() / 1000);
+ const mk = async (kind: string, expiresAt: number | null) => {
+ const { uuid } = await target.create(user.id, {
+ kind,
+ expires_at: expiresAt,
+ });
+ return uuid;
+ };
+ const expired = await mk('debug_app', now - 10);
+ const live = await mk('debug_app', now + 3600);
+ const otherKind = await mk('app', now - 10);
+
+ expect(await target.deleteExpiredDebugAppSessions(now)).toBe(1);
+ expect(await rawRow(expired)).toBeNull();
+ expect(await rawRow(live)).not.toBeNull();
+ expect(await rawRow(otherKind)).not.toBeNull();
+ });
+ });
+
describe('revokeCascade', () => {
it('revokes the root session and all child sessions', async () => {
const user = await makeUser();